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)
170 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
171 EST = EST_BasicNoexcept;
174 // If this function can throw any exceptions, make a note of that.
180 // FIXME: If the call to this decl is using any of its default arguments, we
181 // need to search them for potentially-throwing calls.
182 // If this function has a basic noexcept, it doesn't affect the outcome.
183 case EST_BasicNoexcept:
185 // If we're still at noexcept(true) and there's a nothrow() callee,
186 // change to that specification.
187 case EST_DynamicNone:
188 if (ComputedEST == EST_BasicNoexcept)
189 ComputedEST = EST_DynamicNone;
191 // Check out noexcept specs.
192 case EST_ComputedNoexcept:
194 FunctionProtoType::NoexceptResult NR =
195 Proto->getNoexceptSpec(Self->Context);
196 assert(NR != FunctionProtoType::NR_NoNoexcept &&
197 "Must have noexcept result for EST_ComputedNoexcept.");
198 assert(NR != FunctionProtoType::NR_Dependent &&
199 "Should not generate implicit declarations for dependent cases, "
200 "and don't know how to handle them anyway.");
201 // noexcept(false) -> no spec on the new function
202 if (NR == FunctionProtoType::NR_Throw) {
204 ComputedEST = EST_None;
206 // noexcept(true) won't change anything either.
212 assert(EST == EST_Dynamic && "EST case not considered earlier.");
213 assert(ComputedEST != EST_None &&
214 "Shouldn't collect exceptions when throw-all is guaranteed.");
215 ComputedEST = EST_Dynamic;
216 // Record the exceptions in this function's exception specification.
217 for (const auto &E : Proto->exceptions())
218 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
219 Exceptions.push_back(E);
222 void Sema::ImplicitExceptionSpecification::CalledExpr(Expr *E) {
223 if (!E || ComputedEST == EST_MSAny)
228 // C++0x [except.spec]p14:
229 // [An] implicit exception-specification specifies the type-id T if and
230 // only if T is allowed by the exception-specification of a function directly
231 // invoked by f's implicit definition; f shall allow all exceptions if any
232 // function it directly invokes allows all exceptions, and f shall allow no
233 // exceptions if every function it directly invokes allows no exceptions.
235 // Note in particular that if an implicit exception-specification is generated
236 // for a function containing a throw-expression, that specification can still
237 // be noexcept(true).
239 // Note also that 'directly invoked' is not defined in the standard, and there
240 // is no indication that we should only consider potentially-evaluated calls.
242 // Ultimately we should implement the intent of the standard: the exception
243 // specification should be the set of exceptions which can be thrown by the
244 // implicit definition. For now, we assume that any non-nothrow expression can
245 // throw any exception.
247 if (Self->canThrow(E))
248 ComputedEST = EST_None;
252 Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
253 SourceLocation EqualLoc) {
254 if (RequireCompleteType(Param->getLocation(), Param->getType(),
255 diag::err_typecheck_decl_incomplete_type)) {
256 Param->setInvalidDecl();
260 // C++ [dcl.fct.default]p5
261 // A default argument expression is implicitly converted (clause
262 // 4) to the parameter type. The default argument expression has
263 // the same semantic constraints as the initializer expression in
264 // a declaration of a variable of the parameter type, using the
265 // copy-initialization semantics (8.5).
266 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
268 InitializationKind Kind = InitializationKind::CreateCopy(Param->getLocation(),
270 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
271 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
272 if (Result.isInvalid())
274 Arg = Result.getAs<Expr>();
276 CheckCompletedExpr(Arg, EqualLoc);
277 Arg = MaybeCreateExprWithCleanups(Arg);
279 // Okay: add the default argument to the parameter
280 Param->setDefaultArg(Arg);
282 // We have already instantiated this parameter; provide each of the
283 // instantiations with the uninstantiated default argument.
284 UnparsedDefaultArgInstantiationsMap::iterator InstPos
285 = UnparsedDefaultArgInstantiations.find(Param);
286 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
287 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
288 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
290 // We're done tracking this parameter's instantiations.
291 UnparsedDefaultArgInstantiations.erase(InstPos);
297 /// ActOnParamDefaultArgument - Check whether the default argument
298 /// provided for a function parameter is well-formed. If so, attach it
299 /// to the parameter declaration.
301 Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
303 if (!param || !DefaultArg)
306 ParmVarDecl *Param = cast<ParmVarDecl>(param);
307 UnparsedDefaultArgLocs.erase(Param);
309 // Default arguments are only permitted in C++
310 if (!getLangOpts().CPlusPlus) {
311 Diag(EqualLoc, diag::err_param_default_argument)
312 << DefaultArg->getSourceRange();
313 Param->setInvalidDecl();
317 // Check for unexpanded parameter packs.
318 if (DiagnoseUnexpandedParameterPack(DefaultArg, UPPC_DefaultArgument)) {
319 Param->setInvalidDecl();
323 // C++11 [dcl.fct.default]p3
324 // A default argument expression [...] shall not be specified for a
326 if (Param->isParameterPack()) {
327 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
328 << DefaultArg->getSourceRange();
332 // Check that the default argument is well-formed
333 CheckDefaultArgumentVisitor DefaultArgChecker(DefaultArg, this);
334 if (DefaultArgChecker.Visit(DefaultArg)) {
335 Param->setInvalidDecl();
339 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
342 /// ActOnParamUnparsedDefaultArgument - We've seen a default
343 /// argument for a function parameter, but we can't parse it yet
344 /// because we're inside a class definition. Note that this default
345 /// argument will be parsed later.
346 void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
347 SourceLocation EqualLoc,
348 SourceLocation ArgLoc) {
352 ParmVarDecl *Param = cast<ParmVarDecl>(param);
353 Param->setUnparsedDefaultArg();
354 UnparsedDefaultArgLocs[Param] = ArgLoc;
357 /// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
358 /// the default argument for the parameter param failed.
359 void Sema::ActOnParamDefaultArgumentError(Decl *param,
360 SourceLocation EqualLoc) {
364 ParmVarDecl *Param = cast<ParmVarDecl>(param);
365 Param->setInvalidDecl();
366 UnparsedDefaultArgLocs.erase(Param);
367 Param->setDefaultArg(new(Context)
368 OpaqueValueExpr(EqualLoc,
369 Param->getType().getNonReferenceType(),
373 /// CheckExtraCXXDefaultArguments - Check for any extra default
374 /// arguments in the declarator, which is not a function declaration
375 /// or definition and therefore is not permitted to have default
376 /// arguments. This routine should be invoked for every declarator
377 /// that is not a function declaration or definition.
378 void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
379 // C++ [dcl.fct.default]p3
380 // A default argument expression shall be specified only in the
381 // parameter-declaration-clause of a function declaration or in a
382 // template-parameter (14.1). It shall not be specified for a
383 // parameter pack. If it is specified in a
384 // parameter-declaration-clause, it shall not occur within a
385 // declarator or abstract-declarator of a parameter-declaration.
386 bool MightBeFunction = D.isFunctionDeclarationContext();
387 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
388 DeclaratorChunk &chunk = D.getTypeObject(i);
389 if (chunk.Kind == DeclaratorChunk::Function) {
390 if (MightBeFunction) {
391 // This is a function declaration. It can have default arguments, but
392 // keep looking in case its return type is a function type with default
394 MightBeFunction = false;
397 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
399 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
400 if (Param->hasUnparsedDefaultArg()) {
401 std::unique_ptr<CachedTokens> Toks =
402 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
404 if (Toks->size() > 1)
405 SR = SourceRange((*Toks)[1].getLocation(),
406 Toks->back().getLocation());
408 SR = UnparsedDefaultArgLocs[Param];
409 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
411 } else if (Param->getDefaultArg()) {
412 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
413 << Param->getDefaultArg()->getSourceRange();
414 Param->setDefaultArg(nullptr);
417 } else if (chunk.Kind != DeclaratorChunk::Paren) {
418 MightBeFunction = false;
423 static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
424 for (unsigned NumParams = FD->getNumParams(); NumParams > 0; --NumParams) {
425 const ParmVarDecl *PVD = FD->getParamDecl(NumParams-1);
426 if (!PVD->hasDefaultArg())
428 if (!PVD->hasInheritedDefaultArg())
434 /// MergeCXXFunctionDecl - Merge two declarations of the same C++
435 /// function, once we already know that they have the same
436 /// type. Subroutine of MergeFunctionDecl. Returns true if there was an
437 /// error, false otherwise.
438 bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
440 bool Invalid = false;
442 // The declaration context corresponding to the scope is the semantic
443 // parent, unless this is a local function declaration, in which case
444 // it is that surrounding function.
445 DeclContext *ScopeDC = New->isLocalExternDecl()
446 ? New->getLexicalDeclContext()
447 : New->getDeclContext();
449 // Find the previous declaration for the purpose of default arguments.
450 FunctionDecl *PrevForDefaultArgs = Old;
451 for (/**/; PrevForDefaultArgs;
452 // Don't bother looking back past the latest decl if this is a local
453 // extern declaration; nothing else could work.
454 PrevForDefaultArgs = New->isLocalExternDecl()
456 : PrevForDefaultArgs->getPreviousDecl()) {
457 // Ignore hidden declarations.
458 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
461 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
462 !New->isCXXClassMember()) {
463 // Ignore default arguments of old decl if they are not in
464 // the same scope and this is not an out-of-line definition of
465 // a member function.
469 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
470 // If only one of these is a local function declaration, then they are
471 // declared in different scopes, even though isDeclInScope may think
472 // they're in the same scope. (If both are local, the scope check is
473 // sufficient, and if neither is local, then they are in the same scope.)
477 // We found the right previous declaration.
481 // C++ [dcl.fct.default]p4:
482 // For non-template functions, default arguments can be added in
483 // later declarations of a function in the same
484 // scope. Declarations in different scopes have completely
485 // distinct sets of default arguments. That is, declarations in
486 // inner scopes do not acquire default arguments from
487 // declarations in outer scopes, and vice versa. In a given
488 // function declaration, all parameters subsequent to a
489 // parameter with a default argument shall have default
490 // arguments supplied in this or previous declarations. A
491 // default argument shall not be redefined by a later
492 // declaration (not even to the same value).
494 // C++ [dcl.fct.default]p6:
495 // Except for member functions of class templates, the default arguments
496 // in a member function definition that appears outside of the class
497 // definition are added to the set of default arguments provided by the
498 // member function declaration in the class definition.
499 for (unsigned p = 0, NumParams = PrevForDefaultArgs
500 ? PrevForDefaultArgs->getNumParams()
502 p < NumParams; ++p) {
503 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
504 ParmVarDecl *NewParam = New->getParamDecl(p);
506 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
507 bool NewParamHasDfl = NewParam->hasDefaultArg();
509 if (OldParamHasDfl && NewParamHasDfl) {
510 unsigned DiagDefaultParamID =
511 diag::err_param_default_argument_redefinition;
513 // MSVC accepts that default parameters be redefined for member functions
514 // of template class. The new default parameter's value is ignored.
516 if (getLangOpts().MicrosoftExt) {
517 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
518 if (MD && MD->getParent()->getDescribedClassTemplate()) {
519 // Merge the old default argument into the new parameter.
520 NewParam->setHasInheritedDefaultArg();
521 if (OldParam->hasUninstantiatedDefaultArg())
522 NewParam->setUninstantiatedDefaultArg(
523 OldParam->getUninstantiatedDefaultArg());
525 NewParam->setDefaultArg(OldParam->getInit());
526 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
531 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
532 // hint here. Alternatively, we could walk the type-source information
533 // for NewParam to find the last source location in the type... but it
534 // isn't worth the effort right now. This is the kind of test case that
535 // is hard to get right:
537 // void g(int (*fp)(int) = f);
538 // void g(int (*fp)(int) = &f);
539 Diag(NewParam->getLocation(), DiagDefaultParamID)
540 << NewParam->getDefaultArgRange();
542 // Look for the function declaration where the default argument was
543 // actually written, which may be a declaration prior to Old.
544 for (auto Older = PrevForDefaultArgs;
545 OldParam->hasInheritedDefaultArg(); /**/) {
546 Older = Older->getPreviousDecl();
547 OldParam = Older->getParamDecl(p);
550 Diag(OldParam->getLocation(), diag::note_previous_definition)
551 << OldParam->getDefaultArgRange();
552 } else if (OldParamHasDfl) {
553 // Merge the old default argument into the new parameter unless the new
554 // function is a friend declaration in a template class. In the latter
555 // case the default arguments will be inherited when the friend
556 // declaration will be instantiated.
557 if (New->getFriendObjectKind() == Decl::FOK_None ||
558 !New->getLexicalDeclContext()->isDependentContext()) {
559 // It's important to use getInit() here; getDefaultArg()
560 // strips off any top-level ExprWithCleanups.
561 NewParam->setHasInheritedDefaultArg();
562 if (OldParam->hasUnparsedDefaultArg())
563 NewParam->setUnparsedDefaultArg();
564 else if (OldParam->hasUninstantiatedDefaultArg())
565 NewParam->setUninstantiatedDefaultArg(
566 OldParam->getUninstantiatedDefaultArg());
568 NewParam->setDefaultArg(OldParam->getInit());
570 } else if (NewParamHasDfl) {
571 if (New->getDescribedFunctionTemplate()) {
572 // Paragraph 4, quoted above, only applies to non-template functions.
573 Diag(NewParam->getLocation(),
574 diag::err_param_default_argument_template_redecl)
575 << NewParam->getDefaultArgRange();
576 Diag(PrevForDefaultArgs->getLocation(),
577 diag::note_template_prev_declaration)
579 } else if (New->getTemplateSpecializationKind()
580 != TSK_ImplicitInstantiation &&
581 New->getTemplateSpecializationKind() != TSK_Undeclared) {
582 // C++ [temp.expr.spec]p21:
583 // Default function arguments shall not be specified in a declaration
584 // or a definition for one of the following explicit specializations:
585 // - the explicit specialization of a function template;
586 // - the explicit specialization of a member function template;
587 // - the explicit specialization of a member function of a class
588 // template where the class template specialization to which the
589 // member function specialization belongs is implicitly
591 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
592 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
593 << New->getDeclName()
594 << NewParam->getDefaultArgRange();
595 } else if (New->getDeclContext()->isDependentContext()) {
596 // C++ [dcl.fct.default]p6 (DR217):
597 // Default arguments for a member function of a class template shall
598 // be specified on the initial declaration of the member function
599 // within the class template.
601 // Reading the tea leaves a bit in DR217 and its reference to DR205
602 // leads me to the conclusion that one cannot add default function
603 // arguments for an out-of-line definition of a member function of a
606 if (CXXRecordDecl *Record
607 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
608 if (Record->getDescribedClassTemplate())
610 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
616 Diag(NewParam->getLocation(),
617 diag::err_param_default_argument_member_template_redecl)
619 << NewParam->getDefaultArgRange();
624 // DR1344: If a default argument is added outside a class definition and that
625 // default argument makes the function a special member function, the program
626 // is ill-formed. This can only happen for constructors.
627 if (isa<CXXConstructorDecl>(New) &&
628 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
629 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
630 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
631 if (NewSM != OldSM) {
632 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
633 assert(NewParam->hasDefaultArg());
634 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
635 << NewParam->getDefaultArgRange() << NewSM;
636 Diag(Old->getLocation(), diag::note_previous_declaration);
640 const FunctionDecl *Def;
641 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
642 // template has a constexpr specifier then all its declarations shall
643 // contain the constexpr specifier.
644 if (New->isConstexpr() != Old->isConstexpr()) {
645 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
646 << New << New->isConstexpr();
647 Diag(Old->getLocation(), diag::note_previous_declaration);
649 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
650 Old->isDefined(Def) &&
651 // If a friend function is inlined but does not have 'inline'
652 // specifier, it is a definition. Do not report attribute conflict
653 // in this case, redefinition will be diagnosed later.
654 (New->isInlineSpecified() ||
655 New->getFriendObjectKind() == Decl::FOK_None)) {
656 // C++11 [dcl.fcn.spec]p4:
657 // If the definition of a function appears in a translation unit before its
658 // first declaration as inline, the program is ill-formed.
659 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
660 Diag(Def->getLocation(), diag::note_previous_definition);
664 // FIXME: It's not clear what should happen if multiple declarations of a
665 // deduction guide have different explicitness. For now at least we simply
666 // reject any case where the explicitness changes.
667 auto *NewGuide = dyn_cast<CXXDeductionGuideDecl>(New);
668 if (NewGuide && NewGuide->isExplicitSpecified() !=
669 cast<CXXDeductionGuideDecl>(Old)->isExplicitSpecified()) {
670 Diag(New->getLocation(), diag::err_deduction_guide_explicit_mismatch)
671 << NewGuide->isExplicitSpecified();
672 Diag(Old->getLocation(), diag::note_previous_declaration);
675 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
676 // argument expression, that declaration shall be a definition and shall be
677 // the only declaration of the function or function template in the
679 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
680 functionDeclHasDefaultArgument(Old)) {
681 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
682 Diag(Old->getLocation(), diag::note_previous_declaration);
690 Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
691 MultiTemplateParamsArg TemplateParamLists) {
692 assert(D.isDecompositionDeclarator());
693 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
695 // The syntax only allows a decomposition declarator as a simple-declaration,
696 // a for-range-declaration, or a condition in Clang, but we parse it in more
698 if (!D.mayHaveDecompositionDeclarator()) {
699 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
700 << Decomp.getSourceRange();
704 if (!TemplateParamLists.empty()) {
705 // FIXME: There's no rule against this, but there are also no rules that
706 // would actually make it usable, so we reject it for now.
707 Diag(TemplateParamLists.front()->getTemplateLoc(),
708 diag::err_decomp_decl_template);
712 Diag(Decomp.getLSquareLoc(),
713 !getLangOpts().CPlusPlus17
714 ? diag::ext_decomp_decl
715 : D.getContext() == DeclaratorContext::ConditionContext
716 ? diag::ext_decomp_decl_cond
717 : diag::warn_cxx14_compat_decomp_decl)
718 << Decomp.getSourceRange();
720 // The semantic context is always just the current context.
721 DeclContext *const DC = CurContext;
723 // C++1z [dcl.dcl]/8:
724 // The decl-specifier-seq shall contain only the type-specifier auto
725 // and cv-qualifiers.
726 auto &DS = D.getDeclSpec();
728 SmallVector<StringRef, 8> BadSpecifiers;
729 SmallVector<SourceLocation, 8> BadSpecifierLocs;
730 if (auto SCS = DS.getStorageClassSpec()) {
731 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
732 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
734 if (auto TSCS = DS.getThreadStorageClassSpec()) {
735 BadSpecifiers.push_back(DeclSpec::getSpecifierName(TSCS));
736 BadSpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
738 if (DS.isConstexprSpecified()) {
739 BadSpecifiers.push_back("constexpr");
740 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
742 if (DS.isInlineSpecified()) {
743 BadSpecifiers.push_back("inline");
744 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
746 if (!BadSpecifiers.empty()) {
747 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
748 Err << (int)BadSpecifiers.size()
749 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
750 // Don't add FixItHints to remove the specifiers; we do still respect
751 // them when building the underlying variable.
752 for (auto Loc : BadSpecifierLocs)
753 Err << SourceRange(Loc, Loc);
755 // We can't recover from it being declared as a typedef.
756 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
760 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
761 QualType R = TInfo->getType();
763 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
764 UPPC_DeclarationType))
767 // The syntax only allows a single ref-qualifier prior to the decomposition
768 // declarator. No other declarator chunks are permitted. Also check the type
770 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
771 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
772 (D.getNumTypeObjects() == 1 &&
773 D.getTypeObject(0).Kind != DeclaratorChunk::Reference)) {
774 Diag(Decomp.getLSquareLoc(),
775 (D.hasGroupingParens() ||
776 (D.getNumTypeObjects() &&
777 D.getTypeObject(0).Kind == DeclaratorChunk::Paren))
778 ? diag::err_decomp_decl_parens
779 : diag::err_decomp_decl_type)
782 // In most cases, there's no actual problem with an explicitly-specified
783 // type, but a function type won't work here, and ActOnVariableDeclarator
784 // shouldn't be called for such a type.
785 if (R->isFunctionType())
789 // Build the BindingDecls.
790 SmallVector<BindingDecl*, 8> Bindings;
792 // Build the BindingDecls.
793 for (auto &B : D.getDecompositionDeclarator().bindings()) {
794 // Check for name conflicts.
795 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
796 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
797 ForVisibleRedeclaration);
798 LookupName(Previous, S,
799 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
801 // It's not permitted to shadow a template parameter name.
802 if (Previous.isSingleResult() &&
803 Previous.getFoundDecl()->isTemplateParameter()) {
804 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(),
805 Previous.getFoundDecl());
809 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
810 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
811 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
812 /*AllowInlineNamespace*/false);
813 if (!Previous.empty()) {
814 auto *Old = Previous.getRepresentativeDecl();
815 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
816 Diag(Old->getLocation(), diag::note_previous_definition);
819 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, B.Name);
820 PushOnScopeChains(BD, S, true);
821 Bindings.push_back(BD);
822 ParsingInitForAutoVars.insert(BD);
825 // There are no prior lookup results for the variable itself, because it
827 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
828 Decomp.getLSquareLoc());
829 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
830 ForVisibleRedeclaration);
832 // Build the variable that holds the non-decomposed object.
833 bool AddToScope = true;
835 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
836 MultiTemplateParamsArg(), AddToScope, Bindings);
839 CurContext->addHiddenDecl(New);
842 if (isInOpenMPDeclareTargetContext())
843 checkDeclIsAllowedInOpenMPTarget(nullptr, New);
848 static bool checkSimpleDecomposition(
849 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
850 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
851 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
852 if ((int64_t)Bindings.size() != NumElems) {
853 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
854 << DecompType << (unsigned)Bindings.size() << NumElems.toString(10)
855 << (NumElems < Bindings.size());
860 for (auto *B : Bindings) {
861 SourceLocation Loc = B->getLocation();
862 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
865 E = GetInit(Loc, E.get(), I++);
868 B->setBinding(ElemType, E.get());
874 static bool checkArrayLikeDecomposition(Sema &S,
875 ArrayRef<BindingDecl *> Bindings,
876 ValueDecl *Src, QualType DecompType,
877 const llvm::APSInt &NumElems,
879 return checkSimpleDecomposition(
880 S, Bindings, Src, DecompType, NumElems, ElemType,
881 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
882 ExprResult E = S.ActOnIntegerConstant(Loc, I);
885 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
889 static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
890 ValueDecl *Src, QualType DecompType,
891 const ConstantArrayType *CAT) {
892 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
893 llvm::APSInt(CAT->getSize()),
894 CAT->getElementType());
897 static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
898 ValueDecl *Src, QualType DecompType,
899 const VectorType *VT) {
900 return checkArrayLikeDecomposition(
901 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
902 S.Context.getQualifiedType(VT->getElementType(),
903 DecompType.getQualifiers()));
906 static bool checkComplexDecomposition(Sema &S,
907 ArrayRef<BindingDecl *> Bindings,
908 ValueDecl *Src, QualType DecompType,
909 const ComplexType *CT) {
910 return checkSimpleDecomposition(
911 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
912 S.Context.getQualifiedType(CT->getElementType(),
913 DecompType.getQualifiers()),
914 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
915 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
919 static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
920 TemplateArgumentListInfo &Args) {
922 llvm::raw_svector_ostream OS(SS);
924 for (auto &Arg : Args.arguments()) {
927 Arg.getArgument().print(PrintingPolicy, OS);
933 static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
934 SourceLocation Loc, StringRef Trait,
935 TemplateArgumentListInfo &Args,
937 auto DiagnoseMissing = [&] {
939 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
944 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
945 NamespaceDecl *Std = S.getStdNamespace();
947 return DiagnoseMissing();
949 // Look up the trait itself, within namespace std. We can diagnose various
950 // problems with this lookup even if we've been asked to not diagnose a
951 // missing specialization, because this can only fail if the user has been
952 // declaring their own names in namespace std or we don't support the
953 // standard library implementation in use.
954 LookupResult Result(S, &S.PP.getIdentifierTable().get(Trait),
955 Loc, Sema::LookupOrdinaryName);
956 if (!S.LookupQualifiedName(Result, Std))
957 return DiagnoseMissing();
958 if (Result.isAmbiguous())
961 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
963 Result.suppressDiagnostics();
964 NamedDecl *Found = *Result.begin();
965 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
966 S.Diag(Found->getLocation(), diag::note_declared_at);
970 // Build the template-id.
971 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
972 if (TraitTy.isNull())
974 if (!S.isCompleteType(Loc, TraitTy)) {
976 S.RequireCompleteType(
977 Loc, TraitTy, DiagID,
978 printTemplateArgs(S.Context.getPrintingPolicy(), Args));
982 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
983 assert(RD && "specialization of class template is not a class?");
985 // Look up the member of the trait type.
986 S.LookupQualifiedName(TraitMemberLookup, RD);
987 return TraitMemberLookup.isAmbiguous();
990 static TemplateArgumentLoc
991 getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
993 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(I, T), T);
994 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
997 static TemplateArgumentLoc
998 getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
999 return S.getTrivialTemplateArgumentLoc(TemplateArgument(T), QualType(), Loc);
1002 namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1004 static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1005 llvm::APSInt &Size) {
1006 EnterExpressionEvaluationContext ContextRAII(
1007 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1009 DeclarationName Value = S.PP.getIdentifierInfo("value");
1010 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1012 // Form template argument list for tuple_size<T>.
1013 TemplateArgumentListInfo Args(Loc, Loc);
1014 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1016 // If there's no tuple_size specialization, it's not tuple-like.
1017 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/0))
1018 return IsTupleLike::NotTupleLike;
1020 // If we get this far, we've committed to the tuple interpretation, but
1021 // we can still fail if there actually isn't a usable ::value.
1023 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1025 TemplateArgumentListInfo &Args;
1026 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1027 : R(R), Args(Args) {}
1028 void diagnoseNotICE(Sema &S, SourceLocation Loc, SourceRange SR) {
1029 S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1030 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1032 } Diagnoser(R, Args);
1035 Diagnoser.diagnoseNotICE(S, Loc, SourceRange());
1036 return IsTupleLike::Error;
1040 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1042 return IsTupleLike::Error;
1044 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser, false);
1046 return IsTupleLike::Error;
1048 return IsTupleLike::TupleLike;
1051 /// \return std::tuple_element<I, T>::type.
1052 static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1053 unsigned I, QualType T) {
1054 // Form template argument list for tuple_element<I, T>.
1055 TemplateArgumentListInfo Args(Loc, Loc);
1057 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1058 Args.addArgument(getTrivialTypeTemplateArgument(S, Loc, T));
1060 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1061 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1062 if (lookupStdTypeTraitMember(
1063 S, R, Loc, "tuple_element", Args,
1064 diag::err_decomp_decl_std_tuple_element_not_specialized))
1067 auto *TD = R.getAsSingle<TypeDecl>();
1069 R.suppressDiagnostics();
1070 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1071 << printTemplateArgs(S.Context.getPrintingPolicy(), Args);
1073 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1077 return S.Context.getTypeDeclType(TD);
1081 struct BindingDiagnosticTrap {
1083 DiagnosticErrorTrap Trap;
1086 BindingDiagnosticTrap(Sema &S, BindingDecl *BD)
1087 : S(S), Trap(S.Diags), BD(BD) {}
1088 ~BindingDiagnosticTrap() {
1089 if (Trap.hasErrorOccurred())
1090 S.Diag(BD->getLocation(), diag::note_in_binding_decl_init) << BD;
1095 static bool checkTupleLikeDecomposition(Sema &S,
1096 ArrayRef<BindingDecl *> Bindings,
1097 VarDecl *Src, QualType DecompType,
1098 const llvm::APSInt &TupleSize) {
1099 if ((int64_t)Bindings.size() != TupleSize) {
1100 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1101 << DecompType << (unsigned)Bindings.size() << TupleSize.toString(10)
1102 << (TupleSize < Bindings.size());
1106 if (Bindings.empty())
1109 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1112 // The unqualified-id get is looked up in the scope of E by class member
1114 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1115 bool UseMemberGet = false;
1116 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1117 if (auto *RD = DecompType->getAsCXXRecordDecl())
1118 S.LookupQualifiedName(MemberGet, RD);
1119 if (MemberGet.isAmbiguous())
1121 UseMemberGet = !MemberGet.empty();
1122 S.FilterAcceptableTemplateNames(MemberGet);
1126 for (auto *B : Bindings) {
1127 BindingDiagnosticTrap Trap(S, B);
1128 SourceLocation Loc = B->getLocation();
1130 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1134 // e is an lvalue if the type of the entity is an lvalue reference and
1135 // an xvalue otherwise
1136 if (!Src->getType()->isLValueReferenceType())
1137 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1138 E.get(), nullptr, VK_XValue);
1140 TemplateArgumentListInfo Args(Loc, Loc);
1142 getTrivialIntegralTemplateArgument(S, Loc, S.Context.getSizeType(), I));
1145 // if [lookup of member get] finds at least one declaration, the
1146 // initializer is e.get<i-1>().
1147 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1148 CXXScopeSpec(), SourceLocation(), nullptr,
1149 MemberGet, &Args, nullptr);
1153 E = S.ActOnCallExpr(nullptr, E.get(), Loc, None, Loc);
1155 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1156 // in the associated namespaces.
1157 Expr *Get = UnresolvedLookupExpr::Create(
1158 S.Context, nullptr, NestedNameSpecifierLoc(), SourceLocation(),
1159 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/true, &Args,
1160 UnresolvedSetIterator(), UnresolvedSetIterator());
1162 Expr *Arg = E.get();
1163 E = S.ActOnCallExpr(nullptr, Get, Loc, Arg, Loc);
1167 Expr *Init = E.get();
1169 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1170 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1174 // each vi is a variable of type "reference to T" initialized with the
1175 // initializer, where the reference is an lvalue reference if the
1176 // initializer is an lvalue and an rvalue reference otherwise
1178 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1179 if (RefType.isNull())
1181 auto *RefVD = VarDecl::Create(
1182 S.Context, Src->getDeclContext(), Loc, Loc,
1183 B->getDeclName().getAsIdentifierInfo(), RefType,
1184 S.Context.getTrivialTypeSourceInfo(T, Loc), Src->getStorageClass());
1185 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1186 RefVD->setTSCSpec(Src->getTSCSpec());
1187 RefVD->setImplicit();
1188 if (Src->isInlineSpecified())
1189 RefVD->setInlineSpecified();
1190 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1192 InitializedEntity Entity = InitializedEntity::InitializeBinding(RefVD);
1193 InitializationKind Kind = InitializationKind::CreateCopy(Loc, Loc);
1194 InitializationSequence Seq(S, Entity, Kind, Init);
1195 E = Seq.Perform(S, Entity, Kind, Init);
1198 E = S.ActOnFinishFullExpr(E.get(), Loc);
1201 RefVD->setInit(E.get());
1202 RefVD->checkInitIsICE();
1204 E = S.BuildDeclarationNameExpr(CXXScopeSpec(),
1205 DeclarationNameInfo(B->getDeclName(), Loc),
1210 B->setBinding(T, E.get());
1217 /// Find the base class to decompose in a built-in decomposition of a class type.
1218 /// This base class search is, unfortunately, not quite like any other that we
1219 /// perform anywhere else in C++.
1220 static const CXXRecordDecl *findDecomposableBaseClass(Sema &S,
1222 const CXXRecordDecl *RD,
1223 CXXCastPath &BasePath) {
1224 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1225 CXXBasePath &Path) {
1226 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1229 const CXXRecordDecl *ClassWithFields = nullptr;
1230 if (RD->hasDirectFields())
1232 // Otherwise, all of E's non-static data members shall be public direct
1234 ClassWithFields = RD;
1238 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1239 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1240 // If no classes have fields, just decompose RD itself. (This will work
1241 // if and only if zero bindings were provided.)
1245 CXXBasePath *BestPath = nullptr;
1246 for (auto &P : Paths) {
1249 else if (!S.Context.hasSameType(P.back().Base->getType(),
1250 BestPath->back().Base->getType())) {
1252 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1253 << false << RD << BestPath->back().Base->getType()
1254 << P.back().Base->getType();
1256 } else if (P.Access < BestPath->Access) {
1261 // ... unambiguous ...
1262 QualType BaseType = BestPath->back().Base->getType();
1263 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1264 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1265 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1269 // ... public base class of E.
1270 if (BestPath->Access != AS_public) {
1271 S.Diag(Loc, diag::err_decomp_decl_non_public_base)
1273 for (auto &BS : *BestPath) {
1274 if (BS.Base->getAccessSpecifier() != AS_public) {
1275 S.Diag(BS.Base->getLocStart(), diag::note_access_constrained_by_path)
1276 << (BS.Base->getAccessSpecifier() == AS_protected)
1277 << (BS.Base->getAccessSpecifierAsWritten() == AS_none);
1284 ClassWithFields = BaseType->getAsCXXRecordDecl();
1285 S.BuildBasePathArray(Paths, BasePath);
1288 // The above search did not check whether the selected class itself has base
1289 // classes with fields, so check that now.
1291 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1292 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1293 << (ClassWithFields == RD) << RD << ClassWithFields
1294 << Paths.front().back().Base->getType();
1298 return ClassWithFields;
1301 static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1302 ValueDecl *Src, QualType DecompType,
1303 const CXXRecordDecl *RD) {
1304 CXXCastPath BasePath;
1305 RD = findDecomposableBaseClass(S, Src->getLocation(), RD, BasePath);
1308 QualType BaseType = S.Context.getQualifiedType(S.Context.getRecordType(RD),
1309 DecompType.getQualifiers());
1311 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1312 unsigned NumFields =
1313 std::count_if(RD->field_begin(), RD->field_end(),
1314 [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1315 assert(Bindings.size() != NumFields);
1316 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1317 << DecompType << (unsigned)Bindings.size() << NumFields
1318 << (NumFields < Bindings.size());
1322 // all of E's non-static data members shall be public [...] members,
1323 // E shall not have an anonymous union member, ...
1325 for (auto *FD : RD->fields()) {
1326 if (FD->isUnnamedBitfield())
1329 if (FD->isAnonymousStructOrUnion()) {
1330 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1331 << DecompType << FD->getType()->isUnionType();
1332 S.Diag(FD->getLocation(), diag::note_declared_at);
1336 // We have a real field to bind.
1337 if (I >= Bindings.size())
1338 return DiagnoseBadNumberOfBindings();
1339 auto *B = Bindings[I++];
1341 SourceLocation Loc = B->getLocation();
1342 if (FD->getAccess() != AS_public) {
1343 S.Diag(Loc, diag::err_decomp_decl_non_public_member) << FD << DecompType;
1345 // Determine whether the access specifier was explicit.
1346 bool Implicit = true;
1347 for (const auto *D : RD->decls()) {
1348 if (declaresSameEntity(D, FD))
1350 if (isa<AccessSpecDecl>(D)) {
1356 S.Diag(FD->getLocation(), diag::note_access_natural)
1357 << (FD->getAccess() == AS_protected) << Implicit;
1361 // Initialize the binding to Src.FD.
1362 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1365 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1366 VK_LValue, &BasePath);
1369 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1371 DeclAccessPair::make(FD, FD->getAccess()),
1372 DeclarationNameInfo(FD->getDeclName(), Loc));
1376 // If the type of the member is T, the referenced type is cv T, where cv is
1377 // the cv-qualification of the decomposition expression.
1379 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1380 // 'const' to the type of the field.
1381 Qualifiers Q = DecompType.getQualifiers();
1382 if (FD->isMutable())
1384 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1387 if (I != Bindings.size())
1388 return DiagnoseBadNumberOfBindings();
1393 void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1394 QualType DecompType = DD->getType();
1396 // If the type of the decomposition is dependent, then so is the type of
1398 if (DecompType->isDependentType()) {
1399 for (auto *B : DD->bindings())
1400 B->setType(Context.DependentTy);
1404 DecompType = DecompType.getNonReferenceType();
1405 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1407 // C++1z [dcl.decomp]/2:
1408 // If E is an array type [...]
1409 // As an extension, we also support decomposition of built-in complex and
1411 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1412 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1413 DD->setInvalidDecl();
1416 if (auto *VT = DecompType->getAs<VectorType>()) {
1417 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1418 DD->setInvalidDecl();
1421 if (auto *CT = DecompType->getAs<ComplexType>()) {
1422 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1423 DD->setInvalidDecl();
1427 // C++1z [dcl.decomp]/3:
1428 // if the expression std::tuple_size<E>::value is a well-formed integral
1429 // constant expression, [...]
1430 llvm::APSInt TupleSize(32);
1431 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1432 case IsTupleLike::Error:
1433 DD->setInvalidDecl();
1436 case IsTupleLike::TupleLike:
1437 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1438 DD->setInvalidDecl();
1441 case IsTupleLike::NotTupleLike:
1445 // C++1z [dcl.dcl]/8:
1446 // [E shall be of array or non-union class type]
1447 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1448 if (!RD || RD->isUnion()) {
1449 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1450 << DD << !RD << DecompType;
1451 DD->setInvalidDecl();
1455 // C++1z [dcl.decomp]/4:
1456 // all of E's non-static data members shall be [...] direct members of
1457 // E or of the same unambiguous public base class of E, ...
1458 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1459 DD->setInvalidDecl();
1462 /// \brief Merge the exception specifications of two variable declarations.
1464 /// This is called when there's a redeclaration of a VarDecl. The function
1465 /// checks if the redeclaration might have an exception specification and
1466 /// validates compatibility and merges the specs if necessary.
1467 void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1468 // Shortcut if exceptions are disabled.
1469 if (!getLangOpts().CXXExceptions)
1472 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1473 "Should only be called if types are otherwise the same.");
1475 QualType NewType = New->getType();
1476 QualType OldType = Old->getType();
1478 // We're only interested in pointers and references to functions, as well
1479 // as pointers to member functions.
1480 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1481 NewType = R->getPointeeType();
1482 OldType = OldType->getAs<ReferenceType>()->getPointeeType();
1483 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1484 NewType = P->getPointeeType();
1485 OldType = OldType->getAs<PointerType>()->getPointeeType();
1486 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1487 NewType = M->getPointeeType();
1488 OldType = OldType->getAs<MemberPointerType>()->getPointeeType();
1491 if (!NewType->isFunctionProtoType())
1494 // There's lots of special cases for functions. For function pointers, system
1495 // libraries are hopefully not as broken so that we don't need these
1497 if (CheckEquivalentExceptionSpec(
1498 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1499 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1500 New->setInvalidDecl();
1504 /// CheckCXXDefaultArguments - Verify that the default arguments for a
1505 /// function declaration are well-formed according to C++
1506 /// [dcl.fct.default].
1507 void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1508 unsigned NumParams = FD->getNumParams();
1511 // Find first parameter with a default argument
1512 for (p = 0; p < NumParams; ++p) {
1513 ParmVarDecl *Param = FD->getParamDecl(p);
1514 if (Param->hasDefaultArg())
1518 // C++11 [dcl.fct.default]p4:
1519 // In a given function declaration, each parameter subsequent to a parameter
1520 // with a default argument shall have a default argument supplied in this or
1521 // a previous declaration or shall be a function parameter pack. A default
1522 // argument shall not be redefined by a later declaration (not even to the
1524 unsigned LastMissingDefaultArg = 0;
1525 for (; p < NumParams; ++p) {
1526 ParmVarDecl *Param = FD->getParamDecl(p);
1527 if (!Param->hasDefaultArg() && !Param->isParameterPack()) {
1528 if (Param->isInvalidDecl())
1529 /* We already complained about this parameter. */;
1530 else if (Param->getIdentifier())
1531 Diag(Param->getLocation(),
1532 diag::err_param_default_argument_missing_name)
1533 << Param->getIdentifier();
1535 Diag(Param->getLocation(),
1536 diag::err_param_default_argument_missing);
1538 LastMissingDefaultArg = p;
1542 if (LastMissingDefaultArg > 0) {
1543 // Some default arguments were missing. Clear out all of the
1544 // default arguments up to (and including) the last missing
1545 // default argument, so that we leave the function parameters
1546 // in a semantically valid state.
1547 for (p = 0; p <= LastMissingDefaultArg; ++p) {
1548 ParmVarDecl *Param = FD->getParamDecl(p);
1549 if (Param->hasDefaultArg()) {
1550 Param->setDefaultArg(nullptr);
1556 // CheckConstexprParameterTypes - Check whether a function's parameter types
1557 // are all literal types. If so, return true. If not, produce a suitable
1558 // diagnostic and return false.
1559 static bool CheckConstexprParameterTypes(Sema &SemaRef,
1560 const FunctionDecl *FD) {
1561 unsigned ArgIndex = 0;
1562 const FunctionProtoType *FT = FD->getType()->getAs<FunctionProtoType>();
1563 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1564 e = FT->param_type_end();
1565 i != e; ++i, ++ArgIndex) {
1566 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1567 SourceLocation ParamLoc = PD->getLocation();
1568 if (!(*i)->isDependentType() &&
1569 SemaRef.RequireLiteralType(ParamLoc, *i,
1570 diag::err_constexpr_non_literal_param,
1571 ArgIndex+1, PD->getSourceRange(),
1572 isa<CXXConstructorDecl>(FD)))
1578 /// \brief Get diagnostic %select index for tag kind for
1579 /// record diagnostic message.
1580 /// WARNING: Indexes apply to particular diagnostics only!
1582 /// \returns diagnostic %select index.
1583 static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1585 case TTK_Struct: return 0;
1586 case TTK_Interface: return 1;
1587 case TTK_Class: return 2;
1588 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1592 // CheckConstexprFunctionDecl - Check whether a function declaration satisfies
1593 // the requirements of a constexpr function definition or a constexpr
1594 // constructor definition. If so, return true. If not, produce appropriate
1595 // diagnostics and return false.
1597 // This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1598 bool Sema::CheckConstexprFunctionDecl(const FunctionDecl *NewFD) {
1599 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1600 if (MD && MD->isInstance()) {
1601 // C++11 [dcl.constexpr]p4:
1602 // The definition of a constexpr constructor shall satisfy the following
1604 // - the class shall not have any virtual base classes;
1605 const CXXRecordDecl *RD = MD->getParent();
1606 if (RD->getNumVBases()) {
1607 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1608 << isa<CXXConstructorDecl>(NewFD)
1609 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getNumVBases();
1610 for (const auto &I : RD->vbases())
1611 Diag(I.getLocStart(),
1612 diag::note_constexpr_virtual_base_here) << I.getSourceRange();
1617 if (!isa<CXXConstructorDecl>(NewFD)) {
1618 // C++11 [dcl.constexpr]p3:
1619 // The definition of a constexpr function shall satisfy the following
1621 // - it shall not be virtual;
1622 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1623 if (Method && Method->isVirtual()) {
1624 Method = Method->getCanonicalDecl();
1625 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1627 // If it's not obvious why this function is virtual, find an overridden
1628 // function which uses the 'virtual' keyword.
1629 const CXXMethodDecl *WrittenVirtual = Method;
1630 while (!WrittenVirtual->isVirtualAsWritten())
1631 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1632 if (WrittenVirtual != Method)
1633 Diag(WrittenVirtual->getLocation(),
1634 diag::note_overridden_virtual_function);
1638 // - its return type shall be a literal type;
1639 QualType RT = NewFD->getReturnType();
1640 if (!RT->isDependentType() &&
1641 RequireLiteralType(NewFD->getLocation(), RT,
1642 diag::err_constexpr_non_literal_return))
1646 // - each of its parameter types shall be a literal type;
1647 if (!CheckConstexprParameterTypes(*this, NewFD))
1653 /// Check the given declaration statement is legal within a constexpr function
1654 /// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1656 /// \return true if the body is OK (maybe only as an extension), false if we
1657 /// have diagnosed a problem.
1658 static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
1659 DeclStmt *DS, SourceLocation &Cxx1yLoc) {
1660 // C++11 [dcl.constexpr]p3 and p4:
1661 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1663 for (const auto *DclIt : DS->decls()) {
1664 switch (DclIt->getKind()) {
1665 case Decl::StaticAssert:
1667 case Decl::UsingShadow:
1668 case Decl::UsingDirective:
1669 case Decl::UnresolvedUsingTypename:
1670 case Decl::UnresolvedUsingValue:
1671 // - static_assert-declarations
1672 // - using-declarations,
1673 // - using-directives,
1677 case Decl::TypeAlias: {
1678 // - typedef declarations and alias-declarations that do not define
1679 // classes or enumerations,
1680 const auto *TN = cast<TypedefNameDecl>(DclIt);
1681 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1682 // Don't allow variably-modified types in constexpr functions.
1683 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1684 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1685 << TL.getSourceRange() << TL.getType()
1686 << isa<CXXConstructorDecl>(Dcl);
1693 case Decl::CXXRecord:
1694 // C++1y allows types to be defined, not just declared.
1695 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition())
1696 SemaRef.Diag(DS->getLocStart(),
1697 SemaRef.getLangOpts().CPlusPlus14
1698 ? diag::warn_cxx11_compat_constexpr_type_definition
1699 : diag::ext_constexpr_type_definition)
1700 << isa<CXXConstructorDecl>(Dcl);
1703 case Decl::EnumConstant:
1704 case Decl::IndirectField:
1706 // These can only appear with other declarations which are banned in
1707 // C++11 and permitted in C++1y, so ignore them.
1711 case Decl::Decomposition: {
1712 // C++1y [dcl.constexpr]p3 allows anything except:
1713 // a definition of a variable of non-literal type or of static or
1714 // thread storage duration or for which no initialization is performed.
1715 const auto *VD = cast<VarDecl>(DclIt);
1716 if (VD->isThisDeclarationADefinition()) {
1717 if (VD->isStaticLocal()) {
1718 SemaRef.Diag(VD->getLocation(),
1719 diag::err_constexpr_local_var_static)
1720 << isa<CXXConstructorDecl>(Dcl)
1721 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1724 if (!VD->getType()->isDependentType() &&
1725 SemaRef.RequireLiteralType(
1726 VD->getLocation(), VD->getType(),
1727 diag::err_constexpr_local_var_non_literal_type,
1728 isa<CXXConstructorDecl>(Dcl)))
1730 if (!VD->getType()->isDependentType() &&
1731 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1732 SemaRef.Diag(VD->getLocation(),
1733 diag::err_constexpr_local_var_no_init)
1734 << isa<CXXConstructorDecl>(Dcl);
1738 SemaRef.Diag(VD->getLocation(),
1739 SemaRef.getLangOpts().CPlusPlus14
1740 ? diag::warn_cxx11_compat_constexpr_local_var
1741 : diag::ext_constexpr_local_var)
1742 << isa<CXXConstructorDecl>(Dcl);
1746 case Decl::NamespaceAlias:
1747 case Decl::Function:
1748 // These are disallowed in C++11 and permitted in C++1y. Allow them
1749 // everywhere as an extension.
1750 if (!Cxx1yLoc.isValid())
1751 Cxx1yLoc = DS->getLocStart();
1755 SemaRef.Diag(DS->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1756 << isa<CXXConstructorDecl>(Dcl);
1764 /// Check that the given field is initialized within a constexpr constructor.
1766 /// \param Dcl The constexpr constructor being checked.
1767 /// \param Field The field being checked. This may be a member of an anonymous
1768 /// struct or union nested within the class being checked.
1769 /// \param Inits All declarations, including anonymous struct/union members and
1770 /// indirect members, for which any initialization was provided.
1771 /// \param Diagnosed Set to true if an error is produced.
1772 static void CheckConstexprCtorInitializer(Sema &SemaRef,
1773 const FunctionDecl *Dcl,
1775 llvm::SmallSet<Decl*, 16> &Inits,
1777 if (Field->isInvalidDecl())
1780 if (Field->isUnnamedBitfield())
1783 // Anonymous unions with no variant members and empty anonymous structs do not
1784 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
1785 // indirect fields don't need initializing.
1786 if (Field->isAnonymousStructOrUnion() &&
1787 (Field->getType()->isUnionType()
1788 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
1789 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
1792 if (!Inits.count(Field)) {
1794 SemaRef.Diag(Dcl->getLocation(), diag::err_constexpr_ctor_missing_init);
1797 SemaRef.Diag(Field->getLocation(), diag::note_constexpr_ctor_missing_init);
1798 } else if (Field->isAnonymousStructOrUnion()) {
1799 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
1800 for (auto *I : RD->fields())
1801 // If an anonymous union contains an anonymous struct of which any member
1802 // is initialized, all members must be initialized.
1803 if (!RD->isUnion() || Inits.count(I))
1804 CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed);
1808 /// Check the provided statement is allowed in a constexpr function
1811 CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
1812 SmallVectorImpl<SourceLocation> &ReturnStmts,
1813 SourceLocation &Cxx1yLoc) {
1814 // - its function-body shall be [...] a compound-statement that contains only
1815 switch (S->getStmtClass()) {
1816 case Stmt::NullStmtClass:
1817 // - null statements,
1820 case Stmt::DeclStmtClass:
1821 // - static_assert-declarations
1822 // - using-declarations,
1823 // - using-directives,
1824 // - typedef declarations and alias-declarations that do not define
1825 // classes or enumerations,
1826 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc))
1830 case Stmt::ReturnStmtClass:
1831 // - and exactly one return statement;
1832 if (isa<CXXConstructorDecl>(Dcl)) {
1833 // C++1y allows return statements in constexpr constructors.
1834 if (!Cxx1yLoc.isValid())
1835 Cxx1yLoc = S->getLocStart();
1839 ReturnStmts.push_back(S->getLocStart());
1842 case Stmt::CompoundStmtClass: {
1843 // C++1y allows compound-statements.
1844 if (!Cxx1yLoc.isValid())
1845 Cxx1yLoc = S->getLocStart();
1847 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
1848 for (auto *BodyIt : CompStmt->body()) {
1849 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
1856 case Stmt::AttributedStmtClass:
1857 if (!Cxx1yLoc.isValid())
1858 Cxx1yLoc = S->getLocStart();
1861 case Stmt::IfStmtClass: {
1862 // C++1y allows if-statements.
1863 if (!Cxx1yLoc.isValid())
1864 Cxx1yLoc = S->getLocStart();
1866 IfStmt *If = cast<IfStmt>(S);
1867 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
1870 if (If->getElse() &&
1871 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
1877 case Stmt::WhileStmtClass:
1878 case Stmt::DoStmtClass:
1879 case Stmt::ForStmtClass:
1880 case Stmt::CXXForRangeStmtClass:
1881 case Stmt::ContinueStmtClass:
1882 // C++1y allows all of these. We don't allow them as extensions in C++11,
1883 // because they don't make sense without variable mutation.
1884 if (!SemaRef.getLangOpts().CPlusPlus14)
1886 if (!Cxx1yLoc.isValid())
1887 Cxx1yLoc = S->getLocStart();
1888 for (Stmt *SubStmt : S->children())
1890 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1895 case Stmt::SwitchStmtClass:
1896 case Stmt::CaseStmtClass:
1897 case Stmt::DefaultStmtClass:
1898 case Stmt::BreakStmtClass:
1899 // C++1y allows switch-statements, and since they don't need variable
1900 // mutation, we can reasonably allow them in C++11 as an extension.
1901 if (!Cxx1yLoc.isValid())
1902 Cxx1yLoc = S->getLocStart();
1903 for (Stmt *SubStmt : S->children())
1905 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
1914 // C++1y allows expression-statements.
1915 if (!Cxx1yLoc.isValid())
1916 Cxx1yLoc = S->getLocStart();
1920 SemaRef.Diag(S->getLocStart(), diag::err_constexpr_body_invalid_stmt)
1921 << isa<CXXConstructorDecl>(Dcl);
1925 /// Check the body for the given constexpr function declaration only contains
1926 /// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
1928 /// \return true if the body is OK, false if we have diagnosed a problem.
1929 bool Sema::CheckConstexprFunctionBody(const FunctionDecl *Dcl, Stmt *Body) {
1930 if (isa<CXXTryStmt>(Body)) {
1931 // C++11 [dcl.constexpr]p3:
1932 // The definition of a constexpr function shall satisfy the following
1933 // constraints: [...]
1934 // - its function-body shall be = delete, = default, or a
1935 // compound-statement
1937 // C++11 [dcl.constexpr]p4:
1938 // In the definition of a constexpr constructor, [...]
1939 // - its function-body shall not be a function-try-block;
1940 Diag(Body->getLocStart(), diag::err_constexpr_function_try_block)
1941 << isa<CXXConstructorDecl>(Dcl);
1945 SmallVector<SourceLocation, 4> ReturnStmts;
1947 // - its function-body shall be [...] a compound-statement that contains only
1948 // [... list of cases ...]
1949 CompoundStmt *CompBody = cast<CompoundStmt>(Body);
1950 SourceLocation Cxx1yLoc;
1951 for (auto *BodyIt : CompBody->body()) {
1952 if (!CheckConstexprFunctionStmt(*this, Dcl, BodyIt, ReturnStmts, Cxx1yLoc))
1956 if (Cxx1yLoc.isValid())
1958 getLangOpts().CPlusPlus14
1959 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
1960 : diag::ext_constexpr_body_invalid_stmt)
1961 << isa<CXXConstructorDecl>(Dcl);
1963 if (const CXXConstructorDecl *Constructor
1964 = dyn_cast<CXXConstructorDecl>(Dcl)) {
1965 const CXXRecordDecl *RD = Constructor->getParent();
1967 // - every non-variant non-static data member and base class sub-object
1968 // shall be initialized;
1970 // - if the class is a union having variant members, exactly one of them
1971 // shall be initialized;
1972 if (RD->isUnion()) {
1973 if (Constructor->getNumCtorInitializers() == 0 &&
1974 RD->hasVariantMembers()) {
1975 Diag(Dcl->getLocation(), diag::err_constexpr_union_ctor_no_init);
1978 } else if (!Constructor->isDependentContext() &&
1979 !Constructor->isDelegatingConstructor()) {
1980 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
1982 // Skip detailed checking if we have enough initializers, and we would
1983 // allow at most one initializer per member.
1984 bool AnyAnonStructUnionMembers = false;
1985 unsigned Fields = 0;
1986 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
1987 E = RD->field_end(); I != E; ++I, ++Fields) {
1988 if (I->isAnonymousStructOrUnion()) {
1989 AnyAnonStructUnionMembers = true;
1994 // - if the class is a union-like class, but is not a union, for each of
1995 // its anonymous union members having variant members, exactly one of
1996 // them shall be initialized;
1997 if (AnyAnonStructUnionMembers ||
1998 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
1999 // Check initialization of non-static data members. Base classes are
2000 // always initialized so do not need to be checked. Dependent bases
2001 // might not have initializers in the member initializer list.
2002 llvm::SmallSet<Decl*, 16> Inits;
2003 for (const auto *I: Constructor->inits()) {
2004 if (FieldDecl *FD = I->getMember())
2006 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2007 Inits.insert(ID->chain_begin(), ID->chain_end());
2010 bool Diagnosed = false;
2011 for (auto *I : RD->fields())
2012 CheckConstexprCtorInitializer(*this, Dcl, I, Inits, Diagnosed);
2018 if (ReturnStmts.empty()) {
2019 // C++1y doesn't require constexpr functions to contain a 'return'
2020 // statement. We still do, unless the return type might be void, because
2021 // otherwise if there's no return statement, the function cannot
2022 // be used in a core constant expression.
2023 bool OK = getLangOpts().CPlusPlus14 &&
2024 (Dcl->getReturnType()->isVoidType() ||
2025 Dcl->getReturnType()->isDependentType());
2026 Diag(Dcl->getLocation(),
2027 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2028 : diag::err_constexpr_body_no_return);
2031 } else if (ReturnStmts.size() > 1) {
2032 Diag(ReturnStmts.back(),
2033 getLangOpts().CPlusPlus14
2034 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2035 : diag::ext_constexpr_body_multiple_return);
2036 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2037 Diag(ReturnStmts[I], diag::note_constexpr_body_previous_return);
2041 // C++11 [dcl.constexpr]p5:
2042 // if no function argument values exist such that the function invocation
2043 // substitution would produce a constant expression, the program is
2044 // ill-formed; no diagnostic required.
2045 // C++11 [dcl.constexpr]p3:
2046 // - every constructor call and implicit conversion used in initializing the
2047 // return value shall be one of those allowed in a constant expression.
2048 // C++11 [dcl.constexpr]p4:
2049 // - every constructor involved in initializing non-static data members and
2050 // base class sub-objects shall be a constexpr constructor.
2051 SmallVector<PartialDiagnosticAt, 8> Diags;
2052 if (!Expr::isPotentialConstantExpr(Dcl, Diags)) {
2053 Diag(Dcl->getLocation(), diag::ext_constexpr_function_never_constant_expr)
2054 << isa<CXXConstructorDecl>(Dcl);
2055 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2056 Diag(Diags[I].first, Diags[I].second);
2057 // Don't return false here: we allow this for compatibility in
2064 /// isCurrentClassName - Determine whether the identifier II is the
2065 /// name of the class type currently being defined. In the case of
2066 /// nested classes, this will only return true if II is the name of
2067 /// the innermost class.
2068 bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *,
2069 const CXXScopeSpec *SS) {
2070 assert(getLangOpts().CPlusPlus && "No class names in C!");
2072 CXXRecordDecl *CurDecl;
2073 if (SS && SS->isSet() && !SS->isInvalid()) {
2074 DeclContext *DC = computeDeclContext(*SS, true);
2075 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2077 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2079 if (CurDecl && CurDecl->getIdentifier())
2080 return &II == CurDecl->getIdentifier();
2084 /// \brief Determine whether the identifier II is a typo for the name of
2085 /// the class type currently being defined. If so, update it to the identifier
2086 /// that should have been used.
2087 bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2088 assert(getLangOpts().CPlusPlus && "No class names in C!");
2090 if (!getLangOpts().SpellChecking)
2093 CXXRecordDecl *CurDecl;
2094 if (SS && SS->isSet() && !SS->isInvalid()) {
2095 DeclContext *DC = computeDeclContext(*SS, true);
2096 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2098 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2100 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2101 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2102 < II->getLength()) {
2103 II = CurDecl->getIdentifier();
2110 /// \brief Determine whether the given class is a base class of the given
2111 /// class, including looking at dependent bases.
2112 static bool findCircularInheritance(const CXXRecordDecl *Class,
2113 const CXXRecordDecl *Current) {
2114 SmallVector<const CXXRecordDecl*, 8> Queue;
2116 Class = Class->getCanonicalDecl();
2118 for (const auto &I : Current->bases()) {
2119 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2123 Base = Base->getDefinition();
2127 if (Base->getCanonicalDecl() == Class)
2130 Queue.push_back(Base);
2136 Current = Queue.pop_back_val();
2142 /// \brief Check the validity of a C++ base class specifier.
2144 /// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2145 /// and returns NULL otherwise.
2147 Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2148 SourceRange SpecifierRange,
2149 bool Virtual, AccessSpecifier Access,
2150 TypeSourceInfo *TInfo,
2151 SourceLocation EllipsisLoc) {
2152 QualType BaseType = TInfo->getType();
2154 // C++ [class.union]p1:
2155 // A union shall not have base classes.
2156 if (Class->isUnion()) {
2157 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2162 if (EllipsisLoc.isValid() &&
2163 !TInfo->getType()->containsUnexpandedParameterPack()) {
2164 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2165 << TInfo->getTypeLoc().getSourceRange();
2166 EllipsisLoc = SourceLocation();
2169 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2171 if (BaseType->isDependentType()) {
2172 // Make sure that we don't have circular inheritance among our dependent
2173 // bases. For non-dependent bases, the check for completeness below handles
2175 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2176 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2177 ((BaseDecl = BaseDecl->getDefinition()) &&
2178 findCircularInheritance(Class, BaseDecl))) {
2179 Diag(BaseLoc, diag::err_circular_inheritance)
2180 << BaseType << Context.getTypeDeclType(Class);
2182 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2183 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2190 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2191 Class->getTagKind() == TTK_Class,
2192 Access, TInfo, EllipsisLoc);
2195 // Base specifiers must be record types.
2196 if (!BaseType->isRecordType()) {
2197 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2201 // C++ [class.union]p1:
2202 // A union shall not be used as a base class.
2203 if (BaseType->isUnionType()) {
2204 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2208 // For the MS ABI, propagate DLL attributes to base class templates.
2209 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
2210 if (Attr *ClassAttr = getDLLAttr(Class)) {
2211 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2212 BaseType->getAsCXXRecordDecl())) {
2213 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2219 // C++ [class.derived]p2:
2220 // The class-name in a base-specifier shall not be an incompletely
2222 if (RequireCompleteType(BaseLoc, BaseType,
2223 diag::err_incomplete_base_class, SpecifierRange)) {
2224 Class->setInvalidDecl();
2228 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2229 RecordDecl *BaseDecl = BaseType->getAs<RecordType>()->getDecl();
2230 assert(BaseDecl && "Record type has no declaration");
2231 BaseDecl = BaseDecl->getDefinition();
2232 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2233 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2234 assert(CXXBaseDecl && "Base type is not a C++ type");
2236 // A class which contains a flexible array member is not suitable for use as a
2238 // - If the layout determines that a base comes before another base,
2239 // the flexible array member would index into the subsequent base.
2240 // - If the layout determines that base comes before the derived class,
2241 // the flexible array member would index into the derived class.
2242 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2243 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2244 << CXXBaseDecl->getDeclName();
2249 // If a class is marked final and it appears as a base-type-specifier in
2250 // base-clause, the program is ill-formed.
2251 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2252 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2253 << CXXBaseDecl->getDeclName()
2254 << FA->isSpelledAsSealed();
2255 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2256 << CXXBaseDecl->getDeclName() << FA->getRange();
2260 if (BaseDecl->isInvalidDecl())
2261 Class->setInvalidDecl();
2263 // Create the base specifier.
2264 return new (Context) CXXBaseSpecifier(SpecifierRange, Virtual,
2265 Class->getTagKind() == TTK_Class,
2266 Access, TInfo, EllipsisLoc);
2269 /// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2270 /// one entry in the base class list of a class specifier, for
2272 /// class foo : public bar, virtual private baz {
2273 /// 'public bar' and 'virtual private baz' are each base-specifiers.
2275 Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2276 ParsedAttributes &Attributes,
2277 bool Virtual, AccessSpecifier Access,
2278 ParsedType basetype, SourceLocation BaseLoc,
2279 SourceLocation EllipsisLoc) {
2283 AdjustDeclIfTemplate(classdecl);
2284 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2288 // We haven't yet attached the base specifiers.
2289 Class->setIsParsingBaseSpecifiers();
2291 // We do not support any C++11 attributes on base-specifiers yet.
2292 // Diagnose any attributes we see.
2293 if (!Attributes.empty()) {
2294 for (AttributeList *Attr = Attributes.getList(); Attr;
2295 Attr = Attr->getNext()) {
2296 if (Attr->isInvalid() ||
2297 Attr->getKind() == AttributeList::IgnoredAttribute)
2299 Diag(Attr->getLoc(),
2300 Attr->getKind() == AttributeList::UnknownAttribute
2301 ? diag::warn_unknown_attribute_ignored
2302 : diag::err_base_specifier_attribute)
2307 TypeSourceInfo *TInfo = nullptr;
2308 GetTypeFromParser(basetype, &TInfo);
2310 if (EllipsisLoc.isInvalid() &&
2311 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2315 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2316 Virtual, Access, TInfo,
2320 Class->setInvalidDecl();
2325 /// Use small set to collect indirect bases. As this is only used
2326 /// locally, there's no need to abstract the small size parameter.
2327 typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2329 /// \brief Recursively add the bases of Type. Don't add Type itself.
2331 NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2332 const QualType &Type)
2334 // Even though the incoming type is a base, it might not be
2335 // a class -- it could be a template parm, for instance.
2336 if (auto Rec = Type->getAs<RecordType>()) {
2337 auto Decl = Rec->getAsCXXRecordDecl();
2339 // Iterate over its bases.
2340 for (const auto &BaseSpec : Decl->bases()) {
2341 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2342 .getUnqualifiedType();
2343 if (Set.insert(Base).second)
2344 // If we've not already seen it, recurse.
2345 NoteIndirectBases(Context, Set, Base);
2350 /// \brief Performs the actual work of attaching the given base class
2351 /// specifiers to a C++ class.
2352 bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2353 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2357 // Used to keep track of which base types we have already seen, so
2358 // that we can properly diagnose redundant direct base types. Note
2359 // that the key is always the unqualified canonical type of the base
2361 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2363 // Used to track indirect bases so we can see if a direct base is
2365 IndirectBaseSet IndirectBaseTypes;
2367 // Copy non-redundant base specifiers into permanent storage.
2368 unsigned NumGoodBases = 0;
2369 bool Invalid = false;
2370 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2371 QualType NewBaseType
2372 = Context.getCanonicalType(Bases[idx]->getType());
2373 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2375 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2377 // C++ [class.mi]p3:
2378 // A class shall not be specified as a direct base class of a
2379 // derived class more than once.
2380 Diag(Bases[idx]->getLocStart(),
2381 diag::err_duplicate_base_class)
2382 << KnownBase->getType()
2383 << Bases[idx]->getSourceRange();
2385 // Delete the duplicate base class specifier; we're going to
2386 // overwrite its pointer later.
2387 Context.Deallocate(Bases[idx]);
2391 // Okay, add this new base class.
2392 KnownBase = Bases[idx];
2393 Bases[NumGoodBases++] = Bases[idx];
2395 // Note this base's direct & indirect bases, if there could be ambiguity.
2396 if (Bases.size() > 1)
2397 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2399 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2400 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2401 if (Class->isInterface() &&
2402 (!RD->isInterfaceLike() ||
2403 KnownBase->getAccessSpecifier() != AS_public)) {
2404 // The Microsoft extension __interface does not permit bases that
2405 // are not themselves public interfaces.
2406 Diag(KnownBase->getLocStart(), diag::err_invalid_base_in_interface)
2407 << getRecordDiagFromTagKind(RD->getTagKind()) << RD->getName()
2408 << RD->getSourceRange();
2411 if (RD->hasAttr<WeakAttr>())
2412 Class->addAttr(WeakAttr::CreateImplicit(Context));
2417 // Attach the remaining base class specifiers to the derived class.
2418 Class->setBases(Bases.data(), NumGoodBases);
2420 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2421 // Check whether this direct base is inaccessible due to ambiguity.
2422 QualType BaseType = Bases[idx]->getType();
2423 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
2424 .getUnqualifiedType();
2426 if (IndirectBaseTypes.count(CanonicalBase)) {
2427 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2428 /*DetectVirtual=*/true);
2430 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
2434 if (Paths.isAmbiguous(CanonicalBase))
2435 Diag(Bases[idx]->getLocStart (), diag::warn_inaccessible_base_class)
2436 << BaseType << getAmbiguousPathsDisplayString(Paths)
2437 << Bases[idx]->getSourceRange();
2439 assert(Bases[idx]->isVirtual());
2442 // Delete the base class specifier, since its data has been copied
2443 // into the CXXRecordDecl.
2444 Context.Deallocate(Bases[idx]);
2450 /// ActOnBaseSpecifiers - Attach the given base specifiers to the
2451 /// class, after checking whether there are any duplicate base
2453 void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
2454 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2455 if (!ClassDecl || Bases.empty())
2458 AdjustDeclIfTemplate(ClassDecl);
2459 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
2462 /// \brief Determine whether the type \p Derived is a C++ class that is
2463 /// derived from the type \p Base.
2464 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
2465 if (!getLangOpts().CPlusPlus)
2468 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2472 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2476 // If either the base or the derived type is invalid, don't try to
2477 // check whether one is derived from the other.
2478 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
2481 // FIXME: In a modules build, do we need the entire path to be visible for us
2482 // to be able to use the inheritance relationship?
2483 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2486 return DerivedRD->isDerivedFrom(BaseRD);
2489 /// \brief Determine whether the type \p Derived is a C++ class that is
2490 /// derived from the type \p Base.
2491 bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
2492 CXXBasePaths &Paths) {
2493 if (!getLangOpts().CPlusPlus)
2496 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
2500 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
2504 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
2507 return DerivedRD->isDerivedFrom(BaseRD, Paths);
2510 static void BuildBasePathArray(const CXXBasePath &Path,
2511 CXXCastPath &BasePathArray) {
2512 // We first go backward and check if we have a virtual base.
2513 // FIXME: It would be better if CXXBasePath had the base specifier for
2514 // the nearest virtual base.
2516 for (unsigned I = Path.size(); I != 0; --I) {
2517 if (Path[I - 1].Base->isVirtual()) {
2523 // Now add all bases.
2524 for (unsigned I = Start, E = Path.size(); I != E; ++I)
2525 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
2529 void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
2530 CXXCastPath &BasePathArray) {
2531 assert(BasePathArray.empty() && "Base path array must be empty!");
2532 assert(Paths.isRecordingPaths() && "Must record paths!");
2533 return ::BuildBasePathArray(Paths.front(), BasePathArray);
2535 /// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
2536 /// conversion (where Derived and Base are class types) is
2537 /// well-formed, meaning that the conversion is unambiguous (and
2538 /// that all of the base classes are accessible). Returns true
2539 /// and emits a diagnostic if the code is ill-formed, returns false
2540 /// otherwise. Loc is the location where this routine should point to
2541 /// if there is an error, and Range is the source range to highlight
2542 /// if there is an error.
2544 /// If either InaccessibleBaseID or AmbigiousBaseConvID are 0, then the
2545 /// diagnostic for the respective type of error will be suppressed, but the
2546 /// check for ill-formed code will still be performed.
2548 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2549 unsigned InaccessibleBaseID,
2550 unsigned AmbigiousBaseConvID,
2551 SourceLocation Loc, SourceRange Range,
2552 DeclarationName Name,
2553 CXXCastPath *BasePath,
2554 bool IgnoreAccess) {
2555 // First, determine whether the path from Derived to Base is
2556 // ambiguous. This is slightly more expensive than checking whether
2557 // the Derived to Base conversion exists, because here we need to
2558 // explore multiple paths to determine if there is an ambiguity.
2559 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2560 /*DetectVirtual=*/false);
2561 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2562 if (!DerivationOkay)
2565 const CXXBasePath *Path = nullptr;
2566 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
2567 Path = &Paths.front();
2569 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
2570 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
2571 // user to access such bases.
2572 if (!Path && getLangOpts().MSVCCompat) {
2573 for (const CXXBasePath &PossiblePath : Paths) {
2574 if (PossiblePath.size() == 1) {
2575 Path = &PossiblePath;
2576 if (AmbigiousBaseConvID)
2577 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
2578 << Base << Derived << Range;
2585 if (!IgnoreAccess) {
2586 // Check that the base class can be accessed.
2588 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
2589 case AR_inaccessible:
2598 // Build a base path if necessary.
2600 ::BuildBasePathArray(*Path, *BasePath);
2604 if (AmbigiousBaseConvID) {
2605 // We know that the derived-to-base conversion is ambiguous, and
2606 // we're going to produce a diagnostic. Perform the derived-to-base
2607 // search just one more time to compute all of the possible paths so
2608 // that we can print them out. This is more expensive than any of
2609 // the previous derived-to-base checks we've done, but at this point
2610 // performance isn't as much of an issue.
2612 Paths.setRecordingPaths(true);
2613 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
2614 assert(StillOkay && "Can only be used with a derived-to-base conversion");
2617 // Build up a textual representation of the ambiguous paths, e.g.,
2618 // D -> B -> A, that will be used to illustrate the ambiguous
2619 // conversions in the diagnostic. We only print one of the paths
2620 // to each base class subobject.
2621 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
2623 Diag(Loc, AmbigiousBaseConvID)
2624 << Derived << Base << PathDisplayStr << Range << Name;
2630 Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
2631 SourceLocation Loc, SourceRange Range,
2632 CXXCastPath *BasePath,
2633 bool IgnoreAccess) {
2634 return CheckDerivedToBaseConversion(
2635 Derived, Base, diag::err_upcast_to_inaccessible_base,
2636 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
2637 BasePath, IgnoreAccess);
2641 /// @brief Builds a string representing ambiguous paths from a
2642 /// specific derived class to different subobjects of the same base
2645 /// This function builds a string that can be used in error messages
2646 /// to show the different paths that one can take through the
2647 /// inheritance hierarchy to go from the derived class to different
2648 /// subobjects of a base class. The result looks something like this:
2650 /// struct D -> struct B -> struct A
2651 /// struct D -> struct C -> struct A
2653 std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
2654 std::string PathDisplayStr;
2655 std::set<unsigned> DisplayedPaths;
2656 for (CXXBasePaths::paths_iterator Path = Paths.begin();
2657 Path != Paths.end(); ++Path) {
2658 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
2659 // We haven't displayed a path to this particular base
2660 // class subobject yet.
2661 PathDisplayStr += "\n ";
2662 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
2663 for (CXXBasePath::const_iterator Element = Path->begin();
2664 Element != Path->end(); ++Element)
2665 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
2669 return PathDisplayStr;
2672 //===----------------------------------------------------------------------===//
2673 // C++ class member Handling
2674 //===----------------------------------------------------------------------===//
2676 /// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
2677 bool Sema::ActOnAccessSpecifier(AccessSpecifier Access,
2678 SourceLocation ASLoc,
2679 SourceLocation ColonLoc,
2680 AttributeList *Attrs) {
2681 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
2682 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(Context, Access, CurContext,
2684 CurContext->addHiddenDecl(ASDecl);
2685 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
2688 /// CheckOverrideControl - Check C++11 override control semantics.
2689 void Sema::CheckOverrideControl(NamedDecl *D) {
2690 if (D->isInvalidDecl())
2693 // We only care about "override" and "final" declarations.
2694 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
2697 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2699 // We can't check dependent instance methods.
2700 if (MD && MD->isInstance() &&
2701 (MD->getParent()->hasAnyDependentBases() ||
2702 MD->getType()->isDependentType()))
2705 if (MD && !MD->isVirtual()) {
2706 // If we have a non-virtual method, check if if hides a virtual method.
2707 // (In that case, it's most likely the method has the wrong type.)
2708 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
2709 FindHiddenVirtualMethods(MD, OverloadedMethods);
2711 if (!OverloadedMethods.empty()) {
2712 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2713 Diag(OA->getLocation(),
2714 diag::override_keyword_hides_virtual_member_function)
2715 << "override" << (OverloadedMethods.size() > 1);
2716 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2717 Diag(FA->getLocation(),
2718 diag::override_keyword_hides_virtual_member_function)
2719 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2720 << (OverloadedMethods.size() > 1);
2722 NoteHiddenVirtualMethods(MD, OverloadedMethods);
2723 MD->setInvalidDecl();
2726 // Fall through into the general case diagnostic.
2727 // FIXME: We might want to attempt typo correction here.
2730 if (!MD || !MD->isVirtual()) {
2731 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
2732 Diag(OA->getLocation(),
2733 diag::override_keyword_only_allowed_on_virtual_member_functions)
2734 << "override" << FixItHint::CreateRemoval(OA->getLocation());
2735 D->dropAttr<OverrideAttr>();
2737 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
2738 Diag(FA->getLocation(),
2739 diag::override_keyword_only_allowed_on_virtual_member_functions)
2740 << (FA->isSpelledAsSealed() ? "sealed" : "final")
2741 << FixItHint::CreateRemoval(FA->getLocation());
2742 D->dropAttr<FinalAttr>();
2747 // C++11 [class.virtual]p5:
2748 // If a function is marked with the virt-specifier override and
2749 // does not override a member function of a base class, the program is
2751 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
2752 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
2753 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
2754 << MD->getDeclName();
2757 void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D) {
2758 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
2760 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
2761 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
2764 SourceLocation Loc = MD->getLocation();
2765 SourceLocation SpellingLoc = Loc;
2766 if (getSourceManager().isMacroArgExpansion(Loc))
2767 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).first;
2768 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
2769 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
2772 if (MD->size_overridden_methods() > 0) {
2773 unsigned DiagID = isa<CXXDestructorDecl>(MD)
2774 ? diag::warn_destructor_marked_not_override_overriding
2775 : diag::warn_function_marked_not_override_overriding;
2776 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
2777 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
2778 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
2782 /// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
2783 /// function overrides a virtual member function marked 'final', according to
2784 /// C++11 [class.virtual]p4.
2785 bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
2786 const CXXMethodDecl *Old) {
2787 FinalAttr *FA = Old->getAttr<FinalAttr>();
2791 Diag(New->getLocation(), diag::err_final_function_overridden)
2792 << New->getDeclName()
2793 << FA->isSpelledAsSealed();
2794 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
2798 static bool InitializationHasSideEffects(const FieldDecl &FD) {
2799 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
2800 // FIXME: Destruction of ObjC lifetime types has side-effects.
2801 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
2802 return !RD->isCompleteDefinition() ||
2803 !RD->hasTrivialDefaultConstructor() ||
2804 !RD->hasTrivialDestructor();
2808 static AttributeList *getMSPropertyAttr(AttributeList *list) {
2809 for (AttributeList *it = list; it != nullptr; it = it->getNext())
2810 if (it->isDeclspecPropertyAttribute())
2815 // Check if there is a field shadowing.
2816 void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
2817 DeclarationName FieldName,
2818 const CXXRecordDecl *RD) {
2819 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
2822 // To record a shadowed field in a base
2823 std::map<CXXRecordDecl*, NamedDecl*> Bases;
2824 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
2825 CXXBasePath &Path) {
2826 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
2827 // Record an ambiguous path directly
2828 if (Bases.find(Base) != Bases.end())
2830 for (const auto Field : Base->lookup(FieldName)) {
2831 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
2832 Field->getAccess() != AS_private) {
2833 assert(Field->getAccess() != AS_none);
2834 assert(Bases.find(Base) == Bases.end());
2835 Bases[Base] = Field;
2842 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
2843 /*DetectVirtual=*/true);
2844 if (!RD->lookupInBases(FieldShadowed, Paths))
2847 for (const auto &P : Paths) {
2848 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
2849 auto It = Bases.find(Base);
2850 // Skip duplicated bases
2851 if (It == Bases.end())
2853 auto BaseField = It->second;
2854 assert(BaseField->getAccess() != AS_private);
2856 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
2857 Diag(Loc, diag::warn_shadow_field)
2858 << FieldName.getAsString() << RD->getName() << Base->getName();
2859 Diag(BaseField->getLocation(), diag::note_shadow_field);
2865 /// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
2866 /// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
2867 /// bitfield width if there is one, 'InitExpr' specifies the initializer if
2868 /// one has been parsed, and 'InitStyle' is set if an in-class initializer is
2869 /// present (but parsing it has been deferred).
2871 Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
2872 MultiTemplateParamsArg TemplateParameterLists,
2873 Expr *BW, const VirtSpecifiers &VS,
2874 InClassInitStyle InitStyle) {
2875 const DeclSpec &DS = D.getDeclSpec();
2876 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
2877 DeclarationName Name = NameInfo.getName();
2878 SourceLocation Loc = NameInfo.getLoc();
2880 // For anonymous bitfields, the location should point to the type.
2881 if (Loc.isInvalid())
2882 Loc = D.getLocStart();
2884 Expr *BitWidth = static_cast<Expr*>(BW);
2886 assert(isa<CXXRecordDecl>(CurContext));
2887 assert(!DS.isFriendSpecified());
2889 bool isFunc = D.isDeclarationOfFunction();
2890 AttributeList *MSPropertyAttr =
2891 getMSPropertyAttr(D.getDeclSpec().getAttributes().getList());
2893 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
2894 // The Microsoft extension __interface only permits public member functions
2895 // and prohibits constructors, destructors, operators, non-public member
2896 // functions, static methods and data members.
2897 unsigned InvalidDecl;
2898 bool ShowDeclName = true;
2900 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
2904 else if (AS != AS_public)
2906 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
2908 else switch (Name.getNameKind()) {
2909 case DeclarationName::CXXConstructorName:
2911 ShowDeclName = false;
2914 case DeclarationName::CXXDestructorName:
2916 ShowDeclName = false;
2919 case DeclarationName::CXXOperatorName:
2920 case DeclarationName::CXXConversionFunctionName:
2931 Diag(Loc, diag::err_invalid_member_in_interface)
2932 << (InvalidDecl-1) << Name;
2934 Diag(Loc, diag::err_invalid_member_in_interface)
2935 << (InvalidDecl-1) << "";
2940 // C++ 9.2p6: A member shall not be declared to have automatic storage
2941 // duration (auto, register) or with the extern storage-class-specifier.
2942 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
2943 // data members and cannot be applied to names declared const or static,
2944 // and cannot be applied to reference members.
2945 switch (DS.getStorageClassSpec()) {
2946 case DeclSpec::SCS_unspecified:
2947 case DeclSpec::SCS_typedef:
2948 case DeclSpec::SCS_static:
2950 case DeclSpec::SCS_mutable:
2952 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
2954 // FIXME: It would be nicer if the keyword was ignored only for this
2955 // declarator. Otherwise we could get follow-up errors.
2956 D.getMutableDeclSpec().ClearStorageClassSpecs();
2960 Diag(DS.getStorageClassSpecLoc(),
2961 diag::err_storageclass_invalid_for_member);
2962 D.getMutableDeclSpec().ClearStorageClassSpecs();
2966 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
2967 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
2970 if (DS.isConstexprSpecified() && isInstField) {
2971 SemaDiagnosticBuilder B =
2972 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
2973 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
2974 if (InitStyle == ICIS_NoInit) {
2976 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
2977 B << FixItHint::CreateRemoval(ConstexprLoc);
2979 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
2980 D.getMutableDeclSpec().ClearConstexprSpec();
2981 const char *PrevSpec;
2983 bool Failed = D.getMutableDeclSpec().SetTypeQual(
2984 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
2986 assert(!Failed && "Making a constexpr member const shouldn't fail");
2990 const char *PrevSpec;
2992 if (D.getMutableDeclSpec().SetStorageClassSpec(
2993 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
2994 Context.getPrintingPolicy())) {
2995 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
2996 "This is the only DeclSpec that should fail to be applied");
2999 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3000 isInstField = false;
3007 CXXScopeSpec &SS = D.getCXXScopeSpec();
3009 // Data members must have identifiers for names.
3010 if (!Name.isIdentifier()) {
3011 Diag(Loc, diag::err_bad_variable_name)
3016 IdentifierInfo *II = Name.getAsIdentifierInfo();
3018 // Member field could not be with "template" keyword.
3019 // So TemplateParameterLists should be empty in this case.
3020 if (TemplateParameterLists.size()) {
3021 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3022 if (TemplateParams->size()) {
3023 // There is no such thing as a member field template.
3024 Diag(D.getIdentifierLoc(), diag::err_template_member)
3026 << SourceRange(TemplateParams->getTemplateLoc(),
3027 TemplateParams->getRAngleLoc());
3029 // There is an extraneous 'template<>' for this member.
3030 Diag(TemplateParams->getTemplateLoc(),
3031 diag::err_template_member_noparams)
3033 << SourceRange(TemplateParams->getTemplateLoc(),
3034 TemplateParams->getRAngleLoc());
3039 if (SS.isSet() && !SS.isInvalid()) {
3040 // The user provided a superfluous scope specifier inside a class
3046 if (DeclContext *DC = computeDeclContext(SS, false))
3047 diagnoseQualifiedDeclaration(SS, DC, Name, D.getIdentifierLoc());
3049 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3050 << Name << SS.getRange();
3055 if (MSPropertyAttr) {
3056 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3057 BitWidth, InitStyle, AS, MSPropertyAttr);
3060 isInstField = false;
3062 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3063 BitWidth, InitStyle, AS);
3068 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3070 Member = HandleDeclarator(S, D, TemplateParameterLists);
3074 // Non-instance-fields can't have a bitfield.
3076 if (Member->isInvalidDecl()) {
3077 // don't emit another diagnostic.
3078 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3079 // C++ 9.6p3: A bit-field shall not be a static member.
3080 // "static member 'A' cannot be a bit-field"
3081 Diag(Loc, diag::err_static_not_bitfield)
3082 << Name << BitWidth->getSourceRange();
3083 } else if (isa<TypedefDecl>(Member)) {
3084 // "typedef member 'x' cannot be a bit-field"
3085 Diag(Loc, diag::err_typedef_not_bitfield)
3086 << Name << BitWidth->getSourceRange();
3088 // A function typedef ("typedef int f(); f a;").
3089 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3090 Diag(Loc, diag::err_not_integral_type_bitfield)
3091 << Name << cast<ValueDecl>(Member)->getType()
3092 << BitWidth->getSourceRange();
3096 Member->setInvalidDecl();
3099 Member->setAccess(AS);
3101 // If we have declared a member function template or static data member
3102 // template, set the access of the templated declaration as well.
3103 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3104 FunTmpl->getTemplatedDecl()->setAccess(AS);
3105 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3106 VarTmpl->getTemplatedDecl()->setAccess(AS);
3109 if (VS.isOverrideSpecified())
3110 Member->addAttr(new (Context) OverrideAttr(VS.getOverrideLoc(), Context, 0));
3111 if (VS.isFinalSpecified())
3112 Member->addAttr(new (Context) FinalAttr(VS.getFinalLoc(), Context,
3113 VS.isFinalSpelledSealed()));
3115 if (VS.getLastLocation().isValid()) {
3116 // Update the end location of a method that has a virt-specifiers.
3117 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3118 MD->setRangeEnd(VS.getLastLocation());
3121 CheckOverrideControl(Member);
3123 assert((Name || isInstField) && "No identifier for non-field ?");
3126 FieldDecl *FD = cast<FieldDecl>(Member);
3127 FieldCollector->Add(FD);
3129 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3130 // Remember all explicit private FieldDecls that have a name, no side
3131 // effects and are not part of a dependent type declaration.
3132 if (!FD->isImplicit() && FD->getDeclName() &&
3133 FD->getAccess() == AS_private &&
3134 !FD->hasAttr<UnusedAttr>() &&
3135 !FD->getParent()->isDependentContext() &&
3136 !InitializationHasSideEffects(*FD))
3137 UnusedPrivateFields.insert(FD);
3145 class UninitializedFieldVisitor
3146 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3148 // List of Decls to generate a warning on. Also remove Decls that become
3150 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3151 // List of base classes of the record. Classes are removed after their
3153 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3154 // Vector of decls to be removed from the Decl set prior to visiting the
3155 // nodes. These Decls may have been initialized in the prior initializer.
3156 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3157 // If non-null, add a note to the warning pointing back to the constructor.
3158 const CXXConstructorDecl *Constructor;
3159 // Variables to hold state when processing an initializer list. When
3160 // InitList is true, special case initialization of FieldDecls matching
3161 // InitListFieldDecl.
3163 FieldDecl *InitListFieldDecl;
3164 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3167 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3168 UninitializedFieldVisitor(Sema &S,
3169 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3170 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3171 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3172 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3174 // Returns true if the use of ME is not an uninitialized use.
3175 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3176 bool CheckReferenceOnly) {
3177 llvm::SmallVector<FieldDecl*, 4> Fields;
3178 bool ReferenceField = false;
3180 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3183 Fields.push_back(FD);
3184 if (FD->getType()->isReferenceType())
3185 ReferenceField = true;
3186 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3189 // Binding a reference to an unintialized field is not an
3190 // uninitialized use.
3191 if (CheckReferenceOnly && !ReferenceField)
3194 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3195 // Discard the first field since it is the field decl that is being
3197 for (auto I = Fields.rbegin() + 1, E = Fields.rend(); I != E; ++I) {
3198 UsedFieldIndex.push_back((*I)->getFieldIndex());
3201 for (auto UsedIter = UsedFieldIndex.begin(),
3202 UsedEnd = UsedFieldIndex.end(),
3203 OrigIter = InitFieldIndex.begin(),
3204 OrigEnd = InitFieldIndex.end();
3205 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3206 if (*UsedIter < *OrigIter)
3208 if (*UsedIter > *OrigIter)
3215 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3217 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3220 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3222 MemberExpr *FieldME = ME;
3224 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3227 while (MemberExpr *SubME =
3228 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3230 if (isa<VarDecl>(SubME->getMemberDecl()))
3233 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3234 if (!FD->isAnonymousStructOrUnion())
3237 if (!FieldME->getType().isPODType(S.Context))
3238 AllPODFields = false;
3240 Base = SubME->getBase();
3243 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts()))
3246 if (AddressOf && AllPODFields)
3249 ValueDecl* FoundVD = FieldME->getMemberDecl();
3251 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3252 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3253 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3256 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3257 QualType T = BaseCast->getType();
3258 if (T->isPointerType() &&
3259 BaseClasses.count(T->getPointeeType())) {
3260 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3261 << T->getPointeeType() << FoundVD;
3266 if (!Decls.count(FoundVD))
3269 const bool IsReference = FoundVD->getType()->isReferenceType();
3271 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3272 // Special checking for initializer lists.
3273 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3277 // Prevent double warnings on use of unbounded references.
3278 if (CheckReferenceOnly && !IsReference)
3282 unsigned diag = IsReference
3283 ? diag::warn_reference_field_is_uninit
3284 : diag::warn_field_is_uninit;
3285 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3287 S.Diag(Constructor->getLocation(),
3288 diag::note_uninit_in_this_constructor)
3289 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3293 void HandleValue(Expr *E, bool AddressOf) {
3294 E = E->IgnoreParens();
3296 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3297 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3298 AddressOf /*AddressOf*/);
3302 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3303 Visit(CO->getCond());
3304 HandleValue(CO->getTrueExpr(), AddressOf);
3305 HandleValue(CO->getFalseExpr(), AddressOf);
3309 if (BinaryConditionalOperator *BCO =
3310 dyn_cast<BinaryConditionalOperator>(E)) {
3311 Visit(BCO->getCond());
3312 HandleValue(BCO->getFalseExpr(), AddressOf);
3316 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3317 HandleValue(OVE->getSourceExpr(), AddressOf);
3321 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3322 switch (BO->getOpcode()) {
3327 HandleValue(BO->getLHS(), AddressOf);
3328 Visit(BO->getRHS());
3331 Visit(BO->getLHS());
3332 HandleValue(BO->getRHS(), AddressOf);
3340 void CheckInitListExpr(InitListExpr *ILE) {
3341 InitFieldIndex.push_back(0);
3342 for (auto Child : ILE->children()) {
3343 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3344 CheckInitListExpr(SubList);
3348 ++InitFieldIndex.back();
3350 InitFieldIndex.pop_back();
3353 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3354 FieldDecl *Field, const Type *BaseClass) {
3355 // Remove Decls that may have been initialized in the previous
3357 for (ValueDecl* VD : DeclsToRemove)
3359 DeclsToRemove.clear();
3361 Constructor = FieldConstructor;
3362 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3366 InitListFieldDecl = Field;
3367 InitFieldIndex.clear();
3368 CheckInitListExpr(ILE);
3377 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
3380 void VisitMemberExpr(MemberExpr *ME) {
3381 // All uses of unbounded reference fields will warn.
3382 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
3385 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3386 if (E->getCastKind() == CK_LValueToRValue) {
3387 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3391 Inherited::VisitImplicitCastExpr(E);
3394 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3395 if (E->getConstructor()->isCopyConstructor()) {
3396 Expr *ArgExpr = E->getArg(0);
3397 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
3398 if (ILE->getNumInits() == 1)
3399 ArgExpr = ILE->getInit(0);
3400 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
3401 if (ICE->getCastKind() == CK_NoOp)
3402 ArgExpr = ICE->getSubExpr();
3403 HandleValue(ArgExpr, false /*AddressOf*/);
3406 Inherited::VisitCXXConstructExpr(E);
3409 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
3410 Expr *Callee = E->getCallee();
3411 if (isa<MemberExpr>(Callee)) {
3412 HandleValue(Callee, false /*AddressOf*/);
3413 for (auto Arg : E->arguments())
3418 Inherited::VisitCXXMemberCallExpr(E);
3421 void VisitCallExpr(CallExpr *E) {
3422 // Treat std::move as a use.
3423 if (E->isCallToStdMove()) {
3424 HandleValue(E->getArg(0), /*AddressOf=*/false);
3428 Inherited::VisitCallExpr(E);
3431 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
3432 Expr *Callee = E->getCallee();
3434 if (isa<UnresolvedLookupExpr>(Callee))
3435 return Inherited::VisitCXXOperatorCallExpr(E);
3438 for (auto Arg : E->arguments())
3439 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
3442 void VisitBinaryOperator(BinaryOperator *E) {
3443 // If a field assignment is detected, remove the field from the
3444 // uninitiailized field set.
3445 if (E->getOpcode() == BO_Assign)
3446 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
3447 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
3448 if (!FD->getType()->isReferenceType())
3449 DeclsToRemove.push_back(FD);
3451 if (E->isCompoundAssignmentOp()) {
3452 HandleValue(E->getLHS(), false /*AddressOf*/);
3457 Inherited::VisitBinaryOperator(E);
3460 void VisitUnaryOperator(UnaryOperator *E) {
3461 if (E->isIncrementDecrementOp()) {
3462 HandleValue(E->getSubExpr(), false /*AddressOf*/);
3465 if (E->getOpcode() == UO_AddrOf) {
3466 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
3467 HandleValue(ME->getBase(), true /*AddressOf*/);
3472 Inherited::VisitUnaryOperator(E);
3476 // Diagnose value-uses of fields to initialize themselves, e.g.
3478 // where foo is not also a parameter to the constructor.
3479 // Also diagnose across field uninitialized use such as
3481 // TODO: implement -Wuninitialized and fold this into that framework.
3482 static void DiagnoseUninitializedFields(
3483 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
3485 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
3486 Constructor->getLocation())) {
3490 if (Constructor->isInvalidDecl())
3493 const CXXRecordDecl *RD = Constructor->getParent();
3495 if (RD->getDescribedClassTemplate())
3498 // Holds fields that are uninitialized.
3499 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
3501 // At the beginning, all fields are uninitialized.
3502 for (auto *I : RD->decls()) {
3503 if (auto *FD = dyn_cast<FieldDecl>(I)) {
3504 UninitializedFields.insert(FD);
3505 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
3506 UninitializedFields.insert(IFD->getAnonField());
3510 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
3511 for (auto I : RD->bases())
3512 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
3514 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3517 UninitializedFieldVisitor UninitializedChecker(SemaRef,
3518 UninitializedFields,
3519 UninitializedBaseClasses);
3521 for (const auto *FieldInit : Constructor->inits()) {
3522 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
3525 Expr *InitExpr = FieldInit->getInit();
3529 if (CXXDefaultInitExpr *Default =
3530 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
3531 InitExpr = Default->getExpr();
3534 // In class initializers will point to the constructor.
3535 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
3536 FieldInit->getAnyMember(),
3537 FieldInit->getBaseClass());
3539 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
3540 FieldInit->getAnyMember(),
3541 FieldInit->getBaseClass());
3547 /// \brief Enter a new C++ default initializer scope. After calling this, the
3548 /// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
3549 /// parsing or instantiating the initializer failed.
3550 void Sema::ActOnStartCXXInClassMemberInitializer() {
3551 // Create a synthetic function scope to represent the call to the constructor
3552 // that notionally surrounds a use of this initializer.
3553 PushFunctionScope();
3556 /// \brief This is invoked after parsing an in-class initializer for a
3557 /// non-static C++ class member, and after instantiating an in-class initializer
3558 /// in a class template. Such actions are deferred until the class is complete.
3559 void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
3560 SourceLocation InitLoc,
3562 // Pop the notional constructor scope we created earlier.
3563 PopFunctionScopeInfo(nullptr, D);
3565 FieldDecl *FD = dyn_cast<FieldDecl>(D);
3566 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
3567 "must set init style when field is created");
3570 D->setInvalidDecl();
3572 FD->removeInClassInitializer();
3576 if (DiagnoseUnexpandedParameterPack(InitExpr, UPPC_Initializer)) {
3577 FD->setInvalidDecl();
3578 FD->removeInClassInitializer();
3582 ExprResult Init = InitExpr;
3583 if (!FD->getType()->isDependentType() && !InitExpr->isTypeDependent()) {
3584 InitializedEntity Entity = InitializedEntity::InitializeMember(FD);
3585 InitializationKind Kind = FD->getInClassInitStyle() == ICIS_ListInit
3586 ? InitializationKind::CreateDirectList(InitExpr->getLocStart())
3587 : InitializationKind::CreateCopy(InitExpr->getLocStart(), InitLoc);
3588 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
3589 Init = Seq.Perform(*this, Entity, Kind, InitExpr);
3590 if (Init.isInvalid()) {
3591 FD->setInvalidDecl();
3596 // C++11 [class.base.init]p7:
3597 // The initialization of each base and member constitutes a
3599 Init = ActOnFinishFullExpr(Init.get(), InitLoc);
3600 if (Init.isInvalid()) {
3601 FD->setInvalidDecl();
3605 InitExpr = Init.get();
3607 FD->setInClassInitializer(InitExpr);
3610 /// \brief Find the direct and/or virtual base specifiers that
3611 /// correspond to the given base type, for use in base initialization
3612 /// within a constructor.
3613 static bool FindBaseInitializer(Sema &SemaRef,
3614 CXXRecordDecl *ClassDecl,
3616 const CXXBaseSpecifier *&DirectBaseSpec,
3617 const CXXBaseSpecifier *&VirtualBaseSpec) {
3618 // First, check for a direct base class.
3619 DirectBaseSpec = nullptr;
3620 for (const auto &Base : ClassDecl->bases()) {
3621 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
3622 // We found a direct base of this type. That's what we're
3624 DirectBaseSpec = &Base;
3629 // Check for a virtual base class.
3630 // FIXME: We might be able to short-circuit this if we know in advance that
3631 // there are no virtual bases.
3632 VirtualBaseSpec = nullptr;
3633 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
3634 // We haven't found a base yet; search the class hierarchy for a
3635 // virtual base class.
3636 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3637 /*DetectVirtual=*/false);
3638 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
3639 SemaRef.Context.getTypeDeclType(ClassDecl),
3641 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3642 Path != Paths.end(); ++Path) {
3643 if (Path->back().Base->isVirtual()) {
3644 VirtualBaseSpec = Path->back().Base;
3651 return DirectBaseSpec || VirtualBaseSpec;
3654 /// \brief Handle a C++ member initializer using braced-init-list syntax.
3656 Sema::ActOnMemInitializer(Decl *ConstructorD,
3659 IdentifierInfo *MemberOrBase,
3660 ParsedType TemplateTypeTy,
3662 SourceLocation IdLoc,
3664 SourceLocation EllipsisLoc) {
3665 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3666 DS, IdLoc, InitList,
3670 /// \brief Handle a C++ member initializer using parentheses syntax.
3672 Sema::ActOnMemInitializer(Decl *ConstructorD,
3675 IdentifierInfo *MemberOrBase,
3676 ParsedType TemplateTypeTy,
3678 SourceLocation IdLoc,
3679 SourceLocation LParenLoc,
3680 ArrayRef<Expr *> Args,
3681 SourceLocation RParenLoc,
3682 SourceLocation EllipsisLoc) {
3683 Expr *List = new (Context) ParenListExpr(Context, LParenLoc,
3685 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
3686 DS, IdLoc, List, EllipsisLoc);
3691 // Callback to only accept typo corrections that can be a valid C++ member
3692 // intializer: either a non-static field member or a base class.
3693 class MemInitializerValidatorCCC : public CorrectionCandidateCallback {
3695 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
3696 : ClassDecl(ClassDecl) {}
3698 bool ValidateCandidate(const TypoCorrection &candidate) override {
3699 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
3700 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
3701 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
3702 return isa<TypeDecl>(ND);
3708 CXXRecordDecl *ClassDecl;
3713 /// \brief Handle a C++ member initializer.
3715 Sema::BuildMemInitializer(Decl *ConstructorD,
3718 IdentifierInfo *MemberOrBase,
3719 ParsedType TemplateTypeTy,
3721 SourceLocation IdLoc,
3723 SourceLocation EllipsisLoc) {
3724 ExprResult Res = CorrectDelayedTyposInExpr(Init);
3725 if (!Res.isUsable())
3732 AdjustDeclIfTemplate(ConstructorD);
3734 CXXConstructorDecl *Constructor
3735 = dyn_cast<CXXConstructorDecl>(ConstructorD);
3737 // The user wrote a constructor initializer on a function that is
3738 // not a C++ constructor. Ignore the error for now, because we may
3739 // have more member initializers coming; we'll diagnose it just
3740 // once in ActOnMemInitializers.
3744 CXXRecordDecl *ClassDecl = Constructor->getParent();
3746 // C++ [class.base.init]p2:
3747 // Names in a mem-initializer-id are looked up in the scope of the
3748 // constructor's class and, if not found in that scope, are looked
3749 // up in the scope containing the constructor's definition.
3750 // [Note: if the constructor's class contains a member with the
3751 // same name as a direct or virtual base class of the class, a
3752 // mem-initializer-id naming the member or base class and composed
3753 // of a single identifier refers to the class member. A
3754 // mem-initializer-id for the hidden base class may be specified
3755 // using a qualified name. ]
3756 if (!SS.getScopeRep() && !TemplateTypeTy) {
3757 // Look for a member, first.
3758 DeclContext::lookup_result Result = ClassDecl->lookup(MemberOrBase);
3759 if (!Result.empty()) {
3761 if ((Member = dyn_cast<FieldDecl>(Result.front())) ||
3762 (Member = dyn_cast<IndirectFieldDecl>(Result.front()))) {
3763 if (EllipsisLoc.isValid())
3764 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
3766 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
3768 return BuildMemberInitializer(Member, Init, IdLoc);
3772 // It didn't name a member, so see if it names a class.
3774 TypeSourceInfo *TInfo = nullptr;
3776 if (TemplateTypeTy) {
3777 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
3778 } else if (DS.getTypeSpecType() == TST_decltype) {
3779 BaseType = BuildDecltypeType(DS.getRepAsExpr(), DS.getTypeSpecTypeLoc());
3780 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
3781 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
3784 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
3785 LookupParsedName(R, S, &SS);
3787 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
3789 if (R.isAmbiguous()) return true;
3791 // We don't want access-control diagnostics here.
3792 R.suppressDiagnostics();
3794 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
3795 bool NotUnknownSpecialization = false;
3796 DeclContext *DC = computeDeclContext(SS, false);
3797 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
3798 NotUnknownSpecialization = !Record->hasAnyDependentBases();
3800 if (!NotUnknownSpecialization) {
3801 // When the scope specifier can refer to a member of an unknown
3802 // specialization, we take it as a type name.
3803 BaseType = CheckTypenameType(ETK_None, SourceLocation(),
3804 SS.getWithLocInContext(Context),
3805 *MemberOrBase, IdLoc);
3806 if (BaseType.isNull())
3809 TInfo = Context.CreateTypeSourceInfo(BaseType);
3810 DependentNameTypeLoc TL =
3811 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
3813 TL.setNameLoc(IdLoc);
3814 TL.setElaboratedKeywordLoc(SourceLocation());
3815 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3819 R.setLookupName(MemberOrBase);
3823 // If no results were found, try to correct typos.
3824 TypoCorrection Corr;
3825 if (R.empty() && BaseType.isNull() &&
3826 (Corr = CorrectTypo(
3827 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
3828 llvm::make_unique<MemInitializerValidatorCCC>(ClassDecl),
3829 CTK_ErrorRecovery, ClassDecl))) {
3830 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
3831 // We have found a non-static data member with a similar
3832 // name to what was typed; complain and initialize that
3835 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3836 << MemberOrBase << true);
3837 return BuildMemberInitializer(Member, Init, IdLoc);
3838 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
3839 const CXXBaseSpecifier *DirectBaseSpec;
3840 const CXXBaseSpecifier *VirtualBaseSpec;
3841 if (FindBaseInitializer(*this, ClassDecl,
3842 Context.getTypeDeclType(Type),
3843 DirectBaseSpec, VirtualBaseSpec)) {
3844 // We have found a direct or virtual base class with a
3845 // similar name to what was typed; complain and initialize
3848 PDiag(diag::err_mem_init_not_member_or_class_suggest)
3849 << MemberOrBase << false,
3850 PDiag() /*Suppress note, we provide our own.*/);
3852 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
3854 Diag(BaseSpec->getLocStart(),
3855 diag::note_base_class_specified_here)
3856 << BaseSpec->getType()
3857 << BaseSpec->getSourceRange();
3864 if (!TyD && BaseType.isNull()) {
3865 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
3866 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
3871 if (BaseType.isNull()) {
3872 BaseType = Context.getTypeDeclType(TyD);
3873 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
3875 BaseType = Context.getElaboratedType(ETK_None, SS.getScopeRep(),
3877 TInfo = Context.CreateTypeSourceInfo(BaseType);
3878 ElaboratedTypeLoc TL = TInfo->getTypeLoc().castAs<ElaboratedTypeLoc>();
3879 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
3880 TL.setElaboratedKeywordLoc(SourceLocation());
3881 TL.setQualifierLoc(SS.getWithLocInContext(Context));
3887 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
3889 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
3892 /// Checks a member initializer expression for cases where reference (or
3893 /// pointer) members are bound to by-value parameters (or their addresses).
3894 static void CheckForDanglingReferenceOrPointer(Sema &S, ValueDecl *Member,
3896 SourceLocation IdLoc) {
3897 QualType MemberTy = Member->getType();
3899 // We only handle pointers and references currently.
3900 // FIXME: Would this be relevant for ObjC object pointers? Or block pointers?
3901 if (!MemberTy->isReferenceType() && !MemberTy->isPointerType())
3904 const bool IsPointer = MemberTy->isPointerType();
3906 if (const UnaryOperator *Op
3907 = dyn_cast<UnaryOperator>(Init->IgnoreParenImpCasts())) {
3908 // The only case we're worried about with pointers requires taking the
3910 if (Op->getOpcode() != UO_AddrOf)
3913 Init = Op->getSubExpr();
3915 // We only handle address-of expression initializers for pointers.
3920 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Init->IgnoreParens())) {
3921 // We only warn when referring to a non-reference parameter declaration.
3922 const ParmVarDecl *Parameter = dyn_cast<ParmVarDecl>(DRE->getDecl());
3923 if (!Parameter || Parameter->getType()->isReferenceType())
3926 S.Diag(Init->getExprLoc(),
3927 IsPointer ? diag::warn_init_ptr_member_to_parameter_addr
3928 : diag::warn_bind_ref_member_to_parameter)
3929 << Member << Parameter << Init->getSourceRange();
3931 // Other initializers are fine.
3935 S.Diag(Member->getLocation(), diag::note_ref_or_ptr_member_declared_here)
3936 << (unsigned)IsPointer;
3940 Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
3941 SourceLocation IdLoc) {
3942 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
3943 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
3944 assert((DirectMember || IndirectMember) &&
3945 "Member must be a FieldDecl or IndirectFieldDecl");
3947 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
3950 if (Member->isInvalidDecl())
3954 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
3955 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
3956 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
3957 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
3959 // Template instantiation doesn't reconstruct ParenListExprs for us.
3963 SourceRange InitRange = Init->getSourceRange();
3965 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
3966 // Can't check initialization for a member of dependent type or when
3967 // any of the arguments are type-dependent expressions.
3968 DiscardCleanupsInEvaluationContext();
3970 bool InitList = false;
3971 if (isa<InitListExpr>(Init)) {
3976 // Initialize the member.
3977 InitializedEntity MemberEntity =
3978 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
3979 : InitializedEntity::InitializeMember(IndirectMember,
3981 InitializationKind Kind =
3982 InitList ? InitializationKind::CreateDirectList(IdLoc)
3983 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
3984 InitRange.getEnd());
3986 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
3987 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
3989 if (MemberInit.isInvalid())
3992 CheckForDanglingReferenceOrPointer(*this, Member, MemberInit.get(), IdLoc);
3994 // C++11 [class.base.init]p7:
3995 // The initialization of each base and member constitutes a
3997 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin());
3998 if (MemberInit.isInvalid())
4001 Init = MemberInit.get();
4005 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4006 InitRange.getBegin(), Init,
4007 InitRange.getEnd());
4009 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4010 InitRange.getBegin(), Init,
4011 InitRange.getEnd());
4016 Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4017 CXXRecordDecl *ClassDecl) {
4018 SourceLocation NameLoc = TInfo->getTypeLoc().getLocalSourceRange().getBegin();
4019 if (!LangOpts.CPlusPlus11)
4020 return Diag(NameLoc, diag::err_delegating_ctor)
4021 << TInfo->getTypeLoc().getLocalSourceRange();
4022 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4024 bool InitList = true;
4025 MultiExprArg Args = Init;
4026 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4028 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4031 SourceRange InitRange = Init->getSourceRange();
4032 // Initialize the object.
4033 InitializedEntity DelegationEntity = InitializedEntity::InitializeDelegation(
4034 QualType(ClassDecl->getTypeForDecl(), 0));
4035 InitializationKind Kind =
4036 InitList ? InitializationKind::CreateDirectList(NameLoc)
4037 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4038 InitRange.getEnd());
4039 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4040 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4042 if (DelegationInit.isInvalid())
4045 assert(cast<CXXConstructExpr>(DelegationInit.get())->getConstructor() &&
4046 "Delegating constructor with no target?");
4048 // C++11 [class.base.init]p7:
4049 // The initialization of each base and member constitutes a
4051 DelegationInit = ActOnFinishFullExpr(DelegationInit.get(),
4052 InitRange.getBegin());
4053 if (DelegationInit.isInvalid())
4056 // If we are in a dependent context, template instantiation will
4057 // perform this type-checking again. Just save the arguments that we
4058 // received in a ParenListExpr.
4059 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4060 // of the information that we have about the base
4061 // initializer. However, deconstructing the ASTs is a dicey process,
4062 // and this approach is far more likely to get the corner cases right.
4063 if (CurContext->isDependentContext())
4064 DelegationInit = Init;
4066 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4067 DelegationInit.getAs<Expr>(),
4068 InitRange.getEnd());
4072 Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4073 Expr *Init, CXXRecordDecl *ClassDecl,
4074 SourceLocation EllipsisLoc) {
4075 SourceLocation BaseLoc
4076 = BaseTInfo->getTypeLoc().getLocalSourceRange().getBegin();
4078 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4079 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4080 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4082 // C++ [class.base.init]p2:
4083 // [...] Unless the mem-initializer-id names a nonstatic data
4084 // member of the constructor's class or a direct or virtual base
4085 // of that class, the mem-initializer is ill-formed. A
4086 // mem-initializer-list can initialize a base class using any
4087 // name that denotes that base class type.
4088 bool Dependent = BaseType->isDependentType() || Init->isTypeDependent();
4090 SourceRange InitRange = Init->getSourceRange();
4091 if (EllipsisLoc.isValid()) {
4092 // This is a pack expansion.
4093 if (!BaseType->containsUnexpandedParameterPack()) {
4094 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4095 << SourceRange(BaseLoc, InitRange.getEnd());
4097 EllipsisLoc = SourceLocation();
4100 // Check for any unexpanded parameter packs.
4101 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4104 if (DiagnoseUnexpandedParameterPack(Init, UPPC_Initializer))
4108 // Check for direct and virtual base classes.
4109 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4110 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4112 if (Context.hasSameUnqualifiedType(QualType(ClassDecl->getTypeForDecl(),0),
4114 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4116 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4119 // C++ [base.class.init]p2:
4120 // Unless the mem-initializer-id names a nonstatic data member of the
4121 // constructor's class or a direct or virtual base of that class, the
4122 // mem-initializer is ill-formed.
4123 if (!DirectBaseSpec && !VirtualBaseSpec) {
4124 // If the class has any dependent bases, then it's possible that
4125 // one of those types will resolve to the same type as
4126 // BaseType. Therefore, just treat this as a dependent base
4127 // class initialization. FIXME: Should we try to check the
4128 // initialization anyway? It seems odd.
4129 if (ClassDecl->hasAnyDependentBases())
4132 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4133 << BaseType << Context.getTypeDeclType(ClassDecl)
4134 << BaseTInfo->getTypeLoc().getLocalSourceRange();
4139 DiscardCleanupsInEvaluationContext();
4141 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4142 /*IsVirtual=*/false,
4143 InitRange.getBegin(), Init,
4144 InitRange.getEnd(), EllipsisLoc);
4147 // C++ [base.class.init]p2:
4148 // If a mem-initializer-id is ambiguous because it designates both
4149 // a direct non-virtual base class and an inherited virtual base
4150 // class, the mem-initializer is ill-formed.
4151 if (DirectBaseSpec && VirtualBaseSpec)
4152 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4153 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4155 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4157 BaseSpec = VirtualBaseSpec;
4159 // Initialize the base.
4160 bool InitList = true;
4161 MultiExprArg Args = Init;
4162 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4164 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4167 InitializedEntity BaseEntity =
4168 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4169 InitializationKind Kind =
4170 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4171 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4172 InitRange.getEnd());
4173 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4174 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4175 if (BaseInit.isInvalid())
4178 // C++11 [class.base.init]p7:
4179 // The initialization of each base and member constitutes a
4181 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin());
4182 if (BaseInit.isInvalid())
4185 // If we are in a dependent context, template instantiation will
4186 // perform this type-checking again. Just save the arguments that we
4187 // received in a ParenListExpr.
4188 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4189 // of the information that we have about the base
4190 // initializer. However, deconstructing the ASTs is a dicey process,
4191 // and this approach is far more likely to get the corner cases right.
4192 if (CurContext->isDependentContext())
4195 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4196 BaseSpec->isVirtual(),
4197 InitRange.getBegin(),
4198 BaseInit.getAs<Expr>(),
4199 InitRange.getEnd(), EllipsisLoc);
4202 // Create a static_cast\<T&&>(expr).
4203 static Expr *CastForMoving(Sema &SemaRef, Expr *E, QualType T = QualType()) {
4204 if (T.isNull()) T = E->getType();
4205 QualType TargetType = SemaRef.BuildReferenceType(
4206 T, /*SpelledAsLValue*/false, SourceLocation(), DeclarationName());
4207 SourceLocation ExprLoc = E->getLocStart();
4208 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4209 TargetType, ExprLoc);
4211 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4212 SourceRange(ExprLoc, ExprLoc),
4213 E->getSourceRange()).get();
4216 /// ImplicitInitializerKind - How an implicit base or member initializer should
4217 /// initialize its base or member.
4218 enum ImplicitInitializerKind {
4226 BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4227 ImplicitInitializerKind ImplicitInitKind,
4228 CXXBaseSpecifier *BaseSpec,
4229 bool IsInheritedVirtualBase,
4230 CXXCtorInitializer *&CXXBaseInit) {
4231 InitializedEntity InitEntity
4232 = InitializedEntity::InitializeBase(SemaRef.Context, BaseSpec,
4233 IsInheritedVirtualBase);
4235 ExprResult BaseInit;
4237 switch (ImplicitInitKind) {
4240 InitializationKind InitKind
4241 = InitializationKind::CreateDefault(Constructor->getLocation());
4242 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4243 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4249 bool Moving = ImplicitInitKind == IIK_Move;
4250 ParmVarDecl *Param = Constructor->getParamDecl(0);
4251 QualType ParamType = Param->getType().getNonReferenceType();
4254 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4255 SourceLocation(), Param, false,
4256 Constructor->getLocation(), ParamType,
4257 VK_LValue, nullptr);
4259 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4261 // Cast to the base class to avoid ambiguities.
4263 SemaRef.Context.getQualifiedType(BaseSpec->getType().getUnqualifiedType(),
4264 ParamType.getQualifiers());
4267 CopyCtorArg = CastForMoving(SemaRef, CopyCtorArg);
4270 CXXCastPath BasePath;
4271 BasePath.push_back(BaseSpec);
4272 CopyCtorArg = SemaRef.ImpCastExprToType(CopyCtorArg, ArgTy,
4273 CK_UncheckedDerivedToBase,
4274 Moving ? VK_XValue : VK_LValue,
4277 InitializationKind InitKind
4278 = InitializationKind::CreateDirect(Constructor->getLocation(),
4279 SourceLocation(), SourceLocation());
4280 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4281 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, CopyCtorArg);
4286 BaseInit = SemaRef.MaybeCreateExprWithCleanups(BaseInit);
4287 if (BaseInit.isInvalid())
4291 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4292 SemaRef.Context.getTrivialTypeSourceInfo(BaseSpec->getType(),
4294 BaseSpec->isVirtual(),
4296 BaseInit.getAs<Expr>(),
4303 static bool RefersToRValueRef(Expr *MemRef) {
4304 ValueDecl *Referenced = cast<MemberExpr>(MemRef)->getMemberDecl();
4305 return Referenced->getType()->isRValueReferenceType();
4309 BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4310 ImplicitInitializerKind ImplicitInitKind,
4311 FieldDecl *Field, IndirectFieldDecl *Indirect,
4312 CXXCtorInitializer *&CXXMemberInit) {
4313 if (Field->isInvalidDecl())
4316 SourceLocation Loc = Constructor->getLocation();
4318 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
4319 bool Moving = ImplicitInitKind == IIK_Move;
4320 ParmVarDecl *Param = Constructor->getParamDecl(0);
4321 QualType ParamType = Param->getType().getNonReferenceType();
4323 // Suppress copying zero-width bitfields.
4324 if (Field->isBitField() && Field->getBitWidthValue(SemaRef.Context) == 0)
4327 Expr *MemberExprBase =
4328 DeclRefExpr::Create(SemaRef.Context, NestedNameSpecifierLoc(),
4329 SourceLocation(), Param, false,
4330 Loc, ParamType, VK_LValue, nullptr);
4332 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(MemberExprBase));
4335 MemberExprBase = CastForMoving(SemaRef, MemberExprBase);
4338 // Build a reference to this field within the parameter.
4340 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
4341 Sema::LookupMemberName);
4342 MemberLookup.addDecl(Indirect ? cast<ValueDecl>(Indirect)
4343 : cast<ValueDecl>(Field), AS_public);
4344 MemberLookup.resolveKind();
4346 = SemaRef.BuildMemberReferenceExpr(MemberExprBase,
4350 /*TemplateKWLoc=*/SourceLocation(),
4351 /*FirstQualifierInScope=*/nullptr,
4353 /*TemplateArgs=*/nullptr,
4355 if (CtorArg.isInvalid())
4358 // C++11 [class.copy]p15:
4359 // - if a member m has rvalue reference type T&&, it is direct-initialized
4360 // with static_cast<T&&>(x.m);
4361 if (RefersToRValueRef(CtorArg.get())) {
4362 CtorArg = CastForMoving(SemaRef, CtorArg.get());
4365 InitializedEntity Entity =
4366 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4368 : InitializedEntity::InitializeMember(Field, nullptr,
4371 // Direct-initialize to use the copy constructor.
4372 InitializationKind InitKind =
4373 InitializationKind::CreateDirect(Loc, SourceLocation(), SourceLocation());
4375 Expr *CtorArgE = CtorArg.getAs<Expr>();
4376 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
4377 ExprResult MemberInit =
4378 InitSeq.Perform(SemaRef, Entity, InitKind, MultiExprArg(&CtorArgE, 1));
4379 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4380 if (MemberInit.isInvalid())
4384 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4385 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4387 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
4388 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
4392 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
4393 "Unhandled implicit init kind!");
4395 QualType FieldBaseElementType =
4396 SemaRef.Context.getBaseElementType(Field->getType());
4398 if (FieldBaseElementType->isRecordType()) {
4399 InitializedEntity InitEntity =
4400 Indirect ? InitializedEntity::InitializeMember(Indirect, nullptr,
4402 : InitializedEntity::InitializeMember(Field, nullptr,
4404 InitializationKind InitKind =
4405 InitializationKind::CreateDefault(Loc);
4407 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, None);
4408 ExprResult MemberInit =
4409 InitSeq.Perform(SemaRef, InitEntity, InitKind, None);
4411 MemberInit = SemaRef.MaybeCreateExprWithCleanups(MemberInit);
4412 if (MemberInit.isInvalid())
4416 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4422 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4429 if (!Field->getParent()->isUnion()) {
4430 if (FieldBaseElementType->isReferenceType()) {
4431 SemaRef.Diag(Constructor->getLocation(),
4432 diag::err_uninitialized_member_in_ctor)
4433 << (int)Constructor->isImplicit()
4434 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4435 << 0 << Field->getDeclName();
4436 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4440 if (FieldBaseElementType.isConstQualified()) {
4441 SemaRef.Diag(Constructor->getLocation(),
4442 diag::err_uninitialized_member_in_ctor)
4443 << (int)Constructor->isImplicit()
4444 << SemaRef.Context.getTagDeclType(Constructor->getParent())
4445 << 1 << Field->getDeclName();
4446 SemaRef.Diag(Field->getLocation(), diag::note_declared_at);
4451 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
4453 // Default-initialize Objective-C pointers to NULL.
4455 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
4457 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
4462 // Nothing to initialize.
4463 CXXMemberInit = nullptr;
4468 struct BaseAndFieldInfo {
4470 CXXConstructorDecl *Ctor;
4471 bool AnyErrorsInInits;
4472 ImplicitInitializerKind IIK;
4473 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
4474 SmallVector<CXXCtorInitializer*, 8> AllToInit;
4475 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
4477 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
4478 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
4479 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
4480 if (Ctor->getInheritedConstructor())
4482 else if (Generated && Ctor->isCopyConstructor())
4484 else if (Generated && Ctor->isMoveConstructor())
4490 bool isImplicitCopyOrMove() const {
4501 llvm_unreachable("Invalid ImplicitInitializerKind!");
4504 bool addFieldInitializer(CXXCtorInitializer *Init) {
4505 AllToInit.push_back(Init);
4507 // Check whether this initializer makes the field "used".
4508 if (Init->getInit()->HasSideEffects(S.Context))
4509 S.UnusedPrivateFields.remove(Init->getAnyMember());
4514 bool isInactiveUnionMember(FieldDecl *Field) {
4515 RecordDecl *Record = Field->getParent();
4516 if (!Record->isUnion())
4519 if (FieldDecl *Active =
4520 ActiveUnionMember.lookup(Record->getCanonicalDecl()))
4521 return Active != Field->getCanonicalDecl();
4523 // In an implicit copy or move constructor, ignore any in-class initializer.
4524 if (isImplicitCopyOrMove())
4527 // If there's no explicit initialization, the field is active only if it
4528 // has an in-class initializer...
4529 if (Field->hasInClassInitializer())
4531 // ... or it's an anonymous struct or union whose class has an in-class
4533 if (!Field->isAnonymousStructOrUnion())
4535 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
4536 return !FieldRD->hasInClassInitializer();
4539 /// \brief Determine whether the given field is, or is within, a union member
4540 /// that is inactive (because there was an initializer given for a different
4541 /// member of the union, or because the union was not initialized at all).
4542 bool isWithinInactiveUnionMember(FieldDecl *Field,
4543 IndirectFieldDecl *Indirect) {
4545 return isInactiveUnionMember(Field);
4547 for (auto *C : Indirect->chain()) {
4548 FieldDecl *Field = dyn_cast<FieldDecl>(C);
4549 if (Field && isInactiveUnionMember(Field))
4557 /// \brief Determine whether the given type is an incomplete or zero-lenfgth
4559 static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
4560 if (T->isIncompleteArrayType())
4563 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
4564 if (!ArrayT->getSize())
4567 T = ArrayT->getElementType();
4573 static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
4575 IndirectFieldDecl *Indirect = nullptr) {
4576 if (Field->isInvalidDecl())
4579 // Overwhelmingly common case: we have a direct initializer for this field.
4580 if (CXXCtorInitializer *Init =
4581 Info.AllBaseFields.lookup(Field->getCanonicalDecl()))
4582 return Info.addFieldInitializer(Init);
4584 // C++11 [class.base.init]p8:
4585 // if the entity is a non-static data member that has a
4586 // brace-or-equal-initializer and either
4587 // -- the constructor's class is a union and no other variant member of that
4588 // union is designated by a mem-initializer-id or
4589 // -- the constructor's class is not a union, and, if the entity is a member
4590 // of an anonymous union, no other member of that union is designated by
4591 // a mem-initializer-id,
4592 // the entity is initialized as specified in [dcl.init].
4594 // We also apply the same rules to handle anonymous structs within anonymous
4596 if (Info.isWithinInactiveUnionMember(Field, Indirect))
4599 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
4601 SemaRef.BuildCXXDefaultInitExpr(Info.Ctor->getLocation(), Field);
4602 if (DIE.isInvalid())
4604 CXXCtorInitializer *Init;
4606 Init = new (SemaRef.Context)
4607 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
4608 SourceLocation(), DIE.get(), SourceLocation());
4610 Init = new (SemaRef.Context)
4611 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
4612 SourceLocation(), DIE.get(), SourceLocation());
4613 return Info.addFieldInitializer(Init);
4616 // Don't initialize incomplete or zero-length arrays.
4617 if (isIncompleteOrZeroLengthArrayType(SemaRef.Context, Field->getType()))
4620 // Don't try to build an implicit initializer if there were semantic
4621 // errors in any of the initializers (and therefore we might be
4622 // missing some that the user actually wrote).
4623 if (Info.AnyErrorsInInits)
4626 CXXCtorInitializer *Init = nullptr;
4627 if (BuildImplicitMemberInitializer(Info.S, Info.Ctor, Info.IIK, Field,
4634 return Info.addFieldInitializer(Init);
4638 Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
4639 CXXCtorInitializer *Initializer) {
4640 assert(Initializer->isDelegatingInitializer());
4641 Constructor->setNumCtorInitializers(1);
4642 CXXCtorInitializer **initializer =
4643 new (Context) CXXCtorInitializer*[1];
4644 memcpy(initializer, &Initializer, sizeof (CXXCtorInitializer*));
4645 Constructor->setCtorInitializers(initializer);
4647 if (CXXDestructorDecl *Dtor = LookupDestructor(Constructor->getParent())) {
4648 MarkFunctionReferenced(Initializer->getSourceLocation(), Dtor);
4649 DiagnoseUseOfDecl(Dtor, Initializer->getSourceLocation());
4652 DelegatingCtorDecls.push_back(Constructor);
4654 DiagnoseUninitializedFields(*this, Constructor);
4659 bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
4660 ArrayRef<CXXCtorInitializer *> Initializers) {
4661 if (Constructor->isDependentContext()) {
4662 // Just store the initializers as written, they will be checked during
4664 if (!Initializers.empty()) {
4665 Constructor->setNumCtorInitializers(Initializers.size());
4666 CXXCtorInitializer **baseOrMemberInitializers =
4667 new (Context) CXXCtorInitializer*[Initializers.size()];
4668 memcpy(baseOrMemberInitializers, Initializers.data(),
4669 Initializers.size() * sizeof(CXXCtorInitializer*));
4670 Constructor->setCtorInitializers(baseOrMemberInitializers);
4673 // Let template instantiation know whether we had errors.
4675 Constructor->setInvalidDecl();
4680 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
4682 // We need to build the initializer AST according to order of construction
4683 // and not what user specified in the Initializers list.
4684 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
4688 bool HadError = false;
4690 for (unsigned i = 0; i < Initializers.size(); i++) {
4691 CXXCtorInitializer *Member = Initializers[i];
4693 if (Member->isBaseInitializer())
4694 Info.AllBaseFields[Member->getBaseClass()->getAs<RecordType>()] = Member;
4696 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
4698 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
4699 for (auto *C : F->chain()) {
4700 FieldDecl *FD = dyn_cast<FieldDecl>(C);
4701 if (FD && FD->getParent()->isUnion())
4702 Info.ActiveUnionMember.insert(std::make_pair(
4703 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4705 } else if (FieldDecl *FD = Member->getMember()) {
4706 if (FD->getParent()->isUnion())
4707 Info.ActiveUnionMember.insert(std::make_pair(
4708 FD->getParent()->getCanonicalDecl(), FD->getCanonicalDecl()));
4713 // Keep track of the direct virtual bases.
4714 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
4715 for (auto &I : ClassDecl->bases()) {
4717 DirectVBases.insert(&I);
4720 // Push virtual bases before others.
4721 for (auto &VBase : ClassDecl->vbases()) {
4722 if (CXXCtorInitializer *Value
4723 = Info.AllBaseFields.lookup(VBase.getType()->getAs<RecordType>())) {
4724 // [class.base.init]p7, per DR257:
4725 // A mem-initializer where the mem-initializer-id names a virtual base
4726 // class is ignored during execution of a constructor of any class that
4727 // is not the most derived class.
4728 if (ClassDecl->isAbstract()) {
4729 // FIXME: Provide a fixit to remove the base specifier. This requires
4730 // tracking the location of the associated comma for a base specifier.
4731 Diag(Value->getSourceLocation(), diag::warn_abstract_vbase_init_ignored)
4732 << VBase.getType() << ClassDecl;
4733 DiagnoseAbstractType(ClassDecl);
4736 Info.AllToInit.push_back(Value);
4737 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
4738 // [class.base.init]p8, per DR257:
4739 // If a given [...] base class is not named by a mem-initializer-id
4740 // [...] and the entity is not a virtual base class of an abstract
4741 // class, then [...] the entity is default-initialized.
4742 bool IsInheritedVirtualBase = !DirectVBases.count(&VBase);
4743 CXXCtorInitializer *CXXBaseInit;
4744 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4745 &VBase, IsInheritedVirtualBase,
4751 Info.AllToInit.push_back(CXXBaseInit);
4755 // Non-virtual bases.
4756 for (auto &Base : ClassDecl->bases()) {
4757 // Virtuals are in the virtual base list and already constructed.
4758 if (Base.isVirtual())
4761 if (CXXCtorInitializer *Value
4762 = Info.AllBaseFields.lookup(Base.getType()->getAs<RecordType>())) {
4763 Info.AllToInit.push_back(Value);
4764 } else if (!AnyErrors) {
4765 CXXCtorInitializer *CXXBaseInit;
4766 if (BuildImplicitBaseInitializer(*this, Constructor, Info.IIK,
4767 &Base, /*IsInheritedVirtualBase=*/false,
4773 Info.AllToInit.push_back(CXXBaseInit);
4778 for (auto *Mem : ClassDecl->decls()) {
4779 if (auto *F = dyn_cast<FieldDecl>(Mem)) {
4780 // C++ [class.bit]p2:
4781 // A declaration for a bit-field that omits the identifier declares an
4782 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
4784 if (F->isUnnamedBitfield())
4787 // If we're not generating the implicit copy/move constructor, then we'll
4788 // handle anonymous struct/union fields based on their individual
4790 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
4793 if (CollectFieldInitializer(*this, Info, F))
4798 // Beyond this point, we only consider default initialization.
4799 if (Info.isImplicitCopyOrMove())
4802 if (auto *F = dyn_cast<IndirectFieldDecl>(Mem)) {
4803 if (F->getType()->isIncompleteArrayType()) {
4804 assert(ClassDecl->hasFlexibleArrayMember() &&
4805 "Incomplete array type is not valid");
4809 // Initialize each field of an anonymous struct individually.
4810 if (CollectFieldInitializer(*this, Info, F->getAnonField(), F))
4817 unsigned NumInitializers = Info.AllToInit.size();
4818 if (NumInitializers > 0) {
4819 Constructor->setNumCtorInitializers(NumInitializers);
4820 CXXCtorInitializer **baseOrMemberInitializers =
4821 new (Context) CXXCtorInitializer*[NumInitializers];
4822 memcpy(baseOrMemberInitializers, Info.AllToInit.data(),
4823 NumInitializers * sizeof(CXXCtorInitializer*));
4824 Constructor->setCtorInitializers(baseOrMemberInitializers);
4826 // Constructors implicitly reference the base and member
4828 MarkBaseAndMemberDestructorsReferenced(Constructor->getLocation(),
4829 Constructor->getParent());
4835 static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
4836 if (const RecordType *RT = Field->getType()->getAs<RecordType>()) {
4837 const RecordDecl *RD = RT->getDecl();
4838 if (RD->isAnonymousStructOrUnion()) {
4839 for (auto *Field : RD->fields())
4840 PopulateKeysForFields(Field, IdealInits);
4844 IdealInits.push_back(Field->getCanonicalDecl());
4847 static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
4848 return Context.getCanonicalType(BaseType).getTypePtr();
4851 static const void *GetKeyForMember(ASTContext &Context,
4852 CXXCtorInitializer *Member) {
4853 if (!Member->isAnyMemberInitializer())
4854 return GetKeyForBase(Context, QualType(Member->getBaseClass(), 0));
4856 return Member->getAnyMember()->getCanonicalDecl();
4859 static void DiagnoseBaseOrMemInitializerOrder(
4860 Sema &SemaRef, const CXXConstructorDecl *Constructor,
4861 ArrayRef<CXXCtorInitializer *> Inits) {
4862 if (Constructor->getDeclContext()->isDependentContext())
4865 // Don't check initializers order unless the warning is enabled at the
4866 // location of at least one initializer.
4867 bool ShouldCheckOrder = false;
4868 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4869 CXXCtorInitializer *Init = Inits[InitIndex];
4870 if (!SemaRef.Diags.isIgnored(diag::warn_initializer_out_of_order,
4871 Init->getSourceLocation())) {
4872 ShouldCheckOrder = true;
4876 if (!ShouldCheckOrder)
4879 // Build the list of bases and members in the order that they'll
4880 // actually be initialized. The explicit initializers should be in
4881 // this same order but may be missing things.
4882 SmallVector<const void*, 32> IdealInitKeys;
4884 const CXXRecordDecl *ClassDecl = Constructor->getParent();
4886 // 1. Virtual bases.
4887 for (const auto &VBase : ClassDecl->vbases())
4888 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, VBase.getType()));
4890 // 2. Non-virtual bases.
4891 for (const auto &Base : ClassDecl->bases()) {
4892 if (Base.isVirtual())
4894 IdealInitKeys.push_back(GetKeyForBase(SemaRef.Context, Base.getType()));
4897 // 3. Direct fields.
4898 for (auto *Field : ClassDecl->fields()) {
4899 if (Field->isUnnamedBitfield())
4902 PopulateKeysForFields(Field, IdealInitKeys);
4905 unsigned NumIdealInits = IdealInitKeys.size();
4906 unsigned IdealIndex = 0;
4908 CXXCtorInitializer *PrevInit = nullptr;
4909 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
4910 CXXCtorInitializer *Init = Inits[InitIndex];
4911 const void *InitKey = GetKeyForMember(SemaRef.Context, Init);
4913 // Scan forward to try to find this initializer in the idealized
4914 // initializers list.
4915 for (; IdealIndex != NumIdealInits; ++IdealIndex)
4916 if (InitKey == IdealInitKeys[IdealIndex])
4919 // If we didn't find this initializer, it must be because we
4920 // scanned past it on a previous iteration. That can only
4921 // happen if we're out of order; emit a warning.
4922 if (IdealIndex == NumIdealInits && PrevInit) {
4923 Sema::SemaDiagnosticBuilder D =
4924 SemaRef.Diag(PrevInit->getSourceLocation(),
4925 diag::warn_initializer_out_of_order);
4927 if (PrevInit->isAnyMemberInitializer())
4928 D << 0 << PrevInit->getAnyMember()->getDeclName();
4930 D << 1 << PrevInit->getTypeSourceInfo()->getType();
4932 if (Init->isAnyMemberInitializer())
4933 D << 0 << Init->getAnyMember()->getDeclName();
4935 D << 1 << Init->getTypeSourceInfo()->getType();
4937 // Move back to the initializer's location in the ideal list.
4938 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
4939 if (InitKey == IdealInitKeys[IdealIndex])
4942 assert(IdealIndex < NumIdealInits &&
4943 "initializer not found in initializer list");
4951 bool CheckRedundantInit(Sema &S,
4952 CXXCtorInitializer *Init,
4953 CXXCtorInitializer *&PrevInit) {
4959 if (FieldDecl *Field = Init->getAnyMember())
4960 S.Diag(Init->getSourceLocation(),
4961 diag::err_multiple_mem_initialization)
4962 << Field->getDeclName()
4963 << Init->getSourceRange();
4965 const Type *BaseClass = Init->getBaseClass();
4966 assert(BaseClass && "neither field nor base");
4967 S.Diag(Init->getSourceLocation(),
4968 diag::err_multiple_base_initialization)
4969 << QualType(BaseClass, 0)
4970 << Init->getSourceRange();
4972 S.Diag(PrevInit->getSourceLocation(), diag::note_previous_initializer)
4973 << 0 << PrevInit->getSourceRange();
4978 typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
4979 typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
4981 bool CheckRedundantUnionInit(Sema &S,
4982 CXXCtorInitializer *Init,
4983 RedundantUnionMap &Unions) {
4984 FieldDecl *Field = Init->getAnyMember();
4985 RecordDecl *Parent = Field->getParent();
4986 NamedDecl *Child = Field;
4988 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
4989 if (Parent->isUnion()) {
4990 UnionEntry &En = Unions[Parent];
4991 if (En.first && En.first != Child) {
4992 S.Diag(Init->getSourceLocation(),
4993 diag::err_multiple_mem_union_initialization)
4994 << Field->getDeclName()
4995 << Init->getSourceRange();
4996 S.Diag(En.second->getSourceLocation(), diag::note_previous_initializer)
4997 << 0 << En.second->getSourceRange();
5004 if (!Parent->isAnonymousStructOrUnion())
5009 Parent = cast<RecordDecl>(Parent->getDeclContext());
5016 /// ActOnMemInitializers - Handle the member initializers for a constructor.
5017 void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5018 SourceLocation ColonLoc,
5019 ArrayRef<CXXCtorInitializer*> MemInits,
5021 if (!ConstructorDecl)
5024 AdjustDeclIfTemplate(ConstructorDecl);
5026 CXXConstructorDecl *Constructor
5027 = dyn_cast<CXXConstructorDecl>(ConstructorDecl);
5030 Diag(ColonLoc, diag::err_only_constructors_take_base_inits);
5034 // Mapping for the duplicate initializers check.
5035 // For member initializers, this is keyed with a FieldDecl*.
5036 // For base initializers, this is keyed with a Type*.
5037 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5039 // Mapping for the inconsistent anonymous-union initializers check.
5040 RedundantUnionMap MemberUnions;
5042 bool HadError = false;
5043 for (unsigned i = 0; i < MemInits.size(); i++) {
5044 CXXCtorInitializer *Init = MemInits[i];
5046 // Set the source order index.
5047 Init->setSourceOrder(i);
5049 if (Init->isAnyMemberInitializer()) {
5050 const void *Key = GetKeyForMember(Context, Init);
5051 if (CheckRedundantInit(*this, Init, Members[Key]) ||
5052 CheckRedundantUnionInit(*this, Init, MemberUnions))
5054 } else if (Init->isBaseInitializer()) {
5055 const void *Key = GetKeyForMember(Context, Init);
5056 if (CheckRedundantInit(*this, Init, Members[Key]))
5059 assert(Init->isDelegatingInitializer());
5060 // This must be the only initializer
5061 if (MemInits.size() != 1) {
5062 Diag(Init->getSourceLocation(),
5063 diag::err_delegating_initializer_alone)
5064 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5065 // We will treat this as being the only initializer.
5067 SetDelegatingInitializer(Constructor, MemInits[i]);
5068 // Return immediately as the initializer is set.
5076 DiagnoseBaseOrMemInitializerOrder(*this, Constructor, MemInits);
5078 SetCtorInitializers(Constructor, AnyErrors, MemInits);
5080 DiagnoseUninitializedFields(*this, Constructor);
5084 Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5085 CXXRecordDecl *ClassDecl) {
5086 // Ignore dependent contexts. Also ignore unions, since their members never
5087 // have destructors implicitly called.
5088 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5091 // FIXME: all the access-control diagnostics are positioned on the
5092 // field/base declaration. That's probably good; that said, the
5093 // user might reasonably want to know why the destructor is being
5094 // emitted, and we currently don't say.
5096 // Non-static data members.
5097 for (auto *Field : ClassDecl->fields()) {
5098 if (Field->isInvalidDecl())
5101 // Don't destroy incomplete or zero-length arrays.
5102 if (isIncompleteOrZeroLengthArrayType(Context, Field->getType()))
5105 QualType FieldType = Context.getBaseElementType(Field->getType());
5107 const RecordType* RT = FieldType->getAs<RecordType>();
5111 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5112 if (FieldClassDecl->isInvalidDecl())
5114 if (FieldClassDecl->hasIrrelevantDestructor())
5116 // The destructor for an implicit anonymous union member is never invoked.
5117 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5120 CXXDestructorDecl *Dtor = LookupDestructor(FieldClassDecl);
5121 assert(Dtor && "No dtor found for FieldClassDecl!");
5122 CheckDestructorAccess(Field->getLocation(), Dtor,
5123 PDiag(diag::err_access_dtor_field)
5124 << Field->getDeclName()
5127 MarkFunctionReferenced(Location, Dtor);
5128 DiagnoseUseOfDecl(Dtor, Location);
5131 // We only potentially invoke the destructors of potentially constructed
5133 bool VisitVirtualBases = !ClassDecl->isAbstract();
5135 llvm::SmallPtrSet<const RecordType *, 8> DirectVirtualBases;
5138 for (const auto &Base : ClassDecl->bases()) {
5139 // Bases are always records in a well-formed non-dependent class.
5140 const RecordType *RT = Base.getType()->getAs<RecordType>();
5142 // Remember direct virtual bases.
5143 if (Base.isVirtual()) {
5144 if (!VisitVirtualBases)
5146 DirectVirtualBases.insert(RT);
5149 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5150 // If our base class is invalid, we probably can't get its dtor anyway.
5151 if (BaseClassDecl->isInvalidDecl())
5153 if (BaseClassDecl->hasIrrelevantDestructor())
5156 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5157 assert(Dtor && "No dtor found for BaseClassDecl!");
5159 // FIXME: caret should be on the start of the class name
5160 CheckDestructorAccess(Base.getLocStart(), Dtor,
5161 PDiag(diag::err_access_dtor_base)
5163 << Base.getSourceRange(),
5164 Context.getTypeDeclType(ClassDecl));
5166 MarkFunctionReferenced(Location, Dtor);
5167 DiagnoseUseOfDecl(Dtor, Location);
5170 if (!VisitVirtualBases)
5174 for (const auto &VBase : ClassDecl->vbases()) {
5175 // Bases are always records in a well-formed non-dependent class.
5176 const RecordType *RT = VBase.getType()->castAs<RecordType>();
5178 // Ignore direct virtual bases.
5179 if (DirectVirtualBases.count(RT))
5182 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(RT->getDecl());
5183 // If our base class is invalid, we probably can't get its dtor anyway.
5184 if (BaseClassDecl->isInvalidDecl())
5186 if (BaseClassDecl->hasIrrelevantDestructor())
5189 CXXDestructorDecl *Dtor = LookupDestructor(BaseClassDecl);
5190 assert(Dtor && "No dtor found for BaseClassDecl!");
5191 if (CheckDestructorAccess(
5192 ClassDecl->getLocation(), Dtor,
5193 PDiag(diag::err_access_dtor_vbase)
5194 << Context.getTypeDeclType(ClassDecl) << VBase.getType(),
5195 Context.getTypeDeclType(ClassDecl)) ==
5197 CheckDerivedToBaseConversion(
5198 Context.getTypeDeclType(ClassDecl), VBase.getType(),
5199 diag::err_access_dtor_vbase, 0, ClassDecl->getLocation(),
5200 SourceRange(), DeclarationName(), nullptr);
5203 MarkFunctionReferenced(Location, Dtor);
5204 DiagnoseUseOfDecl(Dtor, Location);
5208 void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5212 if (CXXConstructorDecl *Constructor
5213 = dyn_cast<CXXConstructorDecl>(CDtorDecl)) {
5214 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5215 DiagnoseUninitializedFields(*this, Constructor);
5219 bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5220 if (!getLangOpts().CPlusPlus)
5223 const auto *RD = Context.getBaseElementType(T)->getAsCXXRecordDecl();
5227 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
5228 // class template specialization here, but doing so breaks a lot of code.
5230 // We can't answer whether something is abstract until it has a
5231 // definition. If it's currently being defined, we'll walk back
5232 // over all the declarations when we have a full definition.
5233 const CXXRecordDecl *Def = RD->getDefinition();
5234 if (!Def || Def->isBeingDefined())
5237 return RD->isAbstract();
5240 bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
5241 TypeDiagnoser &Diagnoser) {
5242 if (!isAbstractType(Loc, T))
5245 T = Context.getBaseElementType(T);
5246 Diagnoser.diagnose(*this, Loc, T);
5247 DiagnoseAbstractType(T->getAsCXXRecordDecl());
5251 void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
5252 // Check if we've already emitted the list of pure virtual functions
5254 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(RD))
5257 // If the diagnostic is suppressed, don't emit the notes. We're only
5258 // going to emit them once, so try to attach them to a diagnostic we're
5259 // actually going to show.
5260 if (Diags.isLastDiagnosticIgnored())
5263 CXXFinalOverriderMap FinalOverriders;
5264 RD->getFinalOverriders(FinalOverriders);
5266 // Keep a set of seen pure methods so we won't diagnose the same method
5268 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
5270 for (CXXFinalOverriderMap::iterator M = FinalOverriders.begin(),
5271 MEnd = FinalOverriders.end();
5274 for (OverridingMethods::iterator SO = M->second.begin(),
5275 SOEnd = M->second.end();
5276 SO != SOEnd; ++SO) {
5277 // C++ [class.abstract]p4:
5278 // A class is abstract if it contains or inherits at least one
5279 // pure virtual function for which the final overrider is pure
5283 if (SO->second.size() != 1)
5286 if (!SO->second.front().Method->isPure())
5289 if (!SeenPureMethods.insert(SO->second.front().Method).second)
5292 Diag(SO->second.front().Method->getLocation(),
5293 diag::note_pure_virtual_function)
5294 << SO->second.front().Method->getDeclName() << RD->getDeclName();
5298 if (!PureVirtualClassDiagSet)
5299 PureVirtualClassDiagSet.reset(new RecordDeclSetTy);
5300 PureVirtualClassDiagSet->insert(RD);
5304 struct AbstractUsageInfo {
5306 CXXRecordDecl *Record;
5307 CanQualType AbstractType;
5310 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
5311 : S(S), Record(Record),
5312 AbstractType(S.Context.getCanonicalType(
5313 S.Context.getTypeDeclType(Record))),
5316 void DiagnoseAbstractType() {
5317 if (Invalid) return;
5318 S.DiagnoseAbstractType(Record);
5322 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
5325 struct CheckAbstractUsage {
5326 AbstractUsageInfo &Info;
5327 const NamedDecl *Ctx;
5329 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
5330 : Info(Info), Ctx(Ctx) {}
5332 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5333 switch (TL.getTypeLocClass()) {
5334 #define ABSTRACT_TYPELOC(CLASS, PARENT)
5335 #define TYPELOC(CLASS, PARENT) \
5336 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
5337 #include "clang/AST/TypeLocNodes.def"
5341 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5342 Visit(TL.getReturnLoc(), Sema::AbstractReturnType);
5343 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
5344 if (!TL.getParam(I))
5347 TypeSourceInfo *TSI = TL.getParam(I)->getTypeSourceInfo();
5348 if (TSI) Visit(TSI->getTypeLoc(), Sema::AbstractParamType);
5352 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5353 Visit(TL.getElementLoc(), Sema::AbstractArrayType);
5356 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
5357 // Visit the type parameters from a permissive context.
5358 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
5359 TemplateArgumentLoc TAL = TL.getArgLoc(I);
5360 if (TAL.getArgument().getKind() == TemplateArgument::Type)
5361 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
5362 Visit(TSI->getTypeLoc(), Sema::AbstractNone);
5363 // TODO: other template argument types?
5367 // Visit pointee types from a permissive context.
5368 #define CheckPolymorphic(Type) \
5369 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
5370 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
5372 CheckPolymorphic(PointerTypeLoc)
5373 CheckPolymorphic(ReferenceTypeLoc)
5374 CheckPolymorphic(MemberPointerTypeLoc)
5375 CheckPolymorphic(BlockPointerTypeLoc)
5376 CheckPolymorphic(AtomicTypeLoc)
5378 /// Handle all the types we haven't given a more specific
5379 /// implementation for above.
5380 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
5381 // Every other kind of type that we haven't called out already
5382 // that has an inner type is either (1) sugar or (2) contains that
5383 // inner type in some way as a subobject.
5384 if (TypeLoc Next = TL.getNextTypeLoc())
5385 return Visit(Next, Sel);
5387 // If there's no inner type and we're in a permissive context,
5389 if (Sel == Sema::AbstractNone) return;
5391 // Check whether the type matches the abstract type.
5392 QualType T = TL.getType();
5393 if (T->isArrayType()) {
5394 Sel = Sema::AbstractArrayType;
5395 T = Info.S.Context.getBaseElementType(T);
5397 CanQualType CT = T->getCanonicalTypeUnqualified().getUnqualifiedType();
5398 if (CT != Info.AbstractType) return;
5400 // It matched; do some magic.
5401 if (Sel == Sema::AbstractArrayType) {
5402 Info.S.Diag(Ctx->getLocation(), diag::err_array_of_abstract_type)
5403 << T << TL.getSourceRange();
5405 Info.S.Diag(Ctx->getLocation(), diag::err_abstract_type_in_decl)
5406 << Sel << T << TL.getSourceRange();
5408 Info.DiagnoseAbstractType();
5412 void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
5413 Sema::AbstractDiagSelID Sel) {
5414 CheckAbstractUsage(*this, D).Visit(TL, Sel);
5419 /// Check for invalid uses of an abstract type in a method declaration.
5420 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5421 CXXMethodDecl *MD) {
5422 // No need to do the check on definitions, which require that
5423 // the return/param types be complete.
5424 if (MD->doesThisDeclarationHaveABody())
5427 // For safety's sake, just ignore it if we don't have type source
5428 // information. This should never happen for non-implicit methods,
5430 if (TypeSourceInfo *TSI = MD->getTypeSourceInfo())
5431 Info.CheckType(MD, TSI->getTypeLoc(), Sema::AbstractNone);
5434 /// Check for invalid uses of an abstract type within a class definition.
5435 static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
5436 CXXRecordDecl *RD) {
5437 for (auto *D : RD->decls()) {
5438 if (D->isImplicit()) continue;
5440 // Methods and method templates.
5441 if (isa<CXXMethodDecl>(D)) {
5442 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(D));
5443 } else if (isa<FunctionTemplateDecl>(D)) {
5444 FunctionDecl *FD = cast<FunctionTemplateDecl>(D)->getTemplatedDecl();
5445 CheckAbstractClassUsage(Info, cast<CXXMethodDecl>(FD));
5447 // Fields and static variables.
5448 } else if (isa<FieldDecl>(D)) {
5449 FieldDecl *FD = cast<FieldDecl>(D);
5450 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
5451 Info.CheckType(FD, TSI->getTypeLoc(), Sema::AbstractFieldType);
5452 } else if (isa<VarDecl>(D)) {
5453 VarDecl *VD = cast<VarDecl>(D);
5454 if (TypeSourceInfo *TSI = VD->getTypeSourceInfo())
5455 Info.CheckType(VD, TSI->getTypeLoc(), Sema::AbstractVariableType);
5457 // Nested classes and class templates.
5458 } else if (isa<CXXRecordDecl>(D)) {
5459 CheckAbstractClassUsage(Info, cast<CXXRecordDecl>(D));
5460 } else if (isa<ClassTemplateDecl>(D)) {
5461 CheckAbstractClassUsage(Info,
5462 cast<ClassTemplateDecl>(D)->getTemplatedDecl());
5467 static void ReferenceDllExportedMethods(Sema &S, CXXRecordDecl *Class) {
5468 Attr *ClassAttr = getDLLAttr(Class);
5472 assert(ClassAttr->getKind() == attr::DLLExport);
5474 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5476 if (TSK == TSK_ExplicitInstantiationDeclaration)
5477 // Don't go any further if this is just an explicit instantiation
5481 for (Decl *Member : Class->decls()) {
5482 auto *MD = dyn_cast<CXXMethodDecl>(Member);
5486 if (Member->getAttr<DLLExportAttr>()) {
5487 if (MD->isUserProvided()) {
5488 // Instantiate non-default class member functions ...
5490 // .. except for certain kinds of template specializations.
5491 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
5494 S.MarkFunctionReferenced(Class->getLocation(), MD);
5496 // The function will be passed to the consumer when its definition is
5498 } else if (!MD->isTrivial() || MD->isExplicitlyDefaulted() ||
5499 MD->isCopyAssignmentOperator() ||
5500 MD->isMoveAssignmentOperator()) {
5501 // Synthesize and instantiate non-trivial implicit methods, explicitly
5502 // defaulted methods, and the copy and move assignment operators. The
5503 // latter are exported even if they are trivial, because the address of
5504 // an operator can be taken and should compare equal across libraries.
5505 DiagnosticErrorTrap Trap(S.Diags);
5506 S.MarkFunctionReferenced(Class->getLocation(), MD);
5507 if (Trap.hasErrorOccurred()) {
5508 S.Diag(ClassAttr->getLocation(), diag::note_due_to_dllexported_class)
5509 << Class->getName() << !S.getLangOpts().CPlusPlus11;
5513 // There is no later point when we will see the definition of this
5514 // function, so pass it to the consumer now.
5515 S.Consumer.HandleTopLevelDecl(DeclGroupRef(MD));
5521 static void checkForMultipleExportedDefaultConstructors(Sema &S,
5522 CXXRecordDecl *Class) {
5523 // Only the MS ABI has default constructor closures, so we don't need to do
5524 // this semantic checking anywhere else.
5525 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
5528 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
5529 for (Decl *Member : Class->decls()) {
5530 // Look for exported default constructors.
5531 auto *CD = dyn_cast<CXXConstructorDecl>(Member);
5532 if (!CD || !CD->isDefaultConstructor())
5534 auto *Attr = CD->getAttr<DLLExportAttr>();
5538 // If the class is non-dependent, mark the default arguments as ODR-used so
5539 // that we can properly codegen the constructor closure.
5540 if (!Class->isDependentContext()) {
5541 for (ParmVarDecl *PD : CD->parameters()) {
5542 (void)S.CheckCXXDefaultArgExpr(Attr->getLocation(), CD, PD);
5543 S.DiscardCleanupsInEvaluationContext();
5547 if (LastExportedDefaultCtor) {
5548 S.Diag(LastExportedDefaultCtor->getLocation(),
5549 diag::err_attribute_dll_ambiguous_default_ctor)
5551 S.Diag(CD->getLocation(), diag::note_entity_declared_at)
5552 << CD->getDeclName();
5555 LastExportedDefaultCtor = CD;
5559 /// \brief Check class-level dllimport/dllexport attribute.
5560 void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
5561 Attr *ClassAttr = getDLLAttr(Class);
5563 // MSVC inherits DLL attributes to partial class template specializations.
5564 if (Context.getTargetInfo().getCXXABI().isMicrosoft() && !ClassAttr) {
5565 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Class)) {
5566 if (Attr *TemplateAttr =
5567 getDLLAttr(Spec->getSpecializedTemplate()->getTemplatedDecl())) {
5568 auto *A = cast<InheritableAttr>(TemplateAttr->clone(getASTContext()));
5569 A->setInherited(true);
5578 if (!Class->isExternallyVisible()) {
5579 Diag(Class->getLocation(), diag::err_attribute_dll_not_extern)
5580 << Class << ClassAttr;
5584 if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5585 !ClassAttr->isInherited()) {
5586 // Diagnose dll attributes on members of class with dll attribute.
5587 for (Decl *Member : Class->decls()) {
5588 if (!isa<VarDecl>(Member) && !isa<CXXMethodDecl>(Member))
5590 InheritableAttr *MemberAttr = getDLLAttr(Member);
5591 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
5594 Diag(MemberAttr->getLocation(),
5595 diag::err_attribute_dll_member_of_dll_class)
5596 << MemberAttr << ClassAttr;
5597 Diag(ClassAttr->getLocation(), diag::note_previous_attribute);
5598 Member->setInvalidDecl();
5602 if (Class->getDescribedClassTemplate())
5603 // Don't inherit dll attribute until the template is instantiated.
5606 // The class is either imported or exported.
5607 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
5609 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
5611 // Ignore explicit dllexport on explicit class template instantiation declarations.
5612 if (ClassExported && !ClassAttr->isInherited() &&
5613 TSK == TSK_ExplicitInstantiationDeclaration) {
5614 Class->dropAttr<DLLExportAttr>();
5618 // Force declaration of implicit members so they can inherit the attribute.
5619 ForceDeclarationOfImplicitMembers(Class);
5621 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
5622 // seem to be true in practice?
5624 for (Decl *Member : Class->decls()) {
5625 VarDecl *VD = dyn_cast<VarDecl>(Member);
5626 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Member);
5628 // Only methods and static fields inherit the attributes.
5633 // Don't process deleted methods.
5634 if (MD->isDeleted())
5637 if (MD->isInlined()) {
5638 // MinGW does not import or export inline methods.
5639 if (!Context.getTargetInfo().getCXXABI().isMicrosoft() &&
5640 !Context.getTargetInfo().getTriple().isWindowsItaniumEnvironment())
5643 // MSVC versions before 2015 don't export the move assignment operators
5644 // and move constructor, so don't attempt to import/export them if
5645 // we have a definition.
5646 auto *Ctor = dyn_cast<CXXConstructorDecl>(MD);
5647 if ((MD->isMoveAssignmentOperator() ||
5648 (Ctor && Ctor->isMoveConstructor())) &&
5649 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015))
5652 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
5653 // operator is exported anyway.
5654 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5655 (Ctor || isa<CXXDestructorDecl>(MD)) && MD->isTrivial())
5660 if (!cast<NamedDecl>(Member)->isExternallyVisible())
5663 if (!getDLLAttr(Member)) {
5665 cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5666 NewAttr->setInherited(true);
5667 Member->addAttr(NewAttr);
5672 DelayedDllExportClasses.push_back(Class);
5675 /// \brief Perform propagation of DLL attributes from a derived class to a
5676 /// templated base class for MS compatibility.
5677 void Sema::propagateDLLAttrToBaseClassTemplate(
5678 CXXRecordDecl *Class, Attr *ClassAttr,
5679 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
5681 BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
5682 // If the base class template has a DLL attribute, don't try to change it.
5686 auto TSK = BaseTemplateSpec->getSpecializationKind();
5687 if (!getDLLAttr(BaseTemplateSpec) &&
5688 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
5689 TSK == TSK_ImplicitInstantiation)) {
5690 // The template hasn't been instantiated yet (or it has, but only as an
5691 // explicit instantiation declaration or implicit instantiation, which means
5692 // we haven't codegenned any members yet), so propagate the attribute.
5693 auto *NewAttr = cast<InheritableAttr>(ClassAttr->clone(getASTContext()));
5694 NewAttr->setInherited(true);
5695 BaseTemplateSpec->addAttr(NewAttr);
5697 // If the template is already instantiated, checkDLLAttributeRedeclaration()
5698 // needs to be run again to work see the new attribute. Otherwise this will
5699 // get run whenever the template is instantiated.
5700 if (TSK != TSK_Undeclared)
5701 checkClassLevelDLLAttribute(BaseTemplateSpec);
5706 if (getDLLAttr(BaseTemplateSpec)) {
5707 // The template has already been specialized or instantiated with an
5708 // attribute, explicitly or through propagation. We should not try to change
5713 // The template was previously instantiated or explicitly specialized without
5714 // a dll attribute, It's too late for us to add an attribute, so warn that
5715 // this is unsupported.
5716 Diag(BaseLoc, diag::warn_attribute_dll_instantiated_base_class)
5717 << BaseTemplateSpec->isExplicitSpecialization();
5718 Diag(ClassAttr->getLocation(), diag::note_attribute);
5719 if (BaseTemplateSpec->isExplicitSpecialization()) {
5720 Diag(BaseTemplateSpec->getLocation(),
5721 diag::note_template_class_explicit_specialization_was_here)
5722 << BaseTemplateSpec;
5724 Diag(BaseTemplateSpec->getPointOfInstantiation(),
5725 diag::note_template_class_instantiation_was_here)
5726 << BaseTemplateSpec;
5730 static void DefineImplicitSpecialMember(Sema &S, CXXMethodDecl *MD,
5731 SourceLocation DefaultLoc) {
5732 switch (S.getSpecialMember(MD)) {
5733 case Sema::CXXDefaultConstructor:
5734 S.DefineImplicitDefaultConstructor(DefaultLoc,
5735 cast<CXXConstructorDecl>(MD));
5737 case Sema::CXXCopyConstructor:
5738 S.DefineImplicitCopyConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5740 case Sema::CXXCopyAssignment:
5741 S.DefineImplicitCopyAssignment(DefaultLoc, MD);
5743 case Sema::CXXDestructor:
5744 S.DefineImplicitDestructor(DefaultLoc, cast<CXXDestructorDecl>(MD));
5746 case Sema::CXXMoveConstructor:
5747 S.DefineImplicitMoveConstructor(DefaultLoc, cast<CXXConstructorDecl>(MD));
5749 case Sema::CXXMoveAssignment:
5750 S.DefineImplicitMoveAssignment(DefaultLoc, MD);
5752 case Sema::CXXInvalid:
5753 llvm_unreachable("Invalid special member.");
5757 /// Determine whether a type is permitted to be passed or returned in
5758 /// registers, per C++ [class.temporary]p3.
5759 static bool computeCanPassInRegisters(Sema &S, CXXRecordDecl *D) {
5760 if (D->isDependentType() || D->isInvalidDecl())
5763 // Per C++ [class.temporary]p3, the relevant condition is:
5764 // each copy constructor, move constructor, and destructor of X is
5765 // either trivial or deleted, and X has at least one non-deleted copy
5766 // or move constructor
5767 bool HasNonDeletedCopyOrMove = false;
5769 if (D->needsImplicitCopyConstructor() &&
5770 !D->defaultedCopyConstructorIsDeleted()) {
5771 if (!D->hasTrivialCopyConstructor())
5773 HasNonDeletedCopyOrMove = true;
5776 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
5777 !D->defaultedMoveConstructorIsDeleted()) {
5778 if (!D->hasTrivialMoveConstructor())
5780 HasNonDeletedCopyOrMove = true;
5783 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
5784 !D->hasTrivialDestructor())
5787 for (const CXXMethodDecl *MD : D->methods()) {
5788 if (MD->isDeleted())
5791 auto *CD = dyn_cast<CXXConstructorDecl>(MD);
5792 if (CD && CD->isCopyOrMoveConstructor())
5793 HasNonDeletedCopyOrMove = true;
5794 else if (!isa<CXXDestructorDecl>(MD))
5797 if (!MD->isTrivial())
5801 return HasNonDeletedCopyOrMove;
5804 /// \brief Perform semantic checks on a class definition that has been
5805 /// completing, introducing implicitly-declared members, checking for
5806 /// abstract types, etc.
5807 void Sema::CheckCompletedCXXClass(CXXRecordDecl *Record) {
5811 if (Record->isAbstract() && !Record->isInvalidDecl()) {
5812 AbstractUsageInfo Info(*this, Record);
5813 CheckAbstractClassUsage(Info, Record);
5816 // If this is not an aggregate type and has no user-declared constructor,
5817 // complain about any non-static data members of reference or const scalar
5818 // type, since they will never get initializers.
5819 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
5820 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
5821 !Record->isLambda()) {
5822 bool Complained = false;
5823 for (const auto *F : Record->fields()) {
5824 if (F->hasInClassInitializer() || F->isUnnamedBitfield())
5827 if (F->getType()->isReferenceType() ||
5828 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
5830 Diag(Record->getLocation(), diag::warn_no_constructor_for_refconst)
5831 << Record->getTagKind() << Record;
5835 Diag(F->getLocation(), diag::note_refconst_member_not_initialized)
5836 << F->getType()->isReferenceType()
5837 << F->getDeclName();
5842 if (Record->getIdentifier()) {
5843 // C++ [class.mem]p13:
5844 // If T is the name of a class, then each of the following shall have a
5845 // name different from T:
5846 // - every member of every anonymous union that is a member of class T.
5848 // C++ [class.mem]p14:
5849 // In addition, if class T has a user-declared constructor (12.1), every
5850 // non-static data member of class T shall have a name different from T.
5851 DeclContext::lookup_result R = Record->lookup(Record->getDeclName());
5852 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E;
5855 if ((isa<FieldDecl>(D) && Record->hasUserDeclaredConstructor()) ||
5856 isa<IndirectFieldDecl>(D)) {
5857 Diag(D->getLocation(), diag::err_member_name_of_class)
5858 << D->getDeclName();
5864 // Warn if the class has virtual methods but non-virtual public destructor.
5865 if (Record->isPolymorphic() && !Record->isDependentType()) {
5866 CXXDestructorDecl *dtor = Record->getDestructor();
5867 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
5868 !Record->hasAttr<FinalAttr>())
5869 Diag(dtor ? dtor->getLocation() : Record->getLocation(),
5870 diag::warn_non_virtual_dtor) << Context.getRecordType(Record);
5873 if (Record->isAbstract()) {
5874 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
5875 Diag(Record->getLocation(), diag::warn_abstract_final_class)
5876 << FA->isSpelledAsSealed();
5877 DiagnoseAbstractType(Record);
5881 bool HasMethodWithOverrideControl = false,
5882 HasOverridingMethodWithoutOverrideControl = false;
5883 if (!Record->isDependentType()) {
5884 for (auto *M : Record->methods()) {
5885 // See if a method overloads virtual methods in a base
5886 // class without overriding any.
5888 DiagnoseHiddenVirtualMethods(M);
5889 if (M->hasAttr<OverrideAttr>())
5890 HasMethodWithOverrideControl = true;
5891 else if (M->size_overridden_methods() > 0)
5892 HasOverridingMethodWithoutOverrideControl = true;
5893 // Check whether the explicitly-defaulted special members are valid.
5894 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted())
5895 CheckExplicitlyDefaultedSpecialMember(M);
5897 // For an explicitly defaulted or deleted special member, we defer
5898 // determining triviality until the class is complete. That time is now!
5899 CXXSpecialMember CSM = getSpecialMember(M);
5900 if (!M->isImplicit() && !M->isUserProvided()) {
5901 if (CSM != CXXInvalid) {
5902 M->setTrivial(SpecialMemberIsTrivial(M, CSM));
5904 // Inform the class that we've finished declaring this member.
5905 Record->finishedDefaultedOrDeletedMember(M);
5909 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
5910 M->hasAttr<DLLExportAttr>()) {
5911 if (getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015) &&
5913 (CSM == CXXDefaultConstructor || CSM == CXXCopyConstructor ||
5914 CSM == CXXDestructor))
5915 M->dropAttr<DLLExportAttr>();
5917 if (M->hasAttr<DLLExportAttr>()) {
5918 DefineImplicitSpecialMember(*this, M, M->getLocation());
5919 ActOnFinishInlineFunctionDef(M);
5925 if (HasMethodWithOverrideControl &&
5926 HasOverridingMethodWithoutOverrideControl) {
5927 // At least one method has the 'override' control declared.
5928 // Diagnose all other overridden methods which do not have 'override' specified on them.
5929 for (auto *M : Record->methods())
5930 DiagnoseAbsenceOfOverrideControl(M);
5933 // ms_struct is a request to use the same ABI rules as MSVC. Check
5934 // whether this class uses any C++ features that are implemented
5935 // completely differently in MSVC, and if so, emit a diagnostic.
5936 // That diagnostic defaults to an error, but we allow projects to
5937 // map it down to a warning (or ignore it). It's a fairly common
5938 // practice among users of the ms_struct pragma to mass-annotate
5939 // headers, sweeping up a bunch of types that the project doesn't
5940 // really rely on MSVC-compatible layout for. We must therefore
5941 // support "ms_struct except for C++ stuff" as a secondary ABI.
5942 if (Record->isMsStruct(Context) &&
5943 (Record->isPolymorphic() || Record->getNumBases())) {
5944 Diag(Record->getLocation(), diag::warn_cxx_ms_struct);
5947 checkClassLevelDLLAttribute(Record);
5949 Record->setCanPassInRegisters(computeCanPassInRegisters(*this, Record));
5952 /// Look up the special member function that would be called by a special
5953 /// member function for a subobject of class type.
5955 /// \param Class The class type of the subobject.
5956 /// \param CSM The kind of special member function.
5957 /// \param FieldQuals If the subobject is a field, its cv-qualifiers.
5958 /// \param ConstRHS True if this is a copy operation with a const object
5959 /// on its RHS, that is, if the argument to the outer special member
5960 /// function is 'const' and this is not a field marked 'mutable'.
5961 static Sema::SpecialMemberOverloadResult lookupCallFromSpecialMember(
5962 Sema &S, CXXRecordDecl *Class, Sema::CXXSpecialMember CSM,
5963 unsigned FieldQuals, bool ConstRHS) {
5964 unsigned LHSQuals = 0;
5965 if (CSM == Sema::CXXCopyAssignment || CSM == Sema::CXXMoveAssignment)
5966 LHSQuals = FieldQuals;
5968 unsigned RHSQuals = FieldQuals;
5969 if (CSM == Sema::CXXDefaultConstructor || CSM == Sema::CXXDestructor)
5972 RHSQuals |= Qualifiers::Const;
5974 return S.LookupSpecialMember(Class, CSM,
5975 RHSQuals & Qualifiers::Const,
5976 RHSQuals & Qualifiers::Volatile,
5978 LHSQuals & Qualifiers::Const,
5979 LHSQuals & Qualifiers::Volatile);
5982 class Sema::InheritedConstructorInfo {
5984 SourceLocation UseLoc;
5986 /// A mapping from the base classes through which the constructor was
5987 /// inherited to the using shadow declaration in that base class (or a null
5988 /// pointer if the constructor was declared in that base class).
5989 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
5993 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
5994 ConstructorUsingShadowDecl *Shadow)
5995 : S(S), UseLoc(UseLoc) {
5996 bool DiagnosedMultipleConstructedBases = false;
5997 CXXRecordDecl *ConstructedBase = nullptr;
5998 UsingDecl *ConstructedBaseUsing = nullptr;
6000 // Find the set of such base class subobjects and check that there's a
6001 // unique constructed subobject.
6002 for (auto *D : Shadow->redecls()) {
6003 auto *DShadow = cast<ConstructorUsingShadowDecl>(D);
6004 auto *DNominatedBase = DShadow->getNominatedBaseClass();
6005 auto *DConstructedBase = DShadow->getConstructedBaseClass();
6007 InheritedFromBases.insert(
6008 std::make_pair(DNominatedBase->getCanonicalDecl(),
6009 DShadow->getNominatedBaseClassShadowDecl()));
6010 if (DShadow->constructsVirtualBase())
6011 InheritedFromBases.insert(
6012 std::make_pair(DConstructedBase->getCanonicalDecl(),
6013 DShadow->getConstructedBaseClassShadowDecl()));
6015 assert(DNominatedBase == DConstructedBase);
6017 // [class.inhctor.init]p2:
6018 // If the constructor was inherited from multiple base class subobjects
6019 // of type B, the program is ill-formed.
6020 if (!ConstructedBase) {
6021 ConstructedBase = DConstructedBase;
6022 ConstructedBaseUsing = D->getUsingDecl();
6023 } else if (ConstructedBase != DConstructedBase &&
6024 !Shadow->isInvalidDecl()) {
6025 if (!DiagnosedMultipleConstructedBases) {
6026 S.Diag(UseLoc, diag::err_ambiguous_inherited_constructor)
6027 << Shadow->getTargetDecl();
6028 S.Diag(ConstructedBaseUsing->getLocation(),
6029 diag::note_ambiguous_inherited_constructor_using)
6031 DiagnosedMultipleConstructedBases = true;
6033 S.Diag(D->getUsingDecl()->getLocation(),
6034 diag::note_ambiguous_inherited_constructor_using)
6035 << DConstructedBase;
6039 if (DiagnosedMultipleConstructedBases)
6040 Shadow->setInvalidDecl();
6043 /// Find the constructor to use for inherited construction of a base class,
6044 /// and whether that base class constructor inherits the constructor from a
6045 /// virtual base class (in which case it won't actually invoke it).
6046 std::pair<CXXConstructorDecl *, bool>
6047 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
6048 auto It = InheritedFromBases.find(Base->getCanonicalDecl());
6049 if (It == InheritedFromBases.end())
6050 return std::make_pair(nullptr, false);
6052 // This is an intermediary class.
6054 return std::make_pair(
6055 S.findInheritingConstructor(UseLoc, Ctor, It->second),
6056 It->second->constructsVirtualBase());
6058 // This is the base class from which the constructor was inherited.
6059 return std::make_pair(Ctor, false);
6063 /// Is the special member function which would be selected to perform the
6064 /// specified operation on the specified class type a constexpr constructor?
6066 specialMemberIsConstexpr(Sema &S, CXXRecordDecl *ClassDecl,
6067 Sema::CXXSpecialMember CSM, unsigned Quals,
6069 CXXConstructorDecl *InheritedCtor = nullptr,
6070 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6071 // If we're inheriting a constructor, see if we need to call it for this base
6073 if (InheritedCtor) {
6074 assert(CSM == Sema::CXXDefaultConstructor);
6076 Inherited->findConstructorForBase(ClassDecl, InheritedCtor).first;
6078 return BaseCtor->isConstexpr();
6081 if (CSM == Sema::CXXDefaultConstructor)
6082 return ClassDecl->hasConstexprDefaultConstructor();
6084 Sema::SpecialMemberOverloadResult SMOR =
6085 lookupCallFromSpecialMember(S, ClassDecl, CSM, Quals, ConstRHS);
6086 if (!SMOR.getMethod())
6087 // A constructor we wouldn't select can't be "involved in initializing"
6090 return SMOR.getMethod()->isConstexpr();
6093 /// Determine whether the specified special member function would be constexpr
6094 /// if it were implicitly defined.
6095 static bool defaultedSpecialMemberIsConstexpr(
6096 Sema &S, CXXRecordDecl *ClassDecl, Sema::CXXSpecialMember CSM,
6097 bool ConstArg, CXXConstructorDecl *InheritedCtor = nullptr,
6098 Sema::InheritedConstructorInfo *Inherited = nullptr) {
6099 if (!S.getLangOpts().CPlusPlus11)
6102 // C++11 [dcl.constexpr]p4:
6103 // In the definition of a constexpr constructor [...]
6106 case Sema::CXXDefaultConstructor:
6109 // Since default constructor lookup is essentially trivial (and cannot
6110 // involve, for instance, template instantiation), we compute whether a
6111 // defaulted default constructor is constexpr directly within CXXRecordDecl.
6113 // This is important for performance; we need to know whether the default
6114 // constructor is constexpr to determine whether the type is a literal type.
6115 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
6117 case Sema::CXXCopyConstructor:
6118 case Sema::CXXMoveConstructor:
6119 // For copy or move constructors, we need to perform overload resolution.
6122 case Sema::CXXCopyAssignment:
6123 case Sema::CXXMoveAssignment:
6124 if (!S.getLangOpts().CPlusPlus14)
6126 // In C++1y, we need to perform overload resolution.
6130 case Sema::CXXDestructor:
6131 case Sema::CXXInvalid:
6135 // -- if the class is a non-empty union, or for each non-empty anonymous
6136 // union member of a non-union class, exactly one non-static data member
6137 // shall be initialized; [DR1359]
6139 // If we squint, this is guaranteed, since exactly one non-static data member
6140 // will be initialized (if the constructor isn't deleted), we just don't know
6142 if (Ctor && ClassDecl->isUnion())
6143 return CSM == Sema::CXXDefaultConstructor
6144 ? ClassDecl->hasInClassInitializer() ||
6145 !ClassDecl->hasVariantMembers()
6148 // -- the class shall not have any virtual base classes;
6149 if (Ctor && ClassDecl->getNumVBases())
6152 // C++1y [class.copy]p26:
6153 // -- [the class] is a literal type, and
6154 if (!Ctor && !ClassDecl->isLiteral())
6157 // -- every constructor involved in initializing [...] base class
6158 // sub-objects shall be a constexpr constructor;
6159 // -- the assignment operator selected to copy/move each direct base
6160 // class is a constexpr function, and
6161 for (const auto &B : ClassDecl->bases()) {
6162 const RecordType *BaseType = B.getType()->getAs<RecordType>();
6163 if (!BaseType) continue;
6165 CXXRecordDecl *BaseClassDecl = cast<CXXRecordDecl>(BaseType->getDecl());
6166 if (!specialMemberIsConstexpr(S, BaseClassDecl, CSM, 0, ConstArg,
6167 InheritedCtor, Inherited))
6171 // -- every constructor involved in initializing non-static data members
6172 // [...] shall be a constexpr constructor;
6173 // -- every non-static data member and base class sub-object shall be
6175 // -- for each non-static data member of X that is of class type (or array
6176 // thereof), the assignment operator selected to copy/move that member is
6177 // a constexpr function
6178 for (const auto *F : ClassDecl->fields()) {
6179 if (F->isInvalidDecl())
6181 if (CSM == Sema::CXXDefaultConstructor && F->hasInClassInitializer())
6183 QualType BaseType = S.Context.getBaseElementType(F->getType());
6184 if (const RecordType *RecordTy = BaseType->getAs<RecordType>()) {
6185 CXXRecordDecl *FieldRecDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
6186 if (!specialMemberIsConstexpr(S, FieldRecDecl, CSM,
6187 BaseType.getCVRQualifiers(),
6188 ConstArg && !F->isMutable()))
6190 } else if (CSM == Sema::CXXDefaultConstructor) {
6195 // All OK, it's constexpr!
6199 static Sema::ImplicitExceptionSpecification
6200 ComputeDefaultedSpecialMemberExceptionSpec(
6201 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6202 Sema::InheritedConstructorInfo *ICI);
6204 static Sema::ImplicitExceptionSpecification
6205 computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, CXXMethodDecl *MD) {
6206 auto CSM = S.getSpecialMember(MD);
6207 if (CSM != Sema::CXXInvalid)
6208 return ComputeDefaultedSpecialMemberExceptionSpec(S, Loc, MD, CSM, nullptr);
6210 auto *CD = cast<CXXConstructorDecl>(MD);
6211 assert(CD->getInheritedConstructor() &&
6212 "only special members have implicit exception specs");
6213 Sema::InheritedConstructorInfo ICI(
6214 S, Loc, CD->getInheritedConstructor().getShadowDecl());
6215 return ComputeDefaultedSpecialMemberExceptionSpec(
6216 S, Loc, CD, Sema::CXXDefaultConstructor, &ICI);
6219 static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
6220 CXXMethodDecl *MD) {
6221 FunctionProtoType::ExtProtoInfo EPI;
6223 // Build an exception specification pointing back at this member.
6224 EPI.ExceptionSpec.Type = EST_Unevaluated;
6225 EPI.ExceptionSpec.SourceDecl = MD;
6227 // Set the calling convention to the default for C++ instance methods.
6228 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
6229 S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6230 /*IsCXXMethod=*/true));
6234 void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, CXXMethodDecl *MD) {
6235 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
6236 if (FPT->getExceptionSpecType() != EST_Unevaluated)
6239 // Evaluate the exception specification.
6240 auto IES = computeImplicitExceptionSpec(*this, Loc, MD);
6241 auto ESI = IES.getExceptionSpec();
6243 // Update the type of the special member to use it.
6244 UpdateExceptionSpec(MD, ESI);
6246 // A user-provided destructor can be defined outside the class. When that
6247 // happens, be sure to update the exception specification on both
6249 const FunctionProtoType *CanonicalFPT =
6250 MD->getCanonicalDecl()->getType()->castAs<FunctionProtoType>();
6251 if (CanonicalFPT->getExceptionSpecType() == EST_Unevaluated)
6252 UpdateExceptionSpec(MD->getCanonicalDecl(), ESI);
6255 void Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD) {
6256 CXXRecordDecl *RD = MD->getParent();
6257 CXXSpecialMember CSM = getSpecialMember(MD);
6259 assert(MD->isExplicitlyDefaulted() && CSM != CXXInvalid &&
6260 "not an explicitly-defaulted special member");
6262 // Whether this was the first-declared instance of the constructor.
6263 // This affects whether we implicitly add an exception spec and constexpr.
6264 bool First = MD == MD->getCanonicalDecl();
6266 bool HadError = false;
6268 // C++11 [dcl.fct.def.default]p1:
6269 // A function that is explicitly defaulted shall
6270 // -- be a special member function (checked elsewhere),
6271 // -- have the same type (except for ref-qualifiers, and except that a
6272 // copy operation can take a non-const reference) as an implicit
6274 // -- not have default arguments.
6275 unsigned ExpectedParams = 1;
6276 if (CSM == CXXDefaultConstructor || CSM == CXXDestructor)
6278 if (MD->getNumParams() != ExpectedParams) {
6279 // This also checks for default arguments: a copy or move constructor with a
6280 // default argument is classified as a default constructor, and assignment
6281 // operations and destructors can't have default arguments.
6282 Diag(MD->getLocation(), diag::err_defaulted_special_member_params)
6283 << CSM << MD->getSourceRange();
6285 } else if (MD->isVariadic()) {
6286 Diag(MD->getLocation(), diag::err_defaulted_special_member_variadic)
6287 << CSM << MD->getSourceRange();
6291 const FunctionProtoType *Type = MD->getType()->getAs<FunctionProtoType>();
6293 bool CanHaveConstParam = false;
6294 if (CSM == CXXCopyConstructor)
6295 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
6296 else if (CSM == CXXCopyAssignment)
6297 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
6299 QualType ReturnType = Context.VoidTy;
6300 if (CSM == CXXCopyAssignment || CSM == CXXMoveAssignment) {
6301 // Check for return type matching.
6302 ReturnType = Type->getReturnType();
6303 QualType ExpectedReturnType =
6304 Context.getLValueReferenceType(Context.getTypeDeclType(RD));
6305 if (!Context.hasSameType(ReturnType, ExpectedReturnType)) {
6306 Diag(MD->getLocation(), diag::err_defaulted_special_member_return_type)
6307 << (CSM == CXXMoveAssignment) << ExpectedReturnType;
6311 // A defaulted special member cannot have cv-qualifiers.
6312 if (Type->getTypeQuals()) {
6313 Diag(MD->getLocation(), diag::err_defaulted_special_member_quals)
6314 << (CSM == CXXMoveAssignment) << getLangOpts().CPlusPlus14;
6319 // Check for parameter type matching.
6320 QualType ArgType = ExpectedParams ? Type->getParamType(0) : QualType();
6321 bool HasConstParam = false;
6322 if (ExpectedParams && ArgType->isReferenceType()) {
6323 // Argument must be reference to possibly-const T.
6324 QualType ReferentType = ArgType->getPointeeType();
6325 HasConstParam = ReferentType.isConstQualified();
6327 if (ReferentType.isVolatileQualified()) {
6328 Diag(MD->getLocation(),
6329 diag::err_defaulted_special_member_volatile_param) << CSM;
6333 if (HasConstParam && !CanHaveConstParam) {
6334 if (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment) {
6335 Diag(MD->getLocation(),
6336 diag::err_defaulted_special_member_copy_const_param)
6337 << (CSM == CXXCopyAssignment);
6338 // FIXME: Explain why this special member can't be const.
6340 Diag(MD->getLocation(),
6341 diag::err_defaulted_special_member_move_const_param)
6342 << (CSM == CXXMoveAssignment);
6346 } else if (ExpectedParams) {
6347 // A copy assignment operator can take its argument by value, but a
6348 // defaulted one cannot.
6349 assert(CSM == CXXCopyAssignment && "unexpected non-ref argument");
6350 Diag(MD->getLocation(), diag::err_defaulted_copy_assign_not_ref);
6354 // C++11 [dcl.fct.def.default]p2:
6355 // An explicitly-defaulted function may be declared constexpr only if it
6356 // would have been implicitly declared as constexpr,
6357 // Do not apply this rule to members of class templates, since core issue 1358
6358 // makes such functions always instantiate to constexpr functions. For
6359 // functions which cannot be constexpr (for non-constructors in C++11 and for
6360 // destructors in C++1y), this is checked elsewhere.
6361 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, RD, CSM,
6363 if ((getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(MD)
6364 : isa<CXXConstructorDecl>(MD)) &&
6365 MD->isConstexpr() && !Constexpr &&
6366 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
6367 Diag(MD->getLocStart(), diag::err_incorrect_defaulted_constexpr) << CSM;
6368 // FIXME: Explain why the special member can't be constexpr.
6372 // and may have an explicit exception-specification only if it is compatible
6373 // with the exception-specification on the implicit declaration.
6374 if (Type->hasExceptionSpec()) {
6375 // Delay the check if this is the first declaration of the special member,
6376 // since we may not have parsed some necessary in-class initializers yet.
6378 // If the exception specification needs to be instantiated, do so now,
6379 // before we clobber it with an EST_Unevaluated specification below.
6380 if (Type->getExceptionSpecType() == EST_Uninstantiated) {
6381 InstantiateExceptionSpec(MD->getLocStart(), MD);
6382 Type = MD->getType()->getAs<FunctionProtoType>();
6384 DelayedDefaultedMemberExceptionSpecs.push_back(std::make_pair(MD, Type));
6386 CheckExplicitlyDefaultedMemberExceptionSpec(MD, Type);
6389 // If a function is explicitly defaulted on its first declaration,
6391 // -- it is implicitly considered to be constexpr if the implicit
6392 // definition would be,
6393 MD->setConstexpr(Constexpr);
6395 // -- it is implicitly considered to have the same exception-specification
6396 // as if it had been implicitly declared,
6397 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
6398 EPI.ExceptionSpec.Type = EST_Unevaluated;
6399 EPI.ExceptionSpec.SourceDecl = MD;
6400 MD->setType(Context.getFunctionType(ReturnType,
6401 llvm::makeArrayRef(&ArgType,
6406 if (ShouldDeleteSpecialMember(MD, CSM)) {
6408 SetDeclDeleted(MD, MD->getLocation());
6410 // C++11 [dcl.fct.def.default]p4:
6411 // [For a] user-provided explicitly-defaulted function [...] if such a
6412 // function is implicitly defined as deleted, the program is ill-formed.
6413 Diag(MD->getLocation(), diag::err_out_of_line_default_deletes) << CSM;
6414 ShouldDeleteSpecialMember(MD, CSM, nullptr, /*Diagnose*/true);
6420 MD->setInvalidDecl();
6423 /// Check whether the exception specification provided for an
6424 /// explicitly-defaulted special member matches the exception specification
6425 /// that would have been generated for an implicit special member, per
6426 /// C++11 [dcl.fct.def.default]p2.
6427 void Sema::CheckExplicitlyDefaultedMemberExceptionSpec(
6428 CXXMethodDecl *MD, const FunctionProtoType *SpecifiedType) {
6429 // If the exception specification was explicitly specified but hadn't been
6430 // parsed when the method was defaulted, grab it now.
6431 if (SpecifiedType->getExceptionSpecType() == EST_Unparsed)
6433 MD->getTypeSourceInfo()->getType()->castAs<FunctionProtoType>();
6435 // Compute the implicit exception specification.
6436 CallingConv CC = Context.getDefaultCallingConvention(/*IsVariadic=*/false,
6437 /*IsCXXMethod=*/true);
6438 FunctionProtoType::ExtProtoInfo EPI(CC);
6439 auto IES = computeImplicitExceptionSpec(*this, MD->getLocation(), MD);
6440 EPI.ExceptionSpec = IES.getExceptionSpec();
6441 const FunctionProtoType *ImplicitType = cast<FunctionProtoType>(
6442 Context.getFunctionType(Context.VoidTy, None, EPI));
6444 // Ensure that it matches.
6445 CheckEquivalentExceptionSpec(
6446 PDiag(diag::err_incorrect_defaulted_exception_spec)
6447 << getSpecialMember(MD), PDiag(),
6448 ImplicitType, SourceLocation(),
6449 SpecifiedType, MD->getLocation());
6452 void Sema::CheckDelayedMemberExceptionSpecs() {
6453 decltype(DelayedExceptionSpecChecks) Checks;
6454 decltype(DelayedDefaultedMemberExceptionSpecs) Specs;
6456 std::swap(Checks, DelayedExceptionSpecChecks);
6457 std::swap(Specs, DelayedDefaultedMemberExceptionSpecs);
6459 // Perform any deferred checking of exception specifications for virtual
6461 for (auto &Check : Checks)
6462 CheckOverridingFunctionExceptionSpec(Check.first, Check.second);
6464 // Check that any explicitly-defaulted methods have exception specifications
6465 // compatible with their implicit exception specifications.
6466 for (auto &Spec : Specs)
6467 CheckExplicitlyDefaultedMemberExceptionSpec(Spec.first, Spec.second);
6471 /// CRTP base class for visiting operations performed by a special member
6472 /// function (or inherited constructor).
6473 template<typename Derived>
6474 struct SpecialMemberVisitor {
6477 Sema::CXXSpecialMember CSM;
6478 Sema::InheritedConstructorInfo *ICI;
6480 // Properties of the special member, computed for convenience.
6481 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
6483 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
6484 Sema::InheritedConstructorInfo *ICI)
6485 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
6487 case Sema::CXXDefaultConstructor:
6488 case Sema::CXXCopyConstructor:
6489 case Sema::CXXMoveConstructor:
6490 IsConstructor = true;
6492 case Sema::CXXCopyAssignment:
6493 case Sema::CXXMoveAssignment:
6494 IsAssignment = true;
6496 case Sema::CXXDestructor:
6498 case Sema::CXXInvalid:
6499 llvm_unreachable("invalid special member kind");
6502 if (MD->getNumParams()) {
6503 if (const ReferenceType *RT =
6504 MD->getParamDecl(0)->getType()->getAs<ReferenceType>())
6505 ConstArg = RT->getPointeeType().isConstQualified();
6509 Derived &getDerived() { return static_cast<Derived&>(*this); }
6511 /// Is this a "move" special member?
6512 bool isMove() const {
6513 return CSM == Sema::CXXMoveConstructor || CSM == Sema::CXXMoveAssignment;
6516 /// Look up the corresponding special member in the given class.
6517 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
6518 unsigned Quals, bool IsMutable) {
6519 return lookupCallFromSpecialMember(S, Class, CSM, Quals,
6520 ConstArg && !IsMutable);
6523 /// Look up the constructor for the specified base class to see if it's
6524 /// overridden due to this being an inherited constructor.
6525 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
6528 assert(CSM == Sema::CXXDefaultConstructor);
6530 cast<CXXConstructorDecl>(MD)->getInheritedConstructor().getConstructor();
6531 if (auto *MD = ICI->findConstructorForBase(Class, BaseCtor).first)
6536 /// A base or member subobject.
6537 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
6539 /// Get the location to use for a subobject in diagnostics.
6540 static SourceLocation getSubobjectLoc(Subobject Subobj) {
6541 // FIXME: For an indirect virtual base, the direct base leading to
6542 // the indirect virtual base would be a more useful choice.
6543 if (auto *B = Subobj.dyn_cast<CXXBaseSpecifier*>())
6544 return B->getBaseTypeLoc();
6546 return Subobj.get<FieldDecl*>()->getLocation();
6550 /// Visit all non-virtual (direct) bases.
6551 VisitNonVirtualBases,
6552 /// Visit all direct bases, virtual or not.
6554 /// Visit all non-virtual bases, and all virtual bases if the class
6555 /// is not abstract.
6556 VisitPotentiallyConstructedBases,
6557 /// Visit all direct or virtual bases.
6561 // Visit the bases and members of the class.
6562 bool visit(BasesToVisit Bases) {
6563 CXXRecordDecl *RD = MD->getParent();
6565 if (Bases == VisitPotentiallyConstructedBases)
6566 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
6568 for (auto &B : RD->bases())
6569 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
6570 getDerived().visitBase(&B))
6573 if (Bases == VisitAllBases)
6574 for (auto &B : RD->vbases())
6575 if (getDerived().visitBase(&B))
6578 for (auto *F : RD->fields())
6579 if (!F->isInvalidDecl() && !F->isUnnamedBitfield() &&
6580 getDerived().visitField(F))
6589 struct SpecialMemberDeletionInfo
6590 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
6595 bool AllFieldsAreConst;
6597 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
6598 Sema::CXXSpecialMember CSM,
6599 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
6600 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
6601 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
6603 bool inUnion() const { return MD->getParent()->isUnion(); }
6605 Sema::CXXSpecialMember getEffectiveCSM() {
6606 return ICI ? Sema::CXXInvalid : CSM;
6609 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
6610 bool visitField(FieldDecl *Field) { return shouldDeleteForField(Field); }
6612 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
6613 bool shouldDeleteForField(FieldDecl *FD);
6614 bool shouldDeleteForAllConstMembers();
6616 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
6618 bool shouldDeleteForSubobjectCall(Subobject Subobj,
6619 Sema::SpecialMemberOverloadResult SMOR,
6620 bool IsDtorCallInCtor);
6622 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
6626 /// Is the given special member inaccessible when used on the given
6628 bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
6629 CXXMethodDecl *target) {
6630 /// If we're operating on a base class, the object type is the
6631 /// type of this special member.
6633 AccessSpecifier access = target->getAccess();
6634 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
6635 objectTy = S.Context.getTypeDeclType(MD->getParent());
6636 access = CXXRecordDecl::MergeAccess(base->getAccessSpecifier(), access);
6638 // If we're operating on a field, the object type is the type of the field.
6640 objectTy = S.Context.getTypeDeclType(target->getParent());
6643 return S.isSpecialMemberAccessibleForDeletion(target, access, objectTy);
6646 /// Check whether we should delete a special member due to the implicit
6647 /// definition containing a call to a special member of a subobject.
6648 bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
6649 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
6650 bool IsDtorCallInCtor) {
6651 CXXMethodDecl *Decl = SMOR.getMethod();
6652 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6656 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted)
6657 DiagKind = !Decl ? 0 : 1;
6658 else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
6660 else if (!isAccessible(Subobj, Decl))
6662 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
6663 !Decl->isTrivial()) {
6664 // A member of a union must have a trivial corresponding special member.
6665 // As a weird special case, a destructor call from a union's constructor
6666 // must be accessible and non-deleted, but need not be trivial. Such a
6667 // destructor is never actually called, but is semantically checked as
6677 S.Diag(Field->getLocation(),
6678 diag::note_deleted_special_member_class_subobject)
6679 << getEffectiveCSM() << MD->getParent() << /*IsField*/true
6680 << Field << DiagKind << IsDtorCallInCtor;
6682 CXXBaseSpecifier *Base = Subobj.get<CXXBaseSpecifier*>();
6683 S.Diag(Base->getLocStart(),
6684 diag::note_deleted_special_member_class_subobject)
6685 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6686 << Base->getType() << DiagKind << IsDtorCallInCtor;
6690 S.NoteDeletedFunction(Decl);
6691 // FIXME: Explain inaccessibility if DiagKind == 3.
6697 /// Check whether we should delete a special member function due to having a
6698 /// direct or virtual base class or non-static data member of class type M.
6699 bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
6700 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
6701 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
6702 bool IsMutable = Field && Field->isMutable();
6704 // C++11 [class.ctor]p5:
6705 // -- any direct or virtual base class, or non-static data member with no
6706 // brace-or-equal-initializer, has class type M (or array thereof) and
6707 // either M has no default constructor or overload resolution as applied
6708 // to M's default constructor results in an ambiguity or in a function
6709 // that is deleted or inaccessible
6710 // C++11 [class.copy]p11, C++11 [class.copy]p23:
6711 // -- a direct or virtual base class B that cannot be copied/moved because
6712 // overload resolution, as applied to B's corresponding special member,
6713 // results in an ambiguity or a function that is deleted or inaccessible
6714 // from the defaulted special member
6715 // C++11 [class.dtor]p5:
6716 // -- any direct or virtual base class [...] has a type with a destructor
6717 // that is deleted or inaccessible
6718 if (!(CSM == Sema::CXXDefaultConstructor &&
6719 Field && Field->hasInClassInitializer()) &&
6720 shouldDeleteForSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable),
6724 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
6725 // -- any direct or virtual base class or non-static data member has a
6726 // type with a destructor that is deleted or inaccessible
6727 if (IsConstructor) {
6728 Sema::SpecialMemberOverloadResult SMOR =
6729 S.LookupSpecialMember(Class, Sema::CXXDestructor,
6730 false, false, false, false, false);
6731 if (shouldDeleteForSubobjectCall(Subobj, SMOR, true))
6738 /// Check whether we should delete a special member function due to the class
6739 /// having a particular direct or virtual base class.
6740 bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
6741 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
6742 // If program is correct, BaseClass cannot be null, but if it is, the error
6743 // must be reported elsewhere.
6746 // If we have an inheriting constructor, check whether we're calling an
6747 // inherited constructor instead of a default constructor.
6748 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
6749 if (auto *BaseCtor = SMOR.getMethod()) {
6750 // Note that we do not check access along this path; other than that,
6751 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
6752 // FIXME: Check that the base has a usable destructor! Sink this into
6753 // shouldDeleteForClassSubobject.
6754 if (BaseCtor->isDeleted() && Diagnose) {
6755 S.Diag(Base->getLocStart(),
6756 diag::note_deleted_special_member_class_subobject)
6757 << getEffectiveCSM() << MD->getParent() << /*IsField*/false
6758 << Base->getType() << /*Deleted*/1 << /*IsDtorCallInCtor*/false;
6759 S.NoteDeletedFunction(BaseCtor);
6761 return BaseCtor->isDeleted();
6763 return shouldDeleteForClassSubobject(BaseClass, Base, 0);
6766 /// Check whether we should delete a special member function due to the class
6767 /// having a particular non-static data member.
6768 bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
6769 QualType FieldType = S.Context.getBaseElementType(FD->getType());
6770 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
6772 if (CSM == Sema::CXXDefaultConstructor) {
6773 // For a default constructor, all references must be initialized in-class
6774 // and, if a union, it must have a non-const member.
6775 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
6777 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6778 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
6781 // C++11 [class.ctor]p5: any non-variant non-static data member of
6782 // const-qualified type (or array thereof) with no
6783 // brace-or-equal-initializer does not have a user-provided default
6785 if (!inUnion() && FieldType.isConstQualified() &&
6786 !FD->hasInClassInitializer() &&
6787 (!FieldRecord || !FieldRecord->hasUserProvidedDefaultConstructor())) {
6789 S.Diag(FD->getLocation(), diag::note_deleted_default_ctor_uninit_field)
6790 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
6794 if (inUnion() && !FieldType.isConstQualified())
6795 AllFieldsAreConst = false;
6796 } else if (CSM == Sema::CXXCopyConstructor) {
6797 // For a copy constructor, data members must not be of rvalue reference
6799 if (FieldType->isRValueReferenceType()) {
6801 S.Diag(FD->getLocation(), diag::note_deleted_copy_ctor_rvalue_reference)
6802 << MD->getParent() << FD << FieldType;
6805 } else if (IsAssignment) {
6806 // For an assignment operator, data members must not be of reference type.
6807 if (FieldType->isReferenceType()) {
6809 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6810 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
6813 if (!FieldRecord && FieldType.isConstQualified()) {
6814 // C++11 [class.copy]p23:
6815 // -- a non-static data member of const non-class type (or array thereof)
6817 S.Diag(FD->getLocation(), diag::note_deleted_assign_field)
6818 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
6824 // Some additional restrictions exist on the variant members.
6825 if (!inUnion() && FieldRecord->isUnion() &&
6826 FieldRecord->isAnonymousStructOrUnion()) {
6827 bool AllVariantFieldsAreConst = true;
6829 // FIXME: Handle anonymous unions declared within anonymous unions.
6830 for (auto *UI : FieldRecord->fields()) {
6831 QualType UnionFieldType = S.Context.getBaseElementType(UI->getType());
6833 if (!UnionFieldType.isConstQualified())
6834 AllVariantFieldsAreConst = false;
6836 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
6837 if (UnionFieldRecord &&
6838 shouldDeleteForClassSubobject(UnionFieldRecord, UI,
6839 UnionFieldType.getCVRQualifiers()))
6843 // At least one member in each anonymous union must be non-const
6844 if (CSM == Sema::CXXDefaultConstructor && AllVariantFieldsAreConst &&
6845 !FieldRecord->field_empty()) {
6847 S.Diag(FieldRecord->getLocation(),
6848 diag::note_deleted_default_ctor_all_const)
6849 << !!ICI << MD->getParent() << /*anonymous union*/1;
6853 // Don't check the implicit member of the anonymous union type.
6854 // This is technically non-conformant, but sanity demands it.
6858 if (shouldDeleteForClassSubobject(FieldRecord, FD,
6859 FieldType.getCVRQualifiers()))
6866 /// C++11 [class.ctor] p5:
6867 /// A defaulted default constructor for a class X is defined as deleted if
6868 /// X is a union and all of its variant members are of const-qualified type.
6869 bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
6870 // This is a silly definition, because it gives an empty union a deleted
6871 // default constructor. Don't do that.
6872 if (CSM == Sema::CXXDefaultConstructor && inUnion() && AllFieldsAreConst) {
6873 bool AnyFields = false;
6874 for (auto *F : MD->getParent()->fields())
6875 if ((AnyFields = !F->isUnnamedBitfield()))
6880 S.Diag(MD->getParent()->getLocation(),
6881 diag::note_deleted_default_ctor_all_const)
6882 << !!ICI << MD->getParent() << /*not anonymous union*/0;
6888 /// Determine whether a defaulted special member function should be defined as
6889 /// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
6890 /// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
6891 bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD, CXXSpecialMember CSM,
6892 InheritedConstructorInfo *ICI,
6894 if (MD->isInvalidDecl())
6896 CXXRecordDecl *RD = MD->getParent();
6897 assert(!RD->isDependentType() && "do deletion after instantiation");
6898 if (!LangOpts.CPlusPlus11 || RD->isInvalidDecl())
6901 // C++11 [expr.lambda.prim]p19:
6902 // The closure type associated with a lambda-expression has a
6903 // deleted (8.4.3) default constructor and a deleted copy
6904 // assignment operator.
6905 if (RD->isLambda() &&
6906 (CSM == CXXDefaultConstructor || CSM == CXXCopyAssignment)) {
6908 Diag(RD->getLocation(), diag::note_lambda_decl);
6912 // For an anonymous struct or union, the copy and assignment special members
6913 // will never be used, so skip the check. For an anonymous union declared at
6914 // namespace scope, the constructor and destructor are used.
6915 if (CSM != CXXDefaultConstructor && CSM != CXXDestructor &&
6916 RD->isAnonymousStructOrUnion())
6919 // C++11 [class.copy]p7, p18:
6920 // If the class definition declares a move constructor or move assignment
6921 // operator, an implicitly declared copy constructor or copy assignment
6922 // operator is defined as deleted.
6923 if (MD->isImplicit() &&
6924 (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment)) {
6925 CXXMethodDecl *UserDeclaredMove = nullptr;
6927 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
6928 // deletion of the corresponding copy operation, not both copy operations.
6929 // MSVC 2015 has adopted the standards conforming behavior.
6930 bool DeletesOnlyMatchingCopy =
6931 getLangOpts().MSVCCompat &&
6932 !getLangOpts().isCompatibleWithMSVC(LangOptions::MSVC2015);
6934 if (RD->hasUserDeclaredMoveConstructor() &&
6935 (!DeletesOnlyMatchingCopy || CSM == CXXCopyConstructor)) {
6936 if (!Diagnose) return true;
6938 // Find any user-declared move constructor.
6939 for (auto *I : RD->ctors()) {
6940 if (I->isMoveConstructor()) {
6941 UserDeclaredMove = I;
6945 assert(UserDeclaredMove);
6946 } else if (RD->hasUserDeclaredMoveAssignment() &&
6947 (!DeletesOnlyMatchingCopy || CSM == CXXCopyAssignment)) {
6948 if (!Diagnose) return true;
6950 // Find any user-declared move assignment operator.
6951 for (auto *I : RD->methods()) {
6952 if (I->isMoveAssignmentOperator()) {
6953 UserDeclaredMove = I;
6957 assert(UserDeclaredMove);
6960 if (UserDeclaredMove) {
6961 Diag(UserDeclaredMove->getLocation(),
6962 diag::note_deleted_copy_user_declared_move)
6963 << (CSM == CXXCopyAssignment) << RD
6964 << UserDeclaredMove->isMoveAssignmentOperator();
6969 // Do access control from the special member function
6970 ContextRAII MethodContext(*this, MD);
6972 // C++11 [class.dtor]p5:
6973 // -- for a virtual destructor, lookup of the non-array deallocation function
6974 // results in an ambiguity or in a function that is deleted or inaccessible
6975 if (CSM == CXXDestructor && MD->isVirtual()) {
6976 FunctionDecl *OperatorDelete = nullptr;
6977 DeclarationName Name =
6978 Context.DeclarationNames.getCXXOperatorName(OO_Delete);
6979 if (FindDeallocationFunction(MD->getLocation(), MD->getParent(), Name,
6980 OperatorDelete, /*Diagnose*/false)) {
6982 Diag(RD->getLocation(), diag::note_deleted_dtor_no_operator_delete);
6987 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
6989 // Per DR1611, do not consider virtual bases of constructors of abstract
6990 // classes, since we are not going to construct them.
6991 // Per DR1658, do not consider virtual bases of destructors of abstract
6993 // Per DR2180, for assignment operators we only assign (and thus only
6994 // consider) direct bases.
6995 if (SMI.visit(SMI.IsAssignment ? SMI.VisitDirectBases
6996 : SMI.VisitPotentiallyConstructedBases))
6999 if (SMI.shouldDeleteForAllConstMembers())
7002 if (getLangOpts().CUDA) {
7003 // We should delete the special member in CUDA mode if target inference
7005 return inferCUDATargetForImplicitSpecialMember(RD, CSM, MD, SMI.ConstArg,
7012 /// Perform lookup for a special member of the specified kind, and determine
7013 /// whether it is trivial. If the triviality can be determined without the
7014 /// lookup, skip it. This is intended for use when determining whether a
7015 /// special member of a containing object is trivial, and thus does not ever
7016 /// perform overload resolution for default constructors.
7018 /// If \p Selected is not \c NULL, \c *Selected will be filled in with the
7019 /// member that was most likely to be intended to be trivial, if any.
7020 static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
7021 Sema::CXXSpecialMember CSM, unsigned Quals,
7022 bool ConstRHS, CXXMethodDecl **Selected) {
7024 *Selected = nullptr;
7027 case Sema::CXXInvalid:
7028 llvm_unreachable("not a special member");
7030 case Sema::CXXDefaultConstructor:
7031 // C++11 [class.ctor]p5:
7032 // A default constructor is trivial if:
7033 // - all the [direct subobjects] have trivial default constructors
7035 // Note, no overload resolution is performed in this case.
7036 if (RD->hasTrivialDefaultConstructor())
7040 // If there's a default constructor which could have been trivial, dig it
7041 // out. Otherwise, if there's any user-provided default constructor, point
7042 // to that as an example of why there's not a trivial one.
7043 CXXConstructorDecl *DefCtor = nullptr;
7044 if (RD->needsImplicitDefaultConstructor())
7045 S.DeclareImplicitDefaultConstructor(RD);
7046 for (auto *CI : RD->ctors()) {
7047 if (!CI->isDefaultConstructor())
7050 if (!DefCtor->isUserProvided())
7054 *Selected = DefCtor;
7059 case Sema::CXXDestructor:
7060 // C++11 [class.dtor]p5:
7061 // A destructor is trivial if:
7062 // - all the direct [subobjects] have trivial destructors
7063 if (RD->hasTrivialDestructor())
7067 if (RD->needsImplicitDestructor())
7068 S.DeclareImplicitDestructor(RD);
7069 *Selected = RD->getDestructor();
7074 case Sema::CXXCopyConstructor:
7075 // C++11 [class.copy]p12:
7076 // A copy constructor is trivial if:
7077 // - the constructor selected to copy each direct [subobject] is trivial
7078 if (RD->hasTrivialCopyConstructor()) {
7079 if (Quals == Qualifiers::Const)
7080 // We must either select the trivial copy constructor or reach an
7081 // ambiguity; no need to actually perform overload resolution.
7083 } else if (!Selected) {
7086 // In C++98, we are not supposed to perform overload resolution here, but we
7087 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
7088 // cases like B as having a non-trivial copy constructor:
7089 // struct A { template<typename T> A(T&); };
7090 // struct B { mutable A a; };
7091 goto NeedOverloadResolution;
7093 case Sema::CXXCopyAssignment:
7094 // C++11 [class.copy]p25:
7095 // A copy assignment operator is trivial if:
7096 // - the assignment operator selected to copy each direct [subobject] is
7098 if (RD->hasTrivialCopyAssignment()) {
7099 if (Quals == Qualifiers::Const)
7101 } else if (!Selected) {
7104 // In C++98, we are not supposed to perform overload resolution here, but we
7105 // treat that as a language defect.
7106 goto NeedOverloadResolution;
7108 case Sema::CXXMoveConstructor:
7109 case Sema::CXXMoveAssignment:
7110 NeedOverloadResolution:
7111 Sema::SpecialMemberOverloadResult SMOR =
7112 lookupCallFromSpecialMember(S, RD, CSM, Quals, ConstRHS);
7114 // The standard doesn't describe how to behave if the lookup is ambiguous.
7115 // We treat it as not making the member non-trivial, just like the standard
7116 // mandates for the default constructor. This should rarely matter, because
7117 // the member will also be deleted.
7118 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
7121 if (!SMOR.getMethod()) {
7122 assert(SMOR.getKind() ==
7123 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
7127 // We deliberately don't check if we found a deleted special member. We're
7130 *Selected = SMOR.getMethod();
7131 return SMOR.getMethod()->isTrivial();
7134 llvm_unreachable("unknown special method kind");
7137 static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
7138 for (auto *CI : RD->ctors())
7139 if (!CI->isImplicit())
7142 // Look for constructor templates.
7143 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
7144 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
7145 if (CXXConstructorDecl *CD =
7146 dyn_cast<CXXConstructorDecl>(TI->getTemplatedDecl()))
7153 /// The kind of subobject we are checking for triviality. The values of this
7154 /// enumeration are used in diagnostics.
7155 enum TrivialSubobjectKind {
7156 /// The subobject is a base class.
7158 /// The subobject is a non-static data member.
7160 /// The object is actually the complete object.
7164 /// Check whether the special member selected for a given type would be trivial.
7165 static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
7166 QualType SubType, bool ConstRHS,
7167 Sema::CXXSpecialMember CSM,
7168 TrivialSubobjectKind Kind,
7170 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
7174 CXXMethodDecl *Selected;
7175 if (findTrivialSpecialMember(S, SubRD, CSM, SubType.getCVRQualifiers(),
7176 ConstRHS, Diagnose ? &Selected : nullptr))
7183 if (!Selected && CSM == Sema::CXXDefaultConstructor) {
7184 S.Diag(SubobjLoc, diag::note_nontrivial_no_def_ctor)
7185 << Kind << SubType.getUnqualifiedType();
7186 if (CXXConstructorDecl *CD = findUserDeclaredCtor(SubRD))
7187 S.Diag(CD->getLocation(), diag::note_user_declared_ctor);
7188 } else if (!Selected)
7189 S.Diag(SubobjLoc, diag::note_nontrivial_no_copy)
7190 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
7191 else if (Selected->isUserProvided()) {
7192 if (Kind == TSK_CompleteObject)
7193 S.Diag(Selected->getLocation(), diag::note_nontrivial_user_provided)
7194 << Kind << SubType.getUnqualifiedType() << CSM;
7196 S.Diag(SubobjLoc, diag::note_nontrivial_user_provided)
7197 << Kind << SubType.getUnqualifiedType() << CSM;
7198 S.Diag(Selected->getLocation(), diag::note_declared_at);
7201 if (Kind != TSK_CompleteObject)
7202 S.Diag(SubobjLoc, diag::note_nontrivial_subobject)
7203 << Kind << SubType.getUnqualifiedType() << CSM;
7205 // Explain why the defaulted or deleted special member isn't trivial.
7206 S.SpecialMemberIsTrivial(Selected, CSM, Diagnose);
7213 /// Check whether the members of a class type allow a special member to be
7215 static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
7216 Sema::CXXSpecialMember CSM,
7217 bool ConstArg, bool Diagnose) {
7218 for (const auto *FI : RD->fields()) {
7219 if (FI->isInvalidDecl() || FI->isUnnamedBitfield())
7222 QualType FieldType = S.Context.getBaseElementType(FI->getType());
7224 // Pretend anonymous struct or union members are members of this class.
7225 if (FI->isAnonymousStructOrUnion()) {
7226 if (!checkTrivialClassMembers(S, FieldType->getAsCXXRecordDecl(),
7227 CSM, ConstArg, Diagnose))
7232 // C++11 [class.ctor]p5:
7233 // A default constructor is trivial if [...]
7234 // -- no non-static data member of its class has a
7235 // brace-or-equal-initializer
7236 if (CSM == Sema::CXXDefaultConstructor && FI->hasInClassInitializer()) {
7238 S.Diag(FI->getLocation(), diag::note_nontrivial_in_class_init) << FI;
7242 // Objective C ARC 4.3.5:
7243 // [...] nontrivally ownership-qualified types are [...] not trivially
7244 // default constructible, copy constructible, move constructible, copy
7245 // assignable, move assignable, or destructible [...]
7246 if (FieldType.hasNonTrivialObjCLifetime()) {
7248 S.Diag(FI->getLocation(), diag::note_nontrivial_objc_ownership)
7249 << RD << FieldType.getObjCLifetime();
7253 bool ConstRHS = ConstArg && !FI->isMutable();
7254 if (!checkTrivialSubobjectCall(S, FI->getLocation(), FieldType, ConstRHS,
7255 CSM, TSK_Field, Diagnose))
7262 /// Diagnose why the specified class does not have a trivial special member of
7264 void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD, CXXSpecialMember CSM) {
7265 QualType Ty = Context.getRecordType(RD);
7267 bool ConstArg = (CSM == CXXCopyConstructor || CSM == CXXCopyAssignment);
7268 checkTrivialSubobjectCall(*this, RD->getLocation(), Ty, ConstArg, CSM,
7269 TSK_CompleteObject, /*Diagnose*/true);
7272 /// Determine whether a defaulted or deleted special member function is trivial,
7273 /// as specified in C++11 [class.ctor]p5, C++11 [class.copy]p12,
7274 /// C++11 [class.copy]p25, and C++11 [class.dtor]p5.
7275 bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMember CSM,
7277 assert(!MD->isUserProvided() && CSM != CXXInvalid && "not special enough");
7279 CXXRecordDecl *RD = MD->getParent();
7281 bool ConstArg = false;
7283 // C++11 [class.copy]p12, p25: [DR1593]
7284 // A [special member] is trivial if [...] its parameter-type-list is
7285 // equivalent to the parameter-type-list of an implicit declaration [...]
7287 case CXXDefaultConstructor:
7289 // Trivial default constructors and destructors cannot have parameters.
7292 case CXXCopyConstructor:
7293 case CXXCopyAssignment: {
7294 // Trivial copy operations always have const, non-volatile parameter types.
7296 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7297 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
7298 if (!RT || RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) {
7300 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7301 << Param0->getSourceRange() << Param0->getType()
7302 << Context.getLValueReferenceType(
7303 Context.getRecordType(RD).withConst());
7309 case CXXMoveConstructor:
7310 case CXXMoveAssignment: {
7311 // Trivial move operations always have non-cv-qualified parameters.
7312 const ParmVarDecl *Param0 = MD->getParamDecl(0);
7313 const RValueReferenceType *RT =
7314 Param0->getType()->getAs<RValueReferenceType>();
7315 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
7317 Diag(Param0->getLocation(), diag::note_nontrivial_param_type)
7318 << Param0->getSourceRange() << Param0->getType()
7319 << Context.getRValueReferenceType(Context.getRecordType(RD));
7326 llvm_unreachable("not a special member");
7329 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
7331 Diag(MD->getParamDecl(MD->getMinRequiredArguments())->getLocation(),
7332 diag::note_nontrivial_default_arg)
7333 << MD->getParamDecl(MD->getMinRequiredArguments())->getSourceRange();
7336 if (MD->isVariadic()) {
7338 Diag(MD->getLocation(), diag::note_nontrivial_variadic);
7342 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7343 // A copy/move [constructor or assignment operator] is trivial if
7344 // -- the [member] selected to copy/move each direct base class subobject
7347 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7348 // A [default constructor or destructor] is trivial if
7349 // -- all the direct base classes have trivial [default constructors or
7351 for (const auto &BI : RD->bases())
7352 if (!checkTrivialSubobjectCall(*this, BI.getLocStart(), BI.getType(),
7353 ConstArg, CSM, TSK_BaseClass, Diagnose))
7356 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
7357 // A copy/move [constructor or assignment operator] for a class X is
7359 // -- for each non-static data member of X that is of class type (or array
7360 // thereof), the constructor selected to copy/move that member is
7363 // C++11 [class.copy]p12, C++11 [class.copy]p25:
7364 // A [default constructor or destructor] is trivial if
7365 // -- for all of the non-static data members of its class that are of class
7366 // type (or array thereof), each such class has a trivial [default
7367 // constructor or destructor]
7368 if (!checkTrivialClassMembers(*this, RD, CSM, ConstArg, Diagnose))
7371 // C++11 [class.dtor]p5:
7372 // A destructor is trivial if [...]
7373 // -- the destructor is not virtual
7374 if (CSM == CXXDestructor && MD->isVirtual()) {
7376 Diag(MD->getLocation(), diag::note_nontrivial_virtual_dtor) << RD;
7380 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
7381 // A [special member] for class X is trivial if [...]
7382 // -- class X has no virtual functions and no virtual base classes
7383 if (CSM != CXXDestructor && MD->getParent()->isDynamicClass()) {
7387 if (RD->getNumVBases()) {
7388 // Check for virtual bases. We already know that the corresponding
7389 // member in all bases is trivial, so vbases must all be direct.
7390 CXXBaseSpecifier &BS = *RD->vbases_begin();
7391 assert(BS.isVirtual());
7392 Diag(BS.getLocStart(), diag::note_nontrivial_has_virtual) << RD << 1;
7396 // Must have a virtual method.
7397 for (const auto *MI : RD->methods()) {
7398 if (MI->isVirtual()) {
7399 SourceLocation MLoc = MI->getLocStart();
7400 Diag(MLoc, diag::note_nontrivial_has_virtual) << RD << 0;
7405 llvm_unreachable("dynamic class with no vbases and no virtual functions");
7408 // Looks like it's trivial!
7413 struct FindHiddenVirtualMethod {
7415 CXXMethodDecl *Method;
7416 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
7417 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7420 /// Check whether any most overriden method from MD in Methods
7421 static bool CheckMostOverridenMethods(
7422 const CXXMethodDecl *MD,
7423 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
7424 if (MD->size_overridden_methods() == 0)
7425 return Methods.count(MD->getCanonicalDecl());
7426 for (const CXXMethodDecl *O : MD->overridden_methods())
7427 if (CheckMostOverridenMethods(O, Methods))
7433 /// Member lookup function that determines whether a given C++
7434 /// method overloads virtual methods in a base class without overriding any,
7435 /// to be used with CXXRecordDecl::lookupInBases().
7436 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
7437 RecordDecl *BaseRecord =
7438 Specifier->getType()->getAs<RecordType>()->getDecl();
7440 DeclarationName Name = Method->getDeclName();
7441 assert(Name.getNameKind() == DeclarationName::Identifier);
7443 bool foundSameNameMethod = false;
7444 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
7445 for (Path.Decls = BaseRecord->lookup(Name); !Path.Decls.empty();
7446 Path.Decls = Path.Decls.slice(1)) {
7447 NamedDecl *D = Path.Decls.front();
7448 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D)) {
7449 MD = MD->getCanonicalDecl();
7450 foundSameNameMethod = true;
7451 // Interested only in hidden virtual methods.
7452 if (!MD->isVirtual())
7454 // If the method we are checking overrides a method from its base
7455 // don't warn about the other overloaded methods. Clang deviates from
7456 // GCC by only diagnosing overloads of inherited virtual functions that
7457 // do not override any other virtual functions in the base. GCC's
7458 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
7459 // function from a base class. These cases may be better served by a
7460 // warning (not specific to virtual functions) on call sites when the
7461 // call would select a different function from the base class, were it
7463 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
7464 if (!S->IsOverload(Method, MD, false))
7466 // Collect the overload only if its hidden.
7467 if (!CheckMostOverridenMethods(MD, OverridenAndUsingBaseMethods))
7468 overloadedMethods.push_back(MD);
7472 if (foundSameNameMethod)
7473 OverloadedMethods.append(overloadedMethods.begin(),
7474 overloadedMethods.end());
7475 return foundSameNameMethod;
7478 } // end anonymous namespace
7480 /// \brief Add the most overriden methods from MD to Methods
7481 static void AddMostOverridenMethods(const CXXMethodDecl *MD,
7482 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
7483 if (MD->size_overridden_methods() == 0)
7484 Methods.insert(MD->getCanonicalDecl());
7486 for (const CXXMethodDecl *O : MD->overridden_methods())
7487 AddMostOverridenMethods(O, Methods);
7490 /// \brief Check if a method overloads virtual methods in a base class without
7492 void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
7493 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7494 if (!MD->getDeclName().isIdentifier())
7497 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
7498 /*bool RecordPaths=*/false,
7499 /*bool DetectVirtual=*/false);
7500 FindHiddenVirtualMethod FHVM;
7504 // Keep the base methods that were overriden or introduced in the subclass
7505 // by 'using' in a set. A base method not in this set is hidden.
7506 CXXRecordDecl *DC = MD->getParent();
7507 DeclContext::lookup_result R = DC->lookup(MD->getDeclName());
7508 for (DeclContext::lookup_iterator I = R.begin(), E = R.end(); I != E; ++I) {
7510 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(*I))
7511 ND = shad->getTargetDecl();
7512 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(ND))
7513 AddMostOverridenMethods(MD, FHVM.OverridenAndUsingBaseMethods);
7516 if (DC->lookupInBases(FHVM, Paths))
7517 OverloadedMethods = FHVM.OverloadedMethods;
7520 void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
7521 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
7522 for (unsigned i = 0, e = OverloadedMethods.size(); i != e; ++i) {
7523 CXXMethodDecl *overloadedMD = OverloadedMethods[i];
7524 PartialDiagnostic PD = PDiag(
7525 diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
7526 HandleFunctionTypeMismatch(PD, MD->getType(), overloadedMD->getType());
7527 Diag(overloadedMD->getLocation(), PD);
7531 /// \brief Diagnose methods which overload virtual methods in a base class
7532 /// without overriding any.
7533 void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
7534 if (MD->isInvalidDecl())
7537 if (Diags.isIgnored(diag::warn_overloaded_virtual, MD->getLocation()))
7540 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
7541 FindHiddenVirtualMethods(MD, OverloadedMethods);
7542 if (!OverloadedMethods.empty()) {
7543 Diag(MD->getLocation(), diag::warn_overloaded_virtual)
7544 << MD << (OverloadedMethods.size() > 1);
7546 NoteHiddenVirtualMethods(MD, OverloadedMethods);
7550 void Sema::ActOnFinishCXXMemberSpecification(Scope* S, SourceLocation RLoc,
7552 SourceLocation LBrac,
7553 SourceLocation RBrac,
7554 AttributeList *AttrList) {
7558 AdjustDeclIfTemplate(TagDecl);
7560 for (const AttributeList* l = AttrList; l; l = l->getNext()) {
7561 if (l->getKind() != AttributeList::AT_Visibility)
7564 Diag(l->getLoc(), diag::warn_attribute_after_definition_ignored) <<
7568 ActOnFields(S, RLoc, TagDecl, llvm::makeArrayRef(
7569 // strict aliasing violation!
7570 reinterpret_cast<Decl**>(FieldCollector->getCurFields()),
7571 FieldCollector->getCurNumFields()), LBrac, RBrac, AttrList);
7573 CheckCompletedCXXClass(dyn_cast_or_null<CXXRecordDecl>(TagDecl));
7576 /// AddImplicitlyDeclaredMembersToClass - Adds any implicitly-declared
7577 /// special functions, such as the default constructor, copy
7578 /// constructor, or destructor, to the given C++ class (C++
7579 /// [special]p1). This routine can only be executed just before the
7580 /// definition of the class is complete.
7581 void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
7582 if (ClassDecl->needsImplicitDefaultConstructor()) {
7583 ++ASTContext::NumImplicitDefaultConstructors;
7585 if (ClassDecl->hasInheritedConstructor())
7586 DeclareImplicitDefaultConstructor(ClassDecl);
7589 if (ClassDecl->needsImplicitCopyConstructor()) {
7590 ++ASTContext::NumImplicitCopyConstructors;
7592 // If the properties or semantics of the copy constructor couldn't be
7593 // determined while the class was being declared, force a declaration
7595 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
7596 ClassDecl->hasInheritedConstructor())
7597 DeclareImplicitCopyConstructor(ClassDecl);
7598 // For the MS ABI we need to know whether the copy ctor is deleted. A
7599 // prerequisite for deleting the implicit copy ctor is that the class has a
7600 // move ctor or move assignment that is either user-declared or whose
7601 // semantics are inherited from a subobject. FIXME: We should provide a more
7602 // direct way for CodeGen to ask whether the constructor was deleted.
7603 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
7604 (ClassDecl->hasUserDeclaredMoveConstructor() ||
7605 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7606 ClassDecl->hasUserDeclaredMoveAssignment() ||
7607 ClassDecl->needsOverloadResolutionForMoveAssignment()))
7608 DeclareImplicitCopyConstructor(ClassDecl);
7611 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveConstructor()) {
7612 ++ASTContext::NumImplicitMoveConstructors;
7614 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
7615 ClassDecl->hasInheritedConstructor())
7616 DeclareImplicitMoveConstructor(ClassDecl);
7619 if (ClassDecl->needsImplicitCopyAssignment()) {
7620 ++ASTContext::NumImplicitCopyAssignmentOperators;
7622 // If we have a dynamic class, then the copy assignment operator may be
7623 // virtual, so we have to declare it immediately. This ensures that, e.g.,
7624 // it shows up in the right place in the vtable and that we diagnose
7625 // problems with the implicit exception specification.
7626 if (ClassDecl->isDynamicClass() ||
7627 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
7628 ClassDecl->hasInheritedAssignment())
7629 DeclareImplicitCopyAssignment(ClassDecl);
7632 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
7633 ++ASTContext::NumImplicitMoveAssignmentOperators;
7635 // Likewise for the move assignment operator.
7636 if (ClassDecl->isDynamicClass() ||
7637 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
7638 ClassDecl->hasInheritedAssignment())
7639 DeclareImplicitMoveAssignment(ClassDecl);
7642 if (ClassDecl->needsImplicitDestructor()) {
7643 ++ASTContext::NumImplicitDestructors;
7645 // If we have a dynamic class, then the destructor may be virtual, so we
7646 // have to declare the destructor immediately. This ensures that, e.g., it
7647 // shows up in the right place in the vtable and that we diagnose problems
7648 // with the implicit exception specification.
7649 if (ClassDecl->isDynamicClass() ||
7650 ClassDecl->needsOverloadResolutionForDestructor())
7651 DeclareImplicitDestructor(ClassDecl);
7655 unsigned Sema::ActOnReenterTemplateScope(Scope *S, Decl *D) {
7659 // The order of template parameters is not important here. All names
7660 // get added to the same scope.
7661 SmallVector<TemplateParameterList *, 4> ParameterLists;
7663 if (TemplateDecl *TD = dyn_cast<TemplateDecl>(D))
7664 D = TD->getTemplatedDecl();
7666 if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(D))
7667 ParameterLists.push_back(PSD->getTemplateParameters());
7669 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(D)) {
7670 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
7671 ParameterLists.push_back(DD->getTemplateParameterList(i));
7673 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
7674 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
7675 ParameterLists.push_back(FTD->getTemplateParameters());
7679 if (TagDecl *TD = dyn_cast<TagDecl>(D)) {
7680 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
7681 ParameterLists.push_back(TD->getTemplateParameterList(i));
7683 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(TD)) {
7684 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
7685 ParameterLists.push_back(CTD->getTemplateParameters());
7690 for (TemplateParameterList *Params : ParameterLists) {
7691 if (Params->size() > 0)
7692 // Ignore explicit specializations; they don't contribute to the template
7695 for (NamedDecl *Param : *Params) {
7696 if (Param->getDeclName()) {
7698 IdResolver.AddDecl(Param);
7706 void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7707 if (!RecordD) return;
7708 AdjustDeclIfTemplate(RecordD);
7709 CXXRecordDecl *Record = cast<CXXRecordDecl>(RecordD);
7710 PushDeclContext(S, Record);
7713 void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
7714 if (!RecordD) return;
7718 /// This is used to implement the constant expression evaluation part of the
7719 /// attribute enable_if extension. There is nothing in standard C++ which would
7720 /// require reentering parameters.
7721 void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
7726 if (Param->getDeclName())
7727 IdResolver.AddDecl(Param);
7730 /// ActOnStartDelayedCXXMethodDeclaration - We have completed
7731 /// parsing a top-level (non-nested) C++ class, and we are now
7732 /// parsing those parts of the given Method declaration that could
7733 /// not be parsed earlier (C++ [class.mem]p2), such as default
7734 /// arguments. This action should enter the scope of the given
7735 /// Method declaration as if we had just parsed the qualified method
7736 /// name. However, it should not bring the parameters into scope;
7737 /// that will be performed by ActOnDelayedCXXMethodParameter.
7738 void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7741 /// ActOnDelayedCXXMethodParameter - We've already started a delayed
7742 /// C++ method declaration. We're (re-)introducing the given
7743 /// function parameter into scope for use in parsing later parts of
7744 /// the method declaration. For example, we could see an
7745 /// ActOnParamDefaultArgument event for this parameter.
7746 void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
7750 ParmVarDecl *Param = cast<ParmVarDecl>(ParamD);
7752 // If this parameter has an unparsed default argument, clear it out
7753 // to make way for the parsed default argument.
7754 if (Param->hasUnparsedDefaultArg())
7755 Param->setDefaultArg(nullptr);
7758 if (Param->getDeclName())
7759 IdResolver.AddDecl(Param);
7762 /// ActOnFinishDelayedCXXMethodDeclaration - We have finished
7763 /// processing the delayed method declaration for Method. The method
7764 /// declaration is now considered finished. There may be a separate
7765 /// ActOnStartOfFunctionDef action later (not necessarily
7766 /// immediately!) for this method, if it was also defined inside the
7768 void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
7772 AdjustDeclIfTemplate(MethodD);
7774 FunctionDecl *Method = cast<FunctionDecl>(MethodD);
7776 // Now that we have our default arguments, check the constructor
7777 // again. It could produce additional diagnostics or affect whether
7778 // the class has implicitly-declared destructors, among other
7780 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Method))
7781 CheckConstructor(Constructor);
7783 // Check the default arguments, which we may have added.
7784 if (!Method->isInvalidDecl())
7785 CheckCXXDefaultArguments(Method);
7788 /// CheckConstructorDeclarator - Called by ActOnDeclarator to check
7789 /// the well-formedness of the constructor declarator @p D with type @p
7790 /// R. If there are any errors in the declarator, this routine will
7791 /// emit diagnostics and set the invalid bit to true. In any case, the type
7792 /// will be updated to reflect a well-formed type for the constructor and
7794 QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
7796 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
7798 // C++ [class.ctor]p3:
7799 // A constructor shall not be virtual (10.3) or static (9.4). A
7800 // constructor can be invoked for a const, volatile or const
7801 // volatile object. A constructor shall not be declared const,
7802 // volatile, or const volatile (9.3.2).
7804 if (!D.isInvalidType())
7805 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7806 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
7807 << SourceRange(D.getIdentifierLoc());
7810 if (SC == SC_Static) {
7811 if (!D.isInvalidType())
7812 Diag(D.getIdentifierLoc(), diag::err_constructor_cannot_be)
7813 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7814 << SourceRange(D.getIdentifierLoc());
7819 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
7820 diagnoseIgnoredQualifiers(
7821 diag::err_constructor_return_type, TypeQuals, SourceLocation(),
7822 D.getDeclSpec().getConstSpecLoc(), D.getDeclSpec().getVolatileSpecLoc(),
7823 D.getDeclSpec().getRestrictSpecLoc(),
7824 D.getDeclSpec().getAtomicSpecLoc());
7828 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
7829 if (FTI.TypeQuals != 0) {
7830 if (FTI.TypeQuals & Qualifiers::Const)
7831 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7832 << "const" << SourceRange(D.getIdentifierLoc());
7833 if (FTI.TypeQuals & Qualifiers::Volatile)
7834 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7835 << "volatile" << SourceRange(D.getIdentifierLoc());
7836 if (FTI.TypeQuals & Qualifiers::Restrict)
7837 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_constructor)
7838 << "restrict" << SourceRange(D.getIdentifierLoc());
7842 // C++0x [class.ctor]p4:
7843 // A constructor shall not be declared with a ref-qualifier.
7844 if (FTI.hasRefQualifier()) {
7845 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_constructor)
7846 << FTI.RefQualifierIsLValueRef
7847 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
7851 // Rebuild the function type "R" without any type qualifiers (in
7852 // case any of the errors above fired) and with "void" as the
7853 // return type, since constructors don't have return types.
7854 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
7855 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
7858 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
7860 EPI.RefQualifier = RQ_None;
7862 return Context.getFunctionType(Context.VoidTy, Proto->getParamTypes(), EPI);
7865 /// CheckConstructor - Checks a fully-formed constructor for
7866 /// well-formedness, issuing any diagnostics required. Returns true if
7867 /// the constructor declarator is invalid.
7868 void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
7869 CXXRecordDecl *ClassDecl
7870 = dyn_cast<CXXRecordDecl>(Constructor->getDeclContext());
7872 return Constructor->setInvalidDecl();
7874 // C++ [class.copy]p3:
7875 // A declaration of a constructor for a class X is ill-formed if
7876 // its first parameter is of type (optionally cv-qualified) X and
7877 // either there are no other parameters or else all other
7878 // parameters have default arguments.
7879 if (!Constructor->isInvalidDecl() &&
7880 ((Constructor->getNumParams() == 1) ||
7881 (Constructor->getNumParams() > 1 &&
7882 Constructor->getParamDecl(1)->hasDefaultArg())) &&
7883 Constructor->getTemplateSpecializationKind()
7884 != TSK_ImplicitInstantiation) {
7885 QualType ParamType = Constructor->getParamDecl(0)->getType();
7886 QualType ClassTy = Context.getTagDeclType(ClassDecl);
7887 if (Context.getCanonicalType(ParamType).getUnqualifiedType() == ClassTy) {
7888 SourceLocation ParamLoc = Constructor->getParamDecl(0)->getLocation();
7889 const char *ConstRef
7890 = Constructor->getParamDecl(0)->getIdentifier() ? "const &"
7892 Diag(ParamLoc, diag::err_constructor_byvalue_arg)
7893 << FixItHint::CreateInsertion(ParamLoc, ConstRef);
7895 // FIXME: Rather that making the constructor invalid, we should endeavor
7897 Constructor->setInvalidDecl();
7902 /// CheckDestructor - Checks a fully-formed destructor definition for
7903 /// well-formedness, issuing any diagnostics required. Returns true
7905 bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
7906 CXXRecordDecl *RD = Destructor->getParent();
7908 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
7911 if (!Destructor->isImplicit())
7912 Loc = Destructor->getLocation();
7914 Loc = RD->getLocation();
7916 // If we have a virtual destructor, look up the deallocation function
7917 if (FunctionDecl *OperatorDelete =
7918 FindDeallocationFunctionForDestructor(Loc, RD)) {
7919 Expr *ThisArg = nullptr;
7921 // If the notional 'delete this' expression requires a non-trivial
7922 // conversion from 'this' to the type of a destroying operator delete's
7923 // first parameter, perform that conversion now.
7924 if (OperatorDelete->isDestroyingOperatorDelete()) {
7925 QualType ParamType = OperatorDelete->getParamDecl(0)->getType();
7926 if (!declaresSameEntity(ParamType->getAsCXXRecordDecl(), RD)) {
7927 // C++ [class.dtor]p13:
7928 // ... as if for the expression 'delete this' appearing in a
7929 // non-virtual destructor of the destructor's class.
7930 ContextRAII SwitchContext(*this, Destructor);
7932 ActOnCXXThis(OperatorDelete->getParamDecl(0)->getLocation());
7933 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
7934 This = PerformImplicitConversion(This.get(), ParamType, AA_Passing);
7935 if (This.isInvalid()) {
7936 // FIXME: Register this as a context note so that it comes out
7937 // in the right order.
7938 Diag(Loc, diag::note_implicit_delete_this_in_destructor_here);
7941 ThisArg = This.get();
7945 MarkFunctionReferenced(Loc, OperatorDelete);
7946 Destructor->setOperatorDelete(OperatorDelete, ThisArg);
7953 /// CheckDestructorDeclarator - Called by ActOnDeclarator to check
7954 /// the well-formednes of the destructor declarator @p D with type @p
7955 /// R. If there are any errors in the declarator, this routine will
7956 /// emit diagnostics and set the declarator to invalid. Even if this happens,
7957 /// will be updated to reflect a well-formed type for the destructor and
7959 QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
7961 // C++ [class.dtor]p1:
7962 // [...] A typedef-name that names a class is a class-name
7963 // (7.1.3); however, a typedef-name that names a class shall not
7964 // be used as the identifier in the declarator for a destructor
7966 QualType DeclaratorType = GetTypeFromParser(D.getName().DestructorName);
7967 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
7968 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7969 << DeclaratorType << isa<TypeAliasDecl>(TT->getDecl());
7970 else if (const TemplateSpecializationType *TST =
7971 DeclaratorType->getAs<TemplateSpecializationType>())
7972 if (TST->isTypeAlias())
7973 Diag(D.getIdentifierLoc(), diag::err_destructor_typedef_name)
7974 << DeclaratorType << 1;
7976 // C++ [class.dtor]p2:
7977 // A destructor is used to destroy objects of its class type. A
7978 // destructor takes no parameters, and no return type can be
7979 // specified for it (not even void). The address of a destructor
7980 // shall not be taken. A destructor shall not be static. A
7981 // destructor can be invoked for a const, volatile or const
7982 // volatile object. A destructor shall not be declared const,
7983 // volatile or const volatile (9.3.2).
7984 if (SC == SC_Static) {
7985 if (!D.isInvalidType())
7986 Diag(D.getIdentifierLoc(), diag::err_destructor_cannot_be)
7987 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
7988 << SourceRange(D.getIdentifierLoc())
7989 << FixItHint::CreateRemoval(D.getDeclSpec().getStorageClassSpecLoc());
7993 if (!D.isInvalidType()) {
7994 // Destructors don't have return types, but the parser will
7995 // happily parse something like:
8001 // The return type will be eliminated later.
8002 if (D.getDeclSpec().hasTypeSpecifier())
8003 Diag(D.getIdentifierLoc(), diag::err_destructor_return_type)
8004 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8005 << SourceRange(D.getIdentifierLoc());
8006 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
8007 diagnoseIgnoredQualifiers(diag::err_destructor_return_type, TypeQuals,
8009 D.getDeclSpec().getConstSpecLoc(),
8010 D.getDeclSpec().getVolatileSpecLoc(),
8011 D.getDeclSpec().getRestrictSpecLoc(),
8012 D.getDeclSpec().getAtomicSpecLoc());
8017 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
8018 if (FTI.TypeQuals != 0 && !D.isInvalidType()) {
8019 if (FTI.TypeQuals & Qualifiers::Const)
8020 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8021 << "const" << SourceRange(D.getIdentifierLoc());
8022 if (FTI.TypeQuals & Qualifiers::Volatile)
8023 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8024 << "volatile" << SourceRange(D.getIdentifierLoc());
8025 if (FTI.TypeQuals & Qualifiers::Restrict)
8026 Diag(D.getIdentifierLoc(), diag::err_invalid_qualified_destructor)
8027 << "restrict" << SourceRange(D.getIdentifierLoc());
8031 // C++0x [class.dtor]p2:
8032 // A destructor shall not be declared with a ref-qualifier.
8033 if (FTI.hasRefQualifier()) {
8034 Diag(FTI.getRefQualifierLoc(), diag::err_ref_qualifier_destructor)
8035 << FTI.RefQualifierIsLValueRef
8036 << FixItHint::CreateRemoval(FTI.getRefQualifierLoc());
8040 // Make sure we don't have any parameters.
8041 if (FTIHasNonVoidParameters(FTI)) {
8042 Diag(D.getIdentifierLoc(), diag::err_destructor_with_params);
8044 // Delete the parameters.
8049 // Make sure the destructor isn't variadic.
8050 if (FTI.isVariadic) {
8051 Diag(D.getIdentifierLoc(), diag::err_destructor_variadic);
8055 // Rebuild the function type "R" without any type qualifiers or
8056 // parameters (in case any of the errors above fired) and with
8057 // "void" as the return type, since destructors don't have return
8059 if (!D.isInvalidType())
8062 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8063 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
8064 EPI.Variadic = false;
8066 EPI.RefQualifier = RQ_None;
8067 return Context.getFunctionType(Context.VoidTy, None, EPI);
8070 static void extendLeft(SourceRange &R, SourceRange Before) {
8071 if (Before.isInvalid())
8073 R.setBegin(Before.getBegin());
8074 if (R.getEnd().isInvalid())
8075 R.setEnd(Before.getEnd());
8078 static void extendRight(SourceRange &R, SourceRange After) {
8079 if (After.isInvalid())
8081 if (R.getBegin().isInvalid())
8082 R.setBegin(After.getBegin());
8083 R.setEnd(After.getEnd());
8086 /// CheckConversionDeclarator - Called by ActOnDeclarator to check the
8087 /// well-formednes of the conversion function declarator @p D with
8088 /// type @p R. If there are any errors in the declarator, this routine
8089 /// will emit diagnostics and return true. Otherwise, it will return
8090 /// false. Either way, the type @p R will be updated to reflect a
8091 /// well-formed type for the conversion operator.
8092 void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
8094 // C++ [class.conv.fct]p1:
8095 // Neither parameter types nor return type can be specified. The
8096 // type of a conversion function (8.3.5) is "function taking no
8097 // parameter returning conversion-type-id."
8098 if (SC == SC_Static) {
8099 if (!D.isInvalidType())
8100 Diag(D.getIdentifierLoc(), diag::err_conv_function_not_member)
8101 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
8102 << D.getName().getSourceRange();
8107 TypeSourceInfo *ConvTSI = nullptr;
8109 GetTypeFromParser(D.getName().ConversionFunctionId, &ConvTSI);
8111 if (D.getDeclSpec().hasTypeSpecifier() && !D.isInvalidType()) {
8112 // Conversion functions don't have return types, but the parser will
8113 // happily parse something like:
8116 // float operator bool();
8119 // The return type will be changed later anyway.
8120 Diag(D.getIdentifierLoc(), diag::err_conv_function_return_type)
8121 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
8122 << SourceRange(D.getIdentifierLoc());
8126 const FunctionProtoType *Proto = R->getAs<FunctionProtoType>();
8128 // Make sure we don't have any parameters.
8129 if (Proto->getNumParams() > 0) {
8130 Diag(D.getIdentifierLoc(), diag::err_conv_function_with_params);
8132 // Delete the parameters.
8133 D.getFunctionTypeInfo().freeParams();
8135 } else if (Proto->isVariadic()) {
8136 Diag(D.getIdentifierLoc(), diag::err_conv_function_variadic);
8140 // Diagnose "&operator bool()" and other such nonsense. This
8141 // is actually a gcc extension which we don't support.
8142 if (Proto->getReturnType() != ConvType) {
8143 bool NeedsTypedef = false;
8144 SourceRange Before, After;
8146 // Walk the chunks and extract information on them for our diagnostic.
8147 bool PastFunctionChunk = false;
8148 for (auto &Chunk : D.type_objects()) {
8149 switch (Chunk.Kind) {
8150 case DeclaratorChunk::Function:
8151 if (!PastFunctionChunk) {
8152 if (Chunk.Fun.HasTrailingReturnType) {
8153 TypeSourceInfo *TRT = nullptr;
8154 GetTypeFromParser(Chunk.Fun.getTrailingReturnType(), &TRT);
8155 if (TRT) extendRight(After, TRT->getTypeLoc().getSourceRange());
8157 PastFunctionChunk = true;
8161 case DeclaratorChunk::Array:
8162 NeedsTypedef = true;
8163 extendRight(After, Chunk.getSourceRange());
8166 case DeclaratorChunk::Pointer:
8167 case DeclaratorChunk::BlockPointer:
8168 case DeclaratorChunk::Reference:
8169 case DeclaratorChunk::MemberPointer:
8170 case DeclaratorChunk::Pipe:
8171 extendLeft(Before, Chunk.getSourceRange());
8174 case DeclaratorChunk::Paren:
8175 extendLeft(Before, Chunk.Loc);
8176 extendRight(After, Chunk.EndLoc);
8181 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
8182 After.isValid() ? After.getBegin() :
8183 D.getIdentifierLoc();
8184 auto &&DB = Diag(Loc, diag::err_conv_function_with_complex_decl);
8185 DB << Before << After;
8187 if (!NeedsTypedef) {
8188 DB << /*don't need a typedef*/0;
8190 // If we can provide a correct fix-it hint, do so.
8191 if (After.isInvalid() && ConvTSI) {
8192 SourceLocation InsertLoc =
8193 getLocForEndOfToken(ConvTSI->getTypeLoc().getLocEnd());
8194 DB << FixItHint::CreateInsertion(InsertLoc, " ")
8195 << FixItHint::CreateInsertionFromRange(
8196 InsertLoc, CharSourceRange::getTokenRange(Before))
8197 << FixItHint::CreateRemoval(Before);
8199 } else if (!Proto->getReturnType()->isDependentType()) {
8200 DB << /*typedef*/1 << Proto->getReturnType();
8201 } else if (getLangOpts().CPlusPlus11) {
8202 DB << /*alias template*/2 << Proto->getReturnType();
8204 DB << /*might not be fixable*/3;
8207 // Recover by incorporating the other type chunks into the result type.
8208 // Note, this does *not* change the name of the function. This is compatible
8209 // with the GCC extension:
8210 // struct S { &operator int(); } s;
8211 // int &r = s.operator int(); // ok in GCC
8212 // S::operator int&() {} // error in GCC, function name is 'operator int'.
8213 ConvType = Proto->getReturnType();
8216 // C++ [class.conv.fct]p4:
8217 // The conversion-type-id shall not represent a function type nor
8219 if (ConvType->isArrayType()) {
8220 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_array);
8221 ConvType = Context.getPointerType(ConvType);
8223 } else if (ConvType->isFunctionType()) {
8224 Diag(D.getIdentifierLoc(), diag::err_conv_function_to_function);
8225 ConvType = Context.getPointerType(ConvType);
8229 // Rebuild the function type "R" without any parameters (in case any
8230 // of the errors above fired) and with the conversion type as the
8232 if (D.isInvalidType())
8233 R = Context.getFunctionType(ConvType, None, Proto->getExtProtoInfo());
8235 // C++0x explicit conversion operators.
8236 if (D.getDeclSpec().isExplicitSpecified())
8237 Diag(D.getDeclSpec().getExplicitSpecLoc(),
8238 getLangOpts().CPlusPlus11 ?
8239 diag::warn_cxx98_compat_explicit_conversion_functions :
8240 diag::ext_explicit_conversion_functions)
8241 << SourceRange(D.getDeclSpec().getExplicitSpecLoc());
8244 /// ActOnConversionDeclarator - Called by ActOnDeclarator to complete
8245 /// the declaration of the given C++ conversion function. This routine
8246 /// is responsible for recording the conversion function in the C++
8247 /// class, if possible.
8248 Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
8249 assert(Conversion && "Expected to receive a conversion function declaration");
8251 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Conversion->getDeclContext());
8253 // Make sure we aren't redeclaring the conversion function.
8254 QualType ConvType = Context.getCanonicalType(Conversion->getConversionType());
8256 // C++ [class.conv.fct]p1:
8257 // [...] A conversion function is never used to convert a
8258 // (possibly cv-qualified) object to the (possibly cv-qualified)
8259 // same object type (or a reference to it), to a (possibly
8260 // cv-qualified) base class of that type (or a reference to it),
8261 // or to (possibly cv-qualified) void.
8262 // FIXME: Suppress this warning if the conversion function ends up being a
8263 // virtual function that overrides a virtual function in a base class.
8265 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
8266 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
8267 ConvType = ConvTypeRef->getPointeeType();
8268 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
8269 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
8270 /* Suppress diagnostics for instantiations. */;
8271 else if (ConvType->isRecordType()) {
8272 ConvType = Context.getCanonicalType(ConvType).getUnqualifiedType();
8273 if (ConvType == ClassType)
8274 Diag(Conversion->getLocation(), diag::warn_conv_to_self_not_used)
8276 else if (IsDerivedFrom(Conversion->getLocation(), ClassType, ConvType))
8277 Diag(Conversion->getLocation(), diag::warn_conv_to_base_not_used)
8278 << ClassType << ConvType;
8279 } else if (ConvType->isVoidType()) {
8280 Diag(Conversion->getLocation(), diag::warn_conv_to_void_not_used)
8281 << ClassType << ConvType;
8284 if (FunctionTemplateDecl *ConversionTemplate
8285 = Conversion->getDescribedFunctionTemplate())
8286 return ConversionTemplate;
8292 /// Utility class to accumulate and print a diagnostic listing the invalid
8293 /// specifier(s) on a declaration.
8294 struct BadSpecifierDiagnoser {
8295 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
8296 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
8297 ~BadSpecifierDiagnoser() {
8298 Diagnostic << Specifiers;
8301 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
8302 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
8304 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
8305 return check(SpecLoc,
8306 DeclSpec::getSpecifierName(Spec, S.getPrintingPolicy()));
8308 void check(SourceLocation SpecLoc, const char *Spec) {
8309 if (SpecLoc.isInvalid()) return;
8310 Diagnostic << SourceRange(SpecLoc, SpecLoc);
8311 if (!Specifiers.empty()) Specifiers += " ";
8316 Sema::SemaDiagnosticBuilder Diagnostic;
8317 std::string Specifiers;
8321 /// Check the validity of a declarator that we parsed for a deduction-guide.
8322 /// These aren't actually declarators in the grammar, so we need to check that
8323 /// the user didn't specify any pieces that are not part of the deduction-guide
8325 void Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
8327 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
8328 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
8329 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
8331 // C++ [temp.deduct.guide]p3:
8332 // A deduction-gide shall be declared in the same scope as the
8333 // corresponding class template.
8334 if (!CurContext->getRedeclContext()->Equals(
8335 GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
8336 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_wrong_scope)
8337 << GuidedTemplateDecl;
8338 Diag(GuidedTemplateDecl->getLocation(), diag::note_template_decl_here);
8341 auto &DS = D.getMutableDeclSpec();
8342 // We leave 'friend' and 'virtual' to be rejected in the normal way.
8343 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
8344 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
8345 DS.isNoreturnSpecified() || DS.isConstexprSpecified()) {
8346 BadSpecifierDiagnoser Diagnoser(
8347 *this, D.getIdentifierLoc(),
8348 diag::err_deduction_guide_invalid_specifier);
8350 Diagnoser.check(DS.getStorageClassSpecLoc(), DS.getStorageClassSpec());
8351 DS.ClearStorageClassSpecs();
8354 // 'explicit' is permitted.
8355 Diagnoser.check(DS.getInlineSpecLoc(), "inline");
8356 Diagnoser.check(DS.getNoreturnSpecLoc(), "_Noreturn");
8357 Diagnoser.check(DS.getConstexprSpecLoc(), "constexpr");
8358 DS.ClearConstexprSpec();
8360 Diagnoser.check(DS.getConstSpecLoc(), "const");
8361 Diagnoser.check(DS.getRestrictSpecLoc(), "__restrict");
8362 Diagnoser.check(DS.getVolatileSpecLoc(), "volatile");
8363 Diagnoser.check(DS.getAtomicSpecLoc(), "_Atomic");
8364 Diagnoser.check(DS.getUnalignedSpecLoc(), "__unaligned");
8365 DS.ClearTypeQualifiers();
8367 Diagnoser.check(DS.getTypeSpecComplexLoc(), DS.getTypeSpecComplex());
8368 Diagnoser.check(DS.getTypeSpecSignLoc(), DS.getTypeSpecSign());
8369 Diagnoser.check(DS.getTypeSpecWidthLoc(), DS.getTypeSpecWidth());
8370 Diagnoser.check(DS.getTypeSpecTypeLoc(), DS.getTypeSpecType());
8371 DS.ClearTypeSpecType();
8374 if (D.isInvalidType())
8377 // Check the declarator is simple enough.
8378 bool FoundFunction = false;
8379 for (const DeclaratorChunk &Chunk : llvm::reverse(D.type_objects())) {
8380 if (Chunk.Kind == DeclaratorChunk::Paren)
8382 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
8383 Diag(D.getDeclSpec().getLocStart(),
8384 diag::err_deduction_guide_with_complex_decl)
8385 << D.getSourceRange();
8388 if (!Chunk.Fun.hasTrailingReturnType()) {
8389 Diag(D.getName().getLocStart(),
8390 diag::err_deduction_guide_no_trailing_return_type);
8394 // Check that the return type is written as a specialization of
8395 // the template specified as the deduction-guide's name.
8396 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
8397 TypeSourceInfo *TSI = nullptr;
8398 QualType RetTy = GetTypeFromParser(TrailingReturnType, &TSI);
8399 assert(TSI && "deduction guide has valid type but invalid return type?");
8400 bool AcceptableReturnType = false;
8401 bool MightInstantiateToSpecialization = false;
8403 TSI->getTypeLoc().getAs<TemplateSpecializationTypeLoc>()) {
8404 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
8405 bool TemplateMatches =
8406 Context.hasSameTemplateName(SpecifiedName, GuidedTemplate);
8407 if (SpecifiedName.getKind() == TemplateName::Template && TemplateMatches)
8408 AcceptableReturnType = true;
8410 // This could still instantiate to the right type, unless we know it
8411 // names the wrong class template.
8412 auto *TD = SpecifiedName.getAsTemplateDecl();
8413 MightInstantiateToSpecialization = !(TD && isa<ClassTemplateDecl>(TD) &&
8416 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
8417 MightInstantiateToSpecialization = true;
8420 if (!AcceptableReturnType) {
8421 Diag(TSI->getTypeLoc().getLocStart(),
8422 diag::err_deduction_guide_bad_trailing_return_type)
8423 << GuidedTemplate << TSI->getType() << MightInstantiateToSpecialization
8424 << TSI->getTypeLoc().getSourceRange();
8427 // Keep going to check that we don't have any inner declarator pieces (we
8428 // could still have a function returning a pointer to a function).
8429 FoundFunction = true;
8432 if (D.isFunctionDefinition())
8433 Diag(D.getIdentifierLoc(), diag::err_deduction_guide_defines_function);
8436 //===----------------------------------------------------------------------===//
8437 // Namespace Handling
8438 //===----------------------------------------------------------------------===//
8440 /// \brief Diagnose a mismatch in 'inline' qualifiers when a namespace is
8442 static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
8444 IdentifierInfo *II, bool *IsInline,
8445 NamespaceDecl *PrevNS) {
8446 assert(*IsInline != PrevNS->isInline());
8448 // HACK: Work around a bug in libstdc++4.6's <atomic>, where
8449 // std::__atomic[0,1,2] are defined as non-inline namespaces, then reopened as
8450 // inline namespaces, with the intention of bringing names into namespace std.
8452 // We support this just well enough to get that case working; this is not
8453 // sufficient to support reopening namespaces as inline in general.
8454 if (*IsInline && II && II->getName().startswith("__atomic") &&
8455 S.getSourceManager().isInSystemHeader(Loc)) {
8456 // Mark all prior declarations of the namespace as inline.
8457 for (NamespaceDecl *NS = PrevNS->getMostRecentDecl(); NS;
8458 NS = NS->getPreviousDecl())
8459 NS->setInline(*IsInline);
8460 // Patch up the lookup table for the containing namespace. This isn't really
8461 // correct, but it's good enough for this particular case.
8462 for (auto *I : PrevNS->decls())
8463 if (auto *ND = dyn_cast<NamedDecl>(I))
8464 PrevNS->getParent()->makeDeclVisibleInContext(ND);
8468 if (PrevNS->isInline())
8469 // The user probably just forgot the 'inline', so suggest that it
8471 S.Diag(Loc, diag::warn_inline_namespace_reopened_noninline)
8472 << FixItHint::CreateInsertion(KeywordLoc, "inline ");
8474 S.Diag(Loc, diag::err_inline_namespace_mismatch);
8476 S.Diag(PrevNS->getLocation(), diag::note_previous_definition);
8477 *IsInline = PrevNS->isInline();
8480 /// ActOnStartNamespaceDef - This is called at the start of a namespace
8482 Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
8483 SourceLocation InlineLoc,
8484 SourceLocation NamespaceLoc,
8485 SourceLocation IdentLoc,
8487 SourceLocation LBrace,
8488 AttributeList *AttrList,
8489 UsingDirectiveDecl *&UD) {
8490 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
8491 // For anonymous namespace, take the location of the left brace.
8492 SourceLocation Loc = II ? IdentLoc : LBrace;
8493 bool IsInline = InlineLoc.isValid();
8494 bool IsInvalid = false;
8496 bool AddToKnown = false;
8497 Scope *DeclRegionScope = NamespcScope->getParent();
8499 NamespaceDecl *PrevNS = nullptr;
8501 // C++ [namespace.def]p2:
8502 // The identifier in an original-namespace-definition shall not
8503 // have been previously defined in the declarative region in
8504 // which the original-namespace-definition appears. The
8505 // identifier in an original-namespace-definition is the name of
8506 // the namespace. Subsequently in that declarative region, it is
8507 // treated as an original-namespace-name.
8509 // Since namespace names are unique in their scope, and we don't
8510 // look through using directives, just look for any ordinary names
8511 // as if by qualified name lookup.
8512 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
8513 ForExternalRedeclaration);
8514 LookupQualifiedName(R, CurContext->getRedeclContext());
8515 NamedDecl *PrevDecl =
8516 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
8517 PrevNS = dyn_cast_or_null<NamespaceDecl>(PrevDecl);
8520 // This is an extended namespace definition.
8521 if (IsInline != PrevNS->isInline())
8522 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, Loc, II,
8524 } else if (PrevDecl) {
8525 // This is an invalid name redefinition.
8526 Diag(Loc, diag::err_redefinition_different_kind)
8528 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
8530 // Continue on to push Namespc as current DeclContext and return it.
8531 } else if (II->isStr("std") &&
8532 CurContext->getRedeclContext()->isTranslationUnit()) {
8533 // This is the first "real" definition of the namespace "std", so update
8534 // our cache of the "std" namespace to point at this definition.
8535 PrevNS = getStdNamespace();
8537 AddToKnown = !IsInline;
8539 // We've seen this namespace for the first time.
8540 AddToKnown = !IsInline;
8543 // Anonymous namespaces.
8545 // Determine whether the parent already has an anonymous namespace.
8546 DeclContext *Parent = CurContext->getRedeclContext();
8547 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8548 PrevNS = TU->getAnonymousNamespace();
8550 NamespaceDecl *ND = cast<NamespaceDecl>(Parent);
8551 PrevNS = ND->getAnonymousNamespace();
8554 if (PrevNS && IsInline != PrevNS->isInline())
8555 DiagnoseNamespaceInlineMismatch(*this, NamespaceLoc, NamespaceLoc, II,
8559 NamespaceDecl *Namespc = NamespaceDecl::Create(Context, CurContext, IsInline,
8560 StartLoc, Loc, II, PrevNS);
8562 Namespc->setInvalidDecl();
8564 ProcessDeclAttributeList(DeclRegionScope, Namespc, AttrList);
8565 AddPragmaAttributes(DeclRegionScope, Namespc);
8567 // FIXME: Should we be merging attributes?
8568 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
8569 PushNamespaceVisibilityAttr(Attr, Loc);
8572 StdNamespace = Namespc;
8574 KnownNamespaces[Namespc] = false;
8577 PushOnScopeChains(Namespc, DeclRegionScope);
8579 // Link the anonymous namespace into its parent.
8580 DeclContext *Parent = CurContext->getRedeclContext();
8581 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Parent)) {
8582 TU->setAnonymousNamespace(Namespc);
8584 cast<NamespaceDecl>(Parent)->setAnonymousNamespace(Namespc);
8587 CurContext->addDecl(Namespc);
8589 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
8590 // behaves as if it were replaced by
8591 // namespace unique { /* empty body */ }
8592 // using namespace unique;
8593 // namespace unique { namespace-body }
8594 // where all occurrences of 'unique' in a translation unit are
8595 // replaced by the same identifier and this identifier differs
8596 // from all other identifiers in the entire program.
8598 // We just create the namespace with an empty name and then add an
8599 // implicit using declaration, just like the standard suggests.
8601 // CodeGen enforces the "universally unique" aspect by giving all
8602 // declarations semantically contained within an anonymous
8603 // namespace internal linkage.
8606 UD = UsingDirectiveDecl::Create(Context, Parent,
8607 /* 'using' */ LBrace,
8608 /* 'namespace' */ SourceLocation(),
8609 /* qualifier */ NestedNameSpecifierLoc(),
8610 /* identifier */ SourceLocation(),
8612 /* Ancestor */ Parent);
8614 Parent->addDecl(UD);
8618 ActOnDocumentableDecl(Namespc);
8620 // Although we could have an invalid decl (i.e. the namespace name is a
8621 // redefinition), push it as current DeclContext and try to continue parsing.
8622 // FIXME: We should be able to push Namespc here, so that the each DeclContext
8623 // for the namespace has the declarations that showed up in that particular
8624 // namespace definition.
8625 PushDeclContext(NamespcScope, Namespc);
8629 /// getNamespaceDecl - Returns the namespace a decl represents. If the decl
8630 /// is a namespace alias, returns the namespace it points to.
8631 static inline NamespaceDecl *getNamespaceDecl(NamedDecl *D) {
8632 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(D))
8633 return AD->getNamespace();
8634 return dyn_cast_or_null<NamespaceDecl>(D);
8637 /// ActOnFinishNamespaceDef - This callback is called after a namespace is
8638 /// exited. Decl is the DeclTy returned by ActOnStartNamespaceDef.
8639 void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
8640 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Dcl);
8641 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
8642 Namespc->setRBraceLoc(RBrace);
8644 if (Namespc->hasAttr<VisibilityAttr>())
8645 PopPragmaVisibility(true, RBrace);
8648 CXXRecordDecl *Sema::getStdBadAlloc() const {
8649 return cast_or_null<CXXRecordDecl>(
8650 StdBadAlloc.get(Context.getExternalSource()));
8653 EnumDecl *Sema::getStdAlignValT() const {
8654 return cast_or_null<EnumDecl>(StdAlignValT.get(Context.getExternalSource()));
8657 NamespaceDecl *Sema::getStdNamespace() const {
8658 return cast_or_null<NamespaceDecl>(
8659 StdNamespace.get(Context.getExternalSource()));
8662 NamespaceDecl *Sema::lookupStdExperimentalNamespace() {
8663 if (!StdExperimentalNamespaceCache) {
8664 if (auto Std = getStdNamespace()) {
8665 LookupResult Result(*this, &PP.getIdentifierTable().get("experimental"),
8666 SourceLocation(), LookupNamespaceName);
8667 if (!LookupQualifiedName(Result, Std) ||
8668 !(StdExperimentalNamespaceCache =
8669 Result.getAsSingle<NamespaceDecl>()))
8670 Result.suppressDiagnostics();
8673 return StdExperimentalNamespaceCache;
8676 /// \brief Retrieve the special "std" namespace, which may require us to
8677 /// implicitly define the namespace.
8678 NamespaceDecl *Sema::getOrCreateStdNamespace() {
8679 if (!StdNamespace) {
8680 // The "std" namespace has not yet been defined, so build one implicitly.
8681 StdNamespace = NamespaceDecl::Create(Context,
8682 Context.getTranslationUnitDecl(),
8684 SourceLocation(), SourceLocation(),
8685 &PP.getIdentifierTable().get("std"),
8686 /*PrevDecl=*/nullptr);
8687 getStdNamespace()->setImplicit(true);
8690 return getStdNamespace();
8693 bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
8694 assert(getLangOpts().CPlusPlus &&
8695 "Looking for std::initializer_list outside of C++.");
8697 // We're looking for implicit instantiations of
8698 // template <typename E> class std::initializer_list.
8700 if (!StdNamespace) // If we haven't seen namespace std yet, this can't be it.
8703 ClassTemplateDecl *Template = nullptr;
8704 const TemplateArgument *Arguments = nullptr;
8706 if (const RecordType *RT = Ty->getAs<RecordType>()) {
8708 ClassTemplateSpecializationDecl *Specialization =
8709 dyn_cast<ClassTemplateSpecializationDecl>(RT->getDecl());
8710 if (!Specialization)
8713 Template = Specialization->getSpecializedTemplate();
8714 Arguments = Specialization->getTemplateArgs().data();
8715 } else if (const TemplateSpecializationType *TST =
8716 Ty->getAs<TemplateSpecializationType>()) {
8717 Template = dyn_cast_or_null<ClassTemplateDecl>(
8718 TST->getTemplateName().getAsTemplateDecl());
8719 Arguments = TST->getArgs();
8724 if (!StdInitializerList) {
8725 // Haven't recognized std::initializer_list yet, maybe this is it.
8726 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
8727 if (TemplateClass->getIdentifier() !=
8728 &PP.getIdentifierTable().get("initializer_list") ||
8729 !getStdNamespace()->InEnclosingNamespaceSetOf(
8730 TemplateClass->getDeclContext()))
8732 // This is a template called std::initializer_list, but is it the right
8734 TemplateParameterList *Params = Template->getTemplateParameters();
8735 if (Params->getMinRequiredArguments() != 1)
8737 if (!isa<TemplateTypeParmDecl>(Params->getParam(0)))
8740 // It's the right template.
8741 StdInitializerList = Template;
8744 if (Template->getCanonicalDecl() != StdInitializerList->getCanonicalDecl())
8747 // This is an instance of std::initializer_list. Find the argument type.
8749 *Element = Arguments[0].getAsType();
8753 static ClassTemplateDecl *LookupStdInitializerList(Sema &S, SourceLocation Loc){
8754 NamespaceDecl *Std = S.getStdNamespace();
8756 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8760 LookupResult Result(S, &S.PP.getIdentifierTable().get("initializer_list"),
8761 Loc, Sema::LookupOrdinaryName);
8762 if (!S.LookupQualifiedName(Result, Std)) {
8763 S.Diag(Loc, diag::err_implied_std_initializer_list_not_found);
8766 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
8768 Result.suppressDiagnostics();
8769 // We found something weird. Complain about the first thing we found.
8770 NamedDecl *Found = *Result.begin();
8771 S.Diag(Found->getLocation(), diag::err_malformed_std_initializer_list);
8775 // We found some template called std::initializer_list. Now verify that it's
8777 TemplateParameterList *Params = Template->getTemplateParameters();
8778 if (Params->getMinRequiredArguments() != 1 ||
8779 !isa<TemplateTypeParmDecl>(Params->getParam(0))) {
8780 S.Diag(Template->getLocation(), diag::err_malformed_std_initializer_list);
8787 QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
8788 if (!StdInitializerList) {
8789 StdInitializerList = LookupStdInitializerList(*this, Loc);
8790 if (!StdInitializerList)
8794 TemplateArgumentListInfo Args(Loc, Loc);
8795 Args.addArgument(TemplateArgumentLoc(TemplateArgument(Element),
8796 Context.getTrivialTypeSourceInfo(Element,
8798 return Context.getCanonicalType(
8799 CheckTemplateIdType(TemplateName(StdInitializerList), Loc, Args));
8802 bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
8803 // C++ [dcl.init.list]p2:
8804 // A constructor is an initializer-list constructor if its first parameter
8805 // is of type std::initializer_list<E> or reference to possibly cv-qualified
8806 // std::initializer_list<E> for some type E, and either there are no other
8807 // parameters or else all other parameters have default arguments.
8808 if (Ctor->getNumParams() < 1 ||
8809 (Ctor->getNumParams() > 1 && !Ctor->getParamDecl(1)->hasDefaultArg()))
8812 QualType ArgType = Ctor->getParamDecl(0)->getType();
8813 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
8814 ArgType = RT->getPointeeType().getUnqualifiedType();
8816 return isStdInitializerList(ArgType, nullptr);
8819 /// \brief Determine whether a using statement is in a context where it will be
8820 /// apply in all contexts.
8821 static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
8822 switch (CurContext->getDeclKind()) {
8823 case Decl::TranslationUnit:
8825 case Decl::LinkageSpec:
8826 return IsUsingDirectiveInToplevelContext(CurContext->getParent());
8834 // Callback to only accept typo corrections that are namespaces.
8835 class NamespaceValidatorCCC : public CorrectionCandidateCallback {
8837 bool ValidateCandidate(const TypoCorrection &candidate) override {
8838 if (NamedDecl *ND = candidate.getCorrectionDecl())
8839 return isa<NamespaceDecl>(ND) || isa<NamespaceAliasDecl>(ND);
8846 static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
8848 SourceLocation IdentLoc,
8849 IdentifierInfo *Ident) {
8851 if (TypoCorrection Corrected =
8852 S.CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), Sc, &SS,
8853 llvm::make_unique<NamespaceValidatorCCC>(),
8854 Sema::CTK_ErrorRecovery)) {
8855 if (DeclContext *DC = S.computeDeclContext(SS, false)) {
8856 std::string CorrectedStr(Corrected.getAsString(S.getLangOpts()));
8857 bool DroppedSpecifier = Corrected.WillReplaceSpecifier() &&
8858 Ident->getName().equals(CorrectedStr);
8859 S.diagnoseTypo(Corrected,
8860 S.PDiag(diag::err_using_directive_member_suggest)
8861 << Ident << DC << DroppedSpecifier << SS.getRange(),
8862 S.PDiag(diag::note_namespace_defined_here));
8864 S.diagnoseTypo(Corrected,
8865 S.PDiag(diag::err_using_directive_suggest) << Ident,
8866 S.PDiag(diag::note_namespace_defined_here));
8868 R.addDecl(Corrected.getFoundDecl());
8874 Decl *Sema::ActOnUsingDirective(Scope *S,
8875 SourceLocation UsingLoc,
8876 SourceLocation NamespcLoc,
8878 SourceLocation IdentLoc,
8879 IdentifierInfo *NamespcName,
8880 AttributeList *AttrList) {
8881 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
8882 assert(NamespcName && "Invalid NamespcName.");
8883 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
8885 // This can only happen along a recovery path.
8886 while (S->isTemplateParamScope())
8888 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8890 UsingDirectiveDecl *UDir = nullptr;
8891 NestedNameSpecifier *Qualifier = nullptr;
8893 Qualifier = SS.getScopeRep();
8895 // Lookup namespace name.
8896 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
8897 LookupParsedName(R, S, &SS);
8898 if (R.isAmbiguous())
8903 // Allow "using namespace std;" or "using namespace ::std;" even if
8904 // "std" hasn't been defined yet, for GCC compatibility.
8905 if ((!Qualifier || Qualifier->getKind() == NestedNameSpecifier::Global) &&
8906 NamespcName->isStr("std")) {
8907 Diag(IdentLoc, diag::ext_using_undefined_std);
8908 R.addDecl(getOrCreateStdNamespace());
8911 // Otherwise, attempt typo correction.
8912 else TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, NamespcName);
8916 NamedDecl *Named = R.getRepresentativeDecl();
8917 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
8918 assert(NS && "expected namespace decl");
8920 // The use of a nested name specifier may trigger deprecation warnings.
8921 DiagnoseUseOfDecl(Named, IdentLoc);
8923 // C++ [namespace.udir]p1:
8924 // A using-directive specifies that the names in the nominated
8925 // namespace can be used in the scope in which the
8926 // using-directive appears after the using-directive. During
8927 // unqualified name lookup (3.4.1), the names appear as if they
8928 // were declared in the nearest enclosing namespace which
8929 // contains both the using-directive and the nominated
8930 // namespace. [Note: in this context, "contains" means "contains
8931 // directly or indirectly". ]
8933 // Find enclosing context containing both using-directive and
8934 // nominated namespace.
8935 DeclContext *CommonAncestor = cast<DeclContext>(NS);
8936 while (CommonAncestor && !CommonAncestor->Encloses(CurContext))
8937 CommonAncestor = CommonAncestor->getParent();
8939 UDir = UsingDirectiveDecl::Create(Context, CurContext, UsingLoc, NamespcLoc,
8940 SS.getWithLocInContext(Context),
8941 IdentLoc, Named, CommonAncestor);
8943 if (IsUsingDirectiveInToplevelContext(CurContext) &&
8944 !SourceMgr.isInMainFile(SourceMgr.getExpansionLoc(IdentLoc))) {
8945 Diag(IdentLoc, diag::warn_using_directive_in_header);
8948 PushUsingDirective(S, UDir);
8950 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
8954 ProcessDeclAttributeList(S, UDir, AttrList);
8959 void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
8960 // If the scope has an associated entity and the using directive is at
8961 // namespace or translation unit scope, add the UsingDirectiveDecl into
8962 // its lookup structure so qualified name lookup can find it.
8963 DeclContext *Ctx = S->getEntity();
8964 if (Ctx && !Ctx->isFunctionOrMethod())
8967 // Otherwise, it is at block scope. The using-directives will affect lookup
8968 // only to the end of the scope.
8969 S->PushUsingDirective(UDir);
8973 Decl *Sema::ActOnUsingDeclaration(Scope *S,
8975 SourceLocation UsingLoc,
8976 SourceLocation TypenameLoc,
8978 UnqualifiedId &Name,
8979 SourceLocation EllipsisLoc,
8980 AttributeList *AttrList) {
8981 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
8984 Diag(Name.getLocStart(), diag::err_using_requires_qualname);
8988 switch (Name.getKind()) {
8989 case UnqualifiedIdKind::IK_ImplicitSelfParam:
8990 case UnqualifiedIdKind::IK_Identifier:
8991 case UnqualifiedIdKind::IK_OperatorFunctionId:
8992 case UnqualifiedIdKind::IK_LiteralOperatorId:
8993 case UnqualifiedIdKind::IK_ConversionFunctionId:
8996 case UnqualifiedIdKind::IK_ConstructorName:
8997 case UnqualifiedIdKind::IK_ConstructorTemplateId:
8998 // C++11 inheriting constructors.
8999 Diag(Name.getLocStart(),
9000 getLangOpts().CPlusPlus11 ?
9001 diag::warn_cxx98_compat_using_decl_constructor :
9002 diag::err_using_decl_constructor)
9005 if (getLangOpts().CPlusPlus11) break;
9009 case UnqualifiedIdKind::IK_DestructorName:
9010 Diag(Name.getLocStart(), diag::err_using_decl_destructor)
9014 case UnqualifiedIdKind::IK_TemplateId:
9015 Diag(Name.getLocStart(), diag::err_using_decl_template_id)
9016 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
9019 case UnqualifiedIdKind::IK_DeductionGuideName:
9020 llvm_unreachable("cannot parse qualified deduction guide name");
9023 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
9024 DeclarationName TargetName = TargetNameInfo.getName();
9028 // Warn about access declarations.
9029 if (UsingLoc.isInvalid()) {
9030 Diag(Name.getLocStart(),
9031 getLangOpts().CPlusPlus11 ? diag::err_access_decl
9032 : diag::warn_access_decl_deprecated)
9033 << FixItHint::CreateInsertion(SS.getRange().getBegin(), "using ");
9036 if (EllipsisLoc.isInvalid()) {
9037 if (DiagnoseUnexpandedParameterPack(SS, UPPC_UsingDeclaration) ||
9038 DiagnoseUnexpandedParameterPack(TargetNameInfo, UPPC_UsingDeclaration))
9041 if (!SS.getScopeRep()->containsUnexpandedParameterPack() &&
9042 !TargetNameInfo.containsUnexpandedParameterPack()) {
9043 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
9044 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
9045 EllipsisLoc = SourceLocation();
9050 BuildUsingDeclaration(S, AS, UsingLoc, TypenameLoc.isValid(), TypenameLoc,
9051 SS, TargetNameInfo, EllipsisLoc, AttrList,
9052 /*IsInstantiation*/false);
9054 PushOnScopeChains(UD, S, /*AddToContext*/ false);
9059 /// \brief Determine whether a using declaration considers the given
9060 /// declarations as "equivalent", e.g., if they are redeclarations of
9061 /// the same entity or are both typedefs of the same type.
9063 IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
9064 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
9067 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(D1))
9068 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(D2))
9069 return Context.hasSameType(TD1->getUnderlyingType(),
9070 TD2->getUnderlyingType());
9076 /// Determines whether to create a using shadow decl for a particular
9077 /// decl, given the set of decls existing prior to this using lookup.
9078 bool Sema::CheckUsingShadowDecl(UsingDecl *Using, NamedDecl *Orig,
9079 const LookupResult &Previous,
9080 UsingShadowDecl *&PrevShadow) {
9081 // Diagnose finding a decl which is not from a base class of the
9082 // current class. We do this now because there are cases where this
9083 // function will silently decide not to build a shadow decl, which
9084 // will pre-empt further diagnostics.
9086 // We don't need to do this in C++11 because we do the check once on
9089 // FIXME: diagnose the following if we care enough:
9090 // struct A { int foo; };
9091 // struct B : A { using A::foo; };
9092 // template <class T> struct C : A {};
9093 // template <class T> struct D : C<T> { using B::foo; } // <---
9094 // This is invalid (during instantiation) in C++03 because B::foo
9095 // resolves to the using decl in B, which is not a base class of D<T>.
9096 // We can't diagnose it immediately because C<T> is an unknown
9097 // specialization. The UsingShadowDecl in D<T> then points directly
9098 // to A::foo, which will look well-formed when we instantiate.
9099 // The right solution is to not collapse the shadow-decl chain.
9100 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord()) {
9101 DeclContext *OrigDC = Orig->getDeclContext();
9103 // Handle enums and anonymous structs.
9104 if (isa<EnumDecl>(OrigDC)) OrigDC = OrigDC->getParent();
9105 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(OrigDC);
9106 while (OrigRec->isAnonymousStructOrUnion())
9107 OrigRec = cast<CXXRecordDecl>(OrigRec->getDeclContext());
9109 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(OrigRec)) {
9110 if (OrigDC == CurContext) {
9111 Diag(Using->getLocation(),
9112 diag::err_using_decl_nested_name_specifier_is_current_class)
9113 << Using->getQualifierLoc().getSourceRange();
9114 Diag(Orig->getLocation(), diag::note_using_decl_target);
9115 Using->setInvalidDecl();
9119 Diag(Using->getQualifierLoc().getBeginLoc(),
9120 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9121 << Using->getQualifier()
9122 << cast<CXXRecordDecl>(CurContext)
9123 << Using->getQualifierLoc().getSourceRange();
9124 Diag(Orig->getLocation(), diag::note_using_decl_target);
9125 Using->setInvalidDecl();
9130 if (Previous.empty()) return false;
9132 NamedDecl *Target = Orig;
9133 if (isa<UsingShadowDecl>(Target))
9134 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9136 // If the target happens to be one of the previous declarations, we
9137 // don't have a conflict.
9139 // FIXME: but we might be increasing its access, in which case we
9140 // should redeclare it.
9141 NamedDecl *NonTag = nullptr, *Tag = nullptr;
9142 bool FoundEquivalentDecl = false;
9143 for (LookupResult::iterator I = Previous.begin(), E = Previous.end();
9145 NamedDecl *D = (*I)->getUnderlyingDecl();
9146 // We can have UsingDecls in our Previous results because we use the same
9147 // LookupResult for checking whether the UsingDecl itself is a valid
9149 if (isa<UsingDecl>(D) || isa<UsingPackDecl>(D))
9152 if (IsEquivalentForUsingDecl(Context, D, Target)) {
9153 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(*I))
9154 PrevShadow = Shadow;
9155 FoundEquivalentDecl = true;
9156 } else if (isEquivalentInternalLinkageDeclaration(D, Target)) {
9157 // We don't conflict with an existing using shadow decl of an equivalent
9158 // declaration, but we're not a redeclaration of it.
9159 FoundEquivalentDecl = true;
9163 (isa<TagDecl>(D) ? Tag : NonTag) = D;
9166 if (FoundEquivalentDecl)
9169 if (FunctionDecl *FD = Target->getAsFunction()) {
9170 NamedDecl *OldDecl = nullptr;
9171 switch (CheckOverload(nullptr, FD, Previous, OldDecl,
9172 /*IsForUsingDecl*/ true)) {
9176 case Ovl_NonFunction:
9177 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9180 // We found a decl with the exact signature.
9182 // If we're in a record, we want to hide the target, so we
9183 // return true (without a diagnostic) to tell the caller not to
9184 // build a shadow decl.
9185 if (CurContext->isRecord())
9188 // If we're not in a record, this is an error.
9189 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9193 Diag(Target->getLocation(), diag::note_using_decl_target);
9194 Diag(OldDecl->getLocation(), diag::note_using_decl_conflict);
9195 Using->setInvalidDecl();
9199 // Target is not a function.
9201 if (isa<TagDecl>(Target)) {
9202 // No conflict between a tag and a non-tag.
9203 if (!Tag) return false;
9205 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9206 Diag(Target->getLocation(), diag::note_using_decl_target);
9207 Diag(Tag->getLocation(), diag::note_using_decl_conflict);
9208 Using->setInvalidDecl();
9212 // No conflict between a tag and a non-tag.
9213 if (!NonTag) return false;
9215 Diag(Using->getLocation(), diag::err_using_decl_conflict);
9216 Diag(Target->getLocation(), diag::note_using_decl_target);
9217 Diag(NonTag->getLocation(), diag::note_using_decl_conflict);
9218 Using->setInvalidDecl();
9222 /// Determine whether a direct base class is a virtual base class.
9223 static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
9224 if (!Derived->getNumVBases())
9226 for (auto &B : Derived->bases())
9227 if (B.getType()->getAsCXXRecordDecl() == Base)
9228 return B.isVirtual();
9229 llvm_unreachable("not a direct base class");
9232 /// Builds a shadow declaration corresponding to a 'using' declaration.
9233 UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S,
9236 UsingShadowDecl *PrevDecl) {
9237 // If we resolved to another shadow declaration, just coalesce them.
9238 NamedDecl *Target = Orig;
9239 if (isa<UsingShadowDecl>(Target)) {
9240 Target = cast<UsingShadowDecl>(Target)->getTargetDecl();
9241 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
9244 NamedDecl *NonTemplateTarget = Target;
9245 if (auto *TargetTD = dyn_cast<TemplateDecl>(Target))
9246 NonTemplateTarget = TargetTD->getTemplatedDecl();
9248 UsingShadowDecl *Shadow;
9249 if (isa<CXXConstructorDecl>(NonTemplateTarget)) {
9250 bool IsVirtualBase =
9251 isVirtualDirectBase(cast<CXXRecordDecl>(CurContext),
9252 UD->getQualifier()->getAsRecordDecl());
9253 Shadow = ConstructorUsingShadowDecl::Create(
9254 Context, CurContext, UD->getLocation(), UD, Orig, IsVirtualBase);
9256 Shadow = UsingShadowDecl::Create(Context, CurContext, UD->getLocation(), UD,
9259 UD->addShadowDecl(Shadow);
9261 Shadow->setAccess(UD->getAccess());
9262 if (Orig->isInvalidDecl() || UD->isInvalidDecl())
9263 Shadow->setInvalidDecl();
9265 Shadow->setPreviousDecl(PrevDecl);
9268 PushOnScopeChains(Shadow, S);
9270 CurContext->addDecl(Shadow);
9276 /// Hides a using shadow declaration. This is required by the current
9277 /// using-decl implementation when a resolvable using declaration in a
9278 /// class is followed by a declaration which would hide or override
9279 /// one or more of the using decl's targets; for example:
9281 /// struct Base { void foo(int); };
9282 /// struct Derived : Base {
9283 /// using Base::foo;
9287 /// The governing language is C++03 [namespace.udecl]p12:
9289 /// When a using-declaration brings names from a base class into a
9290 /// derived class scope, member functions in the derived class
9291 /// override and/or hide member functions with the same name and
9292 /// parameter types in a base class (rather than conflicting).
9294 /// There are two ways to implement this:
9295 /// (1) optimistically create shadow decls when they're not hidden
9296 /// by existing declarations, or
9297 /// (2) don't create any shadow decls (or at least don't make them
9298 /// visible) until we've fully parsed/instantiated the class.
9299 /// The problem with (1) is that we might have to retroactively remove
9300 /// a shadow decl, which requires several O(n) operations because the
9301 /// decl structures are (very reasonably) not designed for removal.
9302 /// (2) avoids this but is very fiddly and phase-dependent.
9303 void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
9304 if (Shadow->getDeclName().getNameKind() ==
9305 DeclarationName::CXXConversionFunctionName)
9306 cast<CXXRecordDecl>(Shadow->getDeclContext())->removeConversion(Shadow);
9308 // Remove it from the DeclContext...
9309 Shadow->getDeclContext()->removeDecl(Shadow);
9311 // ...and the scope, if applicable...
9313 S->RemoveDecl(Shadow);
9314 IdResolver.RemoveDecl(Shadow);
9317 // ...and the using decl.
9318 Shadow->getUsingDecl()->removeShadowDecl(Shadow);
9320 // TODO: complain somehow if Shadow was used. It shouldn't
9321 // be possible for this to happen, because...?
9324 /// Find the base specifier for a base class with the given type.
9325 static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
9326 QualType DesiredBase,
9327 bool &AnyDependentBases) {
9328 // Check whether the named type is a direct base class.
9329 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
9330 for (auto &Base : Derived->bases()) {
9331 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
9332 if (CanonicalDesiredBase == BaseType)
9334 if (BaseType->isDependentType())
9335 AnyDependentBases = true;
9341 class UsingValidatorCCC : public CorrectionCandidateCallback {
9343 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
9344 NestedNameSpecifier *NNS, CXXRecordDecl *RequireMemberOf)
9345 : HasTypenameKeyword(HasTypenameKeyword),
9346 IsInstantiation(IsInstantiation), OldNNS(NNS),
9347 RequireMemberOf(RequireMemberOf) {}
9349 bool ValidateCandidate(const TypoCorrection &Candidate) override {
9350 NamedDecl *ND = Candidate.getCorrectionDecl();
9352 // Keywords are not valid here.
9353 if (!ND || isa<NamespaceDecl>(ND))
9356 // Completely unqualified names are invalid for a 'using' declaration.
9357 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
9360 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
9363 if (RequireMemberOf) {
9364 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9365 if (FoundRecord && FoundRecord->isInjectedClassName()) {
9366 // No-one ever wants a using-declaration to name an injected-class-name
9367 // of a base class, unless they're declaring an inheriting constructor.
9368 ASTContext &Ctx = ND->getASTContext();
9369 if (!Ctx.getLangOpts().CPlusPlus11)
9371 QualType FoundType = Ctx.getRecordType(FoundRecord);
9373 // Check that the injected-class-name is named as a member of its own
9374 // type; we don't want to suggest 'using Derived::Base;', since that
9375 // means something else.
9376 NestedNameSpecifier *Specifier =
9377 Candidate.WillReplaceSpecifier()
9378 ? Candidate.getCorrectionSpecifier()
9380 if (!Specifier->getAsType() ||
9381 !Ctx.hasSameType(QualType(Specifier->getAsType(), 0), FoundType))
9384 // Check that this inheriting constructor declaration actually names a
9385 // direct base class of the current class.
9386 bool AnyDependentBases = false;
9387 if (!findDirectBaseWithType(RequireMemberOf,
9388 Ctx.getRecordType(FoundRecord),
9389 AnyDependentBases) &&
9393 auto *RD = dyn_cast<CXXRecordDecl>(ND->getDeclContext());
9394 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(RD))
9397 // FIXME: Check that the base class member is accessible?
9400 auto *FoundRecord = dyn_cast<CXXRecordDecl>(ND);
9401 if (FoundRecord && FoundRecord->isInjectedClassName())
9405 if (isa<TypeDecl>(ND))
9406 return HasTypenameKeyword || !IsInstantiation;
9408 return !HasTypenameKeyword;
9412 bool HasTypenameKeyword;
9413 bool IsInstantiation;
9414 NestedNameSpecifier *OldNNS;
9415 CXXRecordDecl *RequireMemberOf;
9417 } // end anonymous namespace
9419 /// Builds a using declaration.
9421 /// \param IsInstantiation - Whether this call arises from an
9422 /// instantiation of an unresolved using declaration. We treat
9423 /// the lookup differently for these declarations.
9424 NamedDecl *Sema::BuildUsingDeclaration(Scope *S, AccessSpecifier AS,
9425 SourceLocation UsingLoc,
9426 bool HasTypenameKeyword,
9427 SourceLocation TypenameLoc,
9429 DeclarationNameInfo NameInfo,
9430 SourceLocation EllipsisLoc,
9431 AttributeList *AttrList,
9432 bool IsInstantiation) {
9433 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
9434 SourceLocation IdentLoc = NameInfo.getLoc();
9435 assert(IdentLoc.isValid() && "Invalid TargetName location.");
9437 // FIXME: We ignore attributes for now.
9439 // For an inheriting constructor declaration, the name of the using
9440 // declaration is the name of a constructor in this class, not in the
9442 DeclarationNameInfo UsingName = NameInfo;
9443 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
9444 if (auto *RD = dyn_cast<CXXRecordDecl>(CurContext))
9445 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9446 Context.getCanonicalType(Context.getRecordType(RD))));
9448 // Do the redeclaration lookup in the current scope.
9449 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
9450 ForVisibleRedeclaration);
9451 Previous.setHideTags(false);
9453 LookupName(Previous, S);
9455 // It is really dumb that we have to do this.
9456 LookupResult::Filter F = Previous.makeFilter();
9457 while (F.hasNext()) {
9458 NamedDecl *D = F.next();
9459 if (!isDeclInScope(D, CurContext, S))
9461 // If we found a local extern declaration that's not ordinarily visible,
9462 // and this declaration is being added to a non-block scope, ignore it.
9463 // We're only checking for scope conflicts here, not also for violations
9464 // of the linkage rules.
9465 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
9466 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
9471 assert(IsInstantiation && "no scope in non-instantiation");
9472 if (CurContext->isRecord())
9473 LookupQualifiedName(Previous, CurContext);
9475 // No redeclaration check is needed here; in non-member contexts we
9476 // diagnosed all possible conflicts with other using-declarations when
9477 // building the template:
9479 // For a dependent non-type using declaration, the only valid case is
9480 // if we instantiate to a single enumerator. We check for conflicts
9481 // between shadow declarations we introduce, and we check in the template
9482 // definition for conflicts between a non-type using declaration and any
9483 // other declaration, which together covers all cases.
9485 // A dependent typename using declaration will never successfully
9486 // instantiate, since it will always name a class member, so we reject
9487 // that in the template definition.
9491 // Check for invalid redeclarations.
9492 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
9493 SS, IdentLoc, Previous))
9496 // Check for bad qualifiers.
9497 if (CheckUsingDeclQualifier(UsingLoc, HasTypenameKeyword, SS, NameInfo,
9501 DeclContext *LookupContext = computeDeclContext(SS);
9503 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
9504 if (!LookupContext || EllipsisLoc.isValid()) {
9505 if (HasTypenameKeyword) {
9506 // FIXME: not all declaration name kinds are legal here
9507 D = UnresolvedUsingTypenameDecl::Create(Context, CurContext,
9508 UsingLoc, TypenameLoc,
9510 IdentLoc, NameInfo.getName(),
9513 D = UnresolvedUsingValueDecl::Create(Context, CurContext, UsingLoc,
9514 QualifierLoc, NameInfo, EllipsisLoc);
9517 CurContext->addDecl(D);
9521 auto Build = [&](bool Invalid) {
9523 UsingDecl::Create(Context, CurContext, UsingLoc, QualifierLoc,
9524 UsingName, HasTypenameKeyword);
9526 CurContext->addDecl(UD);
9527 UD->setInvalidDecl(Invalid);
9530 auto BuildInvalid = [&]{ return Build(true); };
9531 auto BuildValid = [&]{ return Build(false); };
9533 if (RequireCompleteDeclContext(SS, LookupContext))
9534 return BuildInvalid();
9536 // Look up the target name.
9537 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9539 // Unlike most lookups, we don't always want to hide tag
9540 // declarations: tag names are visible through the using declaration
9541 // even if hidden by ordinary names, *except* in a dependent context
9542 // where it's important for the sanity of two-phase lookup.
9543 if (!IsInstantiation)
9544 R.setHideTags(false);
9546 // For the purposes of this lookup, we have a base object type
9547 // equal to that of the current context.
9548 if (CurContext->isRecord()) {
9549 R.setBaseObjectType(
9550 Context.getTypeDeclType(cast<CXXRecordDecl>(CurContext)));
9553 LookupQualifiedName(R, LookupContext);
9555 // Try to correct typos if possible. If constructor name lookup finds no
9556 // results, that means the named class has no explicit constructors, and we
9557 // suppressed declaring implicit ones (probably because it's dependent or
9560 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
9561 // HACK: Work around a bug in libstdc++'s detection of ::gets. Sometimes
9562 // it will believe that glibc provides a ::gets in cases where it does not,
9563 // and will try to pull it into namespace std with a using-declaration.
9564 // Just ignore the using-declaration in that case.
9565 auto *II = NameInfo.getName().getAsIdentifierInfo();
9566 if (getLangOpts().CPlusPlus14 && II && II->isStr("gets") &&
9567 CurContext->isStdNamespace() &&
9568 isa<TranslationUnitDecl>(LookupContext) &&
9569 getSourceManager().isInSystemHeader(UsingLoc))
9571 if (TypoCorrection Corrected = CorrectTypo(
9572 R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
9573 llvm::make_unique<UsingValidatorCCC>(
9574 HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
9575 dyn_cast<CXXRecordDecl>(CurContext)),
9576 CTK_ErrorRecovery)) {
9577 // We reject candidates where DroppedSpecifier == true, hence the
9578 // literal '0' below.
9579 diagnoseTypo(Corrected, PDiag(diag::err_no_member_suggest)
9580 << NameInfo.getName() << LookupContext << 0
9583 // If we picked a correction with no attached Decl we can't do anything
9584 // useful with it, bail out.
9585 NamedDecl *ND = Corrected.getCorrectionDecl();
9587 return BuildInvalid();
9589 // If we corrected to an inheriting constructor, handle it as one.
9590 auto *RD = dyn_cast<CXXRecordDecl>(ND);
9591 if (RD && RD->isInjectedClassName()) {
9592 // The parent of the injected class name is the class itself.
9593 RD = cast<CXXRecordDecl>(RD->getParent());
9595 // Fix up the information we'll use to build the using declaration.
9596 if (Corrected.WillReplaceSpecifier()) {
9597 NestedNameSpecifierLocBuilder Builder;
9598 Builder.MakeTrivial(Context, Corrected.getCorrectionSpecifier(),
9599 QualifierLoc.getSourceRange());
9600 QualifierLoc = Builder.getWithLocInContext(Context);
9603 // In this case, the name we introduce is the name of a derived class
9605 auto *CurClass = cast<CXXRecordDecl>(CurContext);
9606 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
9607 Context.getCanonicalType(Context.getRecordType(CurClass))));
9608 UsingName.setNamedTypeInfo(nullptr);
9609 for (auto *Ctor : LookupConstructors(RD))
9613 // FIXME: Pick up all the declarations if we found an overloaded
9615 UsingName.setName(ND->getDeclName());
9619 Diag(IdentLoc, diag::err_no_member)
9620 << NameInfo.getName() << LookupContext << SS.getRange();
9621 return BuildInvalid();
9625 if (R.isAmbiguous())
9626 return BuildInvalid();
9628 if (HasTypenameKeyword) {
9629 // If we asked for a typename and got a non-type decl, error out.
9630 if (!R.getAsSingle<TypeDecl>()) {
9631 Diag(IdentLoc, diag::err_using_typename_non_type);
9632 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I)
9633 Diag((*I)->getUnderlyingDecl()->getLocation(),
9634 diag::note_using_decl_target);
9635 return BuildInvalid();
9638 // If we asked for a non-typename and we got a type, error out,
9639 // but only if this is an instantiation of an unresolved using
9640 // decl. Otherwise just silently find the type name.
9641 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
9642 Diag(IdentLoc, diag::err_using_dependent_value_is_type);
9643 Diag(R.getFoundDecl()->getLocation(), diag::note_using_decl_target);
9644 return BuildInvalid();
9648 // C++14 [namespace.udecl]p6:
9649 // A using-declaration shall not name a namespace.
9650 if (R.getAsSingle<NamespaceDecl>()) {
9651 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_namespace)
9653 return BuildInvalid();
9656 // C++14 [namespace.udecl]p7:
9657 // A using-declaration shall not name a scoped enumerator.
9658 if (auto *ED = R.getAsSingle<EnumConstantDecl>()) {
9659 if (cast<EnumDecl>(ED->getDeclContext())->isScoped()) {
9660 Diag(IdentLoc, diag::err_using_decl_can_not_refer_to_scoped_enum)
9662 return BuildInvalid();
9666 UsingDecl *UD = BuildValid();
9668 // Some additional rules apply to inheriting constructors.
9669 if (UsingName.getName().getNameKind() ==
9670 DeclarationName::CXXConstructorName) {
9671 // Suppress access diagnostics; the access check is instead performed at the
9672 // point of use for an inheriting constructor.
9673 R.suppressDiagnostics();
9674 if (CheckInheritingConstructorUsingDecl(UD))
9678 for (LookupResult::iterator I = R.begin(), E = R.end(); I != E; ++I) {
9679 UsingShadowDecl *PrevDecl = nullptr;
9680 if (!CheckUsingShadowDecl(UD, *I, Previous, PrevDecl))
9681 BuildUsingShadowDecl(S, UD, *I, PrevDecl);
9687 NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
9688 ArrayRef<NamedDecl *> Expansions) {
9689 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
9690 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
9691 isa<UsingPackDecl>(InstantiatedFrom));
9694 UsingPackDecl::Create(Context, CurContext, InstantiatedFrom, Expansions);
9695 UPD->setAccess(InstantiatedFrom->getAccess());
9696 CurContext->addDecl(UPD);
9700 /// Additional checks for a using declaration referring to a constructor name.
9701 bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
9702 assert(!UD->hasTypename() && "expecting a constructor name");
9704 const Type *SourceType = UD->getQualifier()->getAsType();
9705 assert(SourceType &&
9706 "Using decl naming constructor doesn't have type in scope spec.");
9707 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(CurContext);
9709 // Check whether the named type is a direct base class.
9710 bool AnyDependentBases = false;
9711 auto *Base = findDirectBaseWithType(TargetClass, QualType(SourceType, 0),
9713 if (!Base && !AnyDependentBases) {
9714 Diag(UD->getUsingLoc(),
9715 diag::err_using_decl_constructor_not_in_direct_base)
9716 << UD->getNameInfo().getSourceRange()
9717 << QualType(SourceType, 0) << TargetClass;
9718 UD->setInvalidDecl();
9723 Base->setInheritConstructors();
9728 /// Checks that the given using declaration is not an invalid
9729 /// redeclaration. Note that this is checking only for the using decl
9730 /// itself, not for any ill-formedness among the UsingShadowDecls.
9731 bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
9732 bool HasTypenameKeyword,
9733 const CXXScopeSpec &SS,
9734 SourceLocation NameLoc,
9735 const LookupResult &Prev) {
9736 NestedNameSpecifier *Qual = SS.getScopeRep();
9738 // C++03 [namespace.udecl]p8:
9739 // C++0x [namespace.udecl]p10:
9740 // A using-declaration is a declaration and can therefore be used
9741 // repeatedly where (and only where) multiple declarations are
9744 // That's in non-member contexts.
9745 if (!CurContext->getRedeclContext()->isRecord()) {
9746 // A dependent qualifier outside a class can only ever resolve to an
9747 // enumeration type. Therefore it conflicts with any other non-type
9748 // declaration in the same scope.
9749 // FIXME: How should we check for dependent type-type conflicts at block
9751 if (Qual->isDependent() && !HasTypenameKeyword) {
9752 for (auto *D : Prev) {
9753 if (!isa<TypeDecl>(D) && !isa<UsingDecl>(D) && !isa<UsingPackDecl>(D)) {
9754 bool OldCouldBeEnumerator =
9755 isa<UnresolvedUsingValueDecl>(D) || isa<EnumConstantDecl>(D);
9757 OldCouldBeEnumerator ? diag::err_redefinition
9758 : diag::err_redefinition_different_kind)
9759 << Prev.getLookupName();
9760 Diag(D->getLocation(), diag::note_previous_definition);
9768 for (LookupResult::iterator I = Prev.begin(), E = Prev.end(); I != E; ++I) {
9772 NestedNameSpecifier *DQual;
9773 if (UsingDecl *UD = dyn_cast<UsingDecl>(D)) {
9774 DTypename = UD->hasTypename();
9775 DQual = UD->getQualifier();
9776 } else if (UnresolvedUsingValueDecl *UD
9777 = dyn_cast<UnresolvedUsingValueDecl>(D)) {
9779 DQual = UD->getQualifier();
9780 } else if (UnresolvedUsingTypenameDecl *UD
9781 = dyn_cast<UnresolvedUsingTypenameDecl>(D)) {
9783 DQual = UD->getQualifier();
9786 // using decls differ if one says 'typename' and the other doesn't.
9787 // FIXME: non-dependent using decls?
9788 if (HasTypenameKeyword != DTypename) continue;
9790 // using decls differ if they name different scopes (but note that
9791 // template instantiation can cause this check to trigger when it
9792 // didn't before instantiation).
9793 if (Context.getCanonicalNestedNameSpecifier(Qual) !=
9794 Context.getCanonicalNestedNameSpecifier(DQual))
9797 Diag(NameLoc, diag::err_using_decl_redeclaration) << SS.getRange();
9798 Diag(D->getLocation(), diag::note_using_decl) << 1;
9806 /// Checks that the given nested-name qualifier used in a using decl
9807 /// in the current context is appropriately related to the current
9808 /// scope. If an error is found, diagnoses it and returns true.
9809 bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc,
9811 const CXXScopeSpec &SS,
9812 const DeclarationNameInfo &NameInfo,
9813 SourceLocation NameLoc) {
9814 DeclContext *NamedContext = computeDeclContext(SS);
9816 if (!CurContext->isRecord()) {
9817 // C++03 [namespace.udecl]p3:
9818 // C++0x [namespace.udecl]p8:
9819 // A using-declaration for a class member shall be a member-declaration.
9821 // If we weren't able to compute a valid scope, it might validly be a
9822 // dependent class scope or a dependent enumeration unscoped scope. If
9823 // we have a 'typename' keyword, the scope must resolve to a class type.
9824 if ((HasTypename && !NamedContext) ||
9825 (NamedContext && NamedContext->getRedeclContext()->isRecord())) {
9826 auto *RD = NamedContext
9827 ? cast<CXXRecordDecl>(NamedContext->getRedeclContext())
9829 if (RD && RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), RD))
9832 Diag(NameLoc, diag::err_using_decl_can_not_refer_to_class_member)
9835 // If we have a complete, non-dependent source type, try to suggest a
9836 // way to get the same effect.
9840 // Find what this using-declaration was referring to.
9841 LookupResult R(*this, NameInfo, LookupOrdinaryName);
9842 R.setHideTags(false);
9843 R.suppressDiagnostics();
9844 LookupQualifiedName(R, RD);
9846 if (R.getAsSingle<TypeDecl>()) {
9847 if (getLangOpts().CPlusPlus11) {
9848 // Convert 'using X::Y;' to 'using Y = X::Y;'.
9849 Diag(SS.getBeginLoc(), diag::note_using_decl_class_member_workaround)
9850 << 0 // alias declaration
9851 << FixItHint::CreateInsertion(SS.getBeginLoc(),
9852 NameInfo.getName().getAsString() +
9855 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
9856 SourceLocation InsertLoc =
9857 getLocForEndOfToken(NameInfo.getLocEnd());
9858 Diag(InsertLoc, diag::note_using_decl_class_member_workaround)
9859 << 1 // typedef declaration
9860 << FixItHint::CreateReplacement(UsingLoc, "typedef")
9861 << FixItHint::CreateInsertion(
9862 InsertLoc, " " + NameInfo.getName().getAsString());
9864 } else if (R.getAsSingle<VarDecl>()) {
9865 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9866 // repeating the type of the static data member here.
9868 if (getLangOpts().CPlusPlus11) {
9869 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9870 FixIt = FixItHint::CreateReplacement(
9871 UsingLoc, "auto &" + NameInfo.getName().getAsString() + " = ");
9874 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9875 << 2 // reference declaration
9877 } else if (R.getAsSingle<EnumConstantDecl>()) {
9878 // Don't provide a fixit outside C++11 mode; we don't want to suggest
9879 // repeating the type of the enumeration here, and we can't do so if
9880 // the type is anonymous.
9882 if (getLangOpts().CPlusPlus11) {
9883 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
9884 FixIt = FixItHint::CreateReplacement(
9886 "constexpr auto " + NameInfo.getName().getAsString() + " = ");
9889 Diag(UsingLoc, diag::note_using_decl_class_member_workaround)
9890 << (getLangOpts().CPlusPlus11 ? 4 : 3) // const[expr] variable
9896 // Otherwise, this might be valid.
9900 // The current scope is a record.
9902 // If the named context is dependent, we can't decide much.
9903 if (!NamedContext) {
9904 // FIXME: in C++0x, we can diagnose if we can prove that the
9905 // nested-name-specifier does not refer to a base class, which is
9906 // still possible in some cases.
9908 // Otherwise we have to conservatively report that things might be
9913 if (!NamedContext->isRecord()) {
9914 // Ideally this would point at the last name in the specifier,
9915 // but we don't have that level of source info.
9916 Diag(SS.getRange().getBegin(),
9917 diag::err_using_decl_nested_name_specifier_is_not_class)
9918 << SS.getScopeRep() << SS.getRange();
9922 if (!NamedContext->isDependentContext() &&
9923 RequireCompleteDeclContext(const_cast<CXXScopeSpec&>(SS), NamedContext))
9926 if (getLangOpts().CPlusPlus11) {
9927 // C++11 [namespace.udecl]p3:
9928 // In a using-declaration used as a member-declaration, the
9929 // nested-name-specifier shall name a base class of the class
9932 if (cast<CXXRecordDecl>(CurContext)->isProvablyNotDerivedFrom(
9933 cast<CXXRecordDecl>(NamedContext))) {
9934 if (CurContext == NamedContext) {
9936 diag::err_using_decl_nested_name_specifier_is_current_class)
9941 if (!cast<CXXRecordDecl>(NamedContext)->isInvalidDecl()) {
9942 Diag(SS.getRange().getBegin(),
9943 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9945 << cast<CXXRecordDecl>(CurContext)
9954 // C++03 [namespace.udecl]p4:
9955 // A using-declaration used as a member-declaration shall refer
9956 // to a member of a base class of the class being defined [etc.].
9958 // Salient point: SS doesn't have to name a base class as long as
9959 // lookup only finds members from base classes. Therefore we can
9960 // diagnose here only if we can prove that that can't happen,
9961 // i.e. if the class hierarchies provably don't intersect.
9963 // TODO: it would be nice if "definitely valid" results were cached
9964 // in the UsingDecl and UsingShadowDecl so that these checks didn't
9965 // need to be repeated.
9967 llvm::SmallPtrSet<const CXXRecordDecl *, 4> Bases;
9968 auto Collect = [&Bases](const CXXRecordDecl *Base) {
9973 // Collect all bases. Return false if we find a dependent base.
9974 if (!cast<CXXRecordDecl>(CurContext)->forallBases(Collect))
9977 // Returns true if the base is dependent or is one of the accumulated base
9979 auto IsNotBase = [&Bases](const CXXRecordDecl *Base) {
9980 return !Bases.count(Base);
9983 // Return false if the class has a dependent base or if it or one
9984 // of its bases is present in the base set of the current context.
9985 if (Bases.count(cast<CXXRecordDecl>(NamedContext)) ||
9986 !cast<CXXRecordDecl>(NamedContext)->forallBases(IsNotBase))
9989 Diag(SS.getRange().getBegin(),
9990 diag::err_using_decl_nested_name_specifier_is_not_base_class)
9992 << cast<CXXRecordDecl>(CurContext)
9998 Decl *Sema::ActOnAliasDeclaration(Scope *S,
10000 MultiTemplateParamsArg TemplateParamLists,
10001 SourceLocation UsingLoc,
10002 UnqualifiedId &Name,
10003 AttributeList *AttrList,
10005 Decl *DeclFromDeclSpec) {
10006 // Skip up to the relevant declaration scope.
10007 while (S->isTemplateParamScope())
10008 S = S->getParent();
10009 assert((S->getFlags() & Scope::DeclScope) &&
10010 "got alias-declaration outside of declaration scope");
10012 if (Type.isInvalid())
10015 bool Invalid = false;
10016 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
10017 TypeSourceInfo *TInfo = nullptr;
10018 GetTypeFromParser(Type.get(), &TInfo);
10020 if (DiagnoseClassNameShadow(CurContext, NameInfo))
10023 if (DiagnoseUnexpandedParameterPack(Name.StartLocation, TInfo,
10024 UPPC_DeclarationType)) {
10026 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
10027 TInfo->getTypeLoc().getBeginLoc());
10030 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
10031 TemplateParamLists.size()
10032 ? forRedeclarationInCurContext()
10033 : ForVisibleRedeclaration);
10034 LookupName(Previous, S);
10036 // Warn about shadowing the name of a template parameter.
10037 if (Previous.isSingleResult() &&
10038 Previous.getFoundDecl()->isTemplateParameter()) {
10039 DiagnoseTemplateParameterShadow(Name.StartLocation,Previous.getFoundDecl());
10043 assert(Name.Kind == UnqualifiedIdKind::IK_Identifier &&
10044 "name in alias declaration must be an identifier");
10045 TypeAliasDecl *NewTD = TypeAliasDecl::Create(Context, CurContext, UsingLoc,
10046 Name.StartLocation,
10047 Name.Identifier, TInfo);
10049 NewTD->setAccess(AS);
10052 NewTD->setInvalidDecl();
10054 ProcessDeclAttributeList(S, NewTD, AttrList);
10055 AddPragmaAttributes(S, NewTD);
10057 CheckTypedefForVariablyModifiedType(S, NewTD);
10058 Invalid |= NewTD->isInvalidDecl();
10060 bool Redeclaration = false;
10063 if (TemplateParamLists.size()) {
10064 TypeAliasTemplateDecl *OldDecl = nullptr;
10065 TemplateParameterList *OldTemplateParams = nullptr;
10067 if (TemplateParamLists.size() != 1) {
10068 Diag(UsingLoc, diag::err_alias_template_extra_headers)
10069 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
10070 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
10072 TemplateParameterList *TemplateParams = TemplateParamLists[0];
10074 // Check that we can declare a template here.
10075 if (CheckTemplateDeclScope(S, TemplateParams))
10078 // Only consider previous declarations in the same scope.
10079 FilterLookupForScope(Previous, CurContext, S, /*ConsiderLinkage*/false,
10080 /*ExplicitInstantiationOrSpecialization*/false);
10081 if (!Previous.empty()) {
10082 Redeclaration = true;
10084 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
10085 if (!OldDecl && !Invalid) {
10086 Diag(UsingLoc, diag::err_redefinition_different_kind)
10087 << Name.Identifier;
10089 NamedDecl *OldD = Previous.getRepresentativeDecl();
10090 if (OldD->getLocation().isValid())
10091 Diag(OldD->getLocation(), diag::note_previous_definition);
10096 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
10097 if (TemplateParameterListsAreEqual(TemplateParams,
10098 OldDecl->getTemplateParameters(),
10100 TPL_TemplateMatch))
10101 OldTemplateParams = OldDecl->getTemplateParameters();
10105 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
10107 !Context.hasSameType(OldTD->getUnderlyingType(),
10108 NewTD->getUnderlyingType())) {
10109 // FIXME: The C++0x standard does not clearly say this is ill-formed,
10110 // but we can't reasonably accept it.
10111 Diag(NewTD->getLocation(), diag::err_redefinition_different_typedef)
10112 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
10113 if (OldTD->getLocation().isValid())
10114 Diag(OldTD->getLocation(), diag::note_previous_definition);
10120 // Merge any previous default template arguments into our parameters,
10121 // and check the parameter list.
10122 if (CheckTemplateParameterList(TemplateParams, OldTemplateParams,
10123 TPC_TypeAliasTemplate))
10126 TypeAliasTemplateDecl *NewDecl =
10127 TypeAliasTemplateDecl::Create(Context, CurContext, UsingLoc,
10128 Name.Identifier, TemplateParams,
10130 NewTD->setDescribedAliasTemplate(NewDecl);
10132 NewDecl->setAccess(AS);
10135 NewDecl->setInvalidDecl();
10136 else if (OldDecl) {
10137 NewDecl->setPreviousDecl(OldDecl);
10138 CheckRedeclarationModuleOwnership(NewDecl, OldDecl);
10143 if (auto *TD = dyn_cast_or_null<TagDecl>(DeclFromDeclSpec)) {
10144 setTagNameForLinkagePurposes(TD, NewTD);
10145 handleTagNumbering(TD, S);
10147 ActOnTypedefNameDecl(S, CurContext, NewTD, Previous, Redeclaration);
10151 PushOnScopeChains(NewND, S);
10152 ActOnDocumentableDecl(NewND);
10156 Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
10157 SourceLocation AliasLoc,
10158 IdentifierInfo *Alias, CXXScopeSpec &SS,
10159 SourceLocation IdentLoc,
10160 IdentifierInfo *Ident) {
10162 // Lookup the namespace name.
10163 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
10164 LookupParsedName(R, S, &SS);
10166 if (R.isAmbiguous())
10170 if (!TryNamespaceTypoCorrection(*this, R, S, SS, IdentLoc, Ident)) {
10171 Diag(IdentLoc, diag::err_expected_namespace_name) << SS.getRange();
10175 assert(!R.isAmbiguous() && !R.empty());
10176 NamedDecl *ND = R.getRepresentativeDecl();
10178 // Check if we have a previous declaration with the same name.
10179 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
10180 ForVisibleRedeclaration);
10181 LookupName(PrevR, S);
10183 // Check we're not shadowing a template parameter.
10184 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
10185 DiagnoseTemplateParameterShadow(AliasLoc, PrevR.getFoundDecl());
10189 // Filter out any other lookup result from an enclosing scope.
10190 FilterLookupForScope(PrevR, CurContext, S, /*ConsiderLinkage*/false,
10191 /*AllowInlineNamespace*/false);
10193 // Find the previous declaration and check that we can redeclare it.
10194 NamespaceAliasDecl *Prev = nullptr;
10195 if (PrevR.isSingleResult()) {
10196 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
10197 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(PrevDecl)) {
10198 // We already have an alias with the same name that points to the same
10199 // namespace; check that it matches.
10200 if (AD->getNamespace()->Equals(getNamespaceDecl(ND))) {
10202 } else if (isVisible(PrevDecl)) {
10203 Diag(AliasLoc, diag::err_redefinition_different_namespace_alias)
10205 Diag(AD->getLocation(), diag::note_previous_namespace_alias)
10206 << AD->getNamespace();
10209 } else if (isVisible(PrevDecl)) {
10210 unsigned DiagID = isa<NamespaceDecl>(PrevDecl->getUnderlyingDecl())
10211 ? diag::err_redefinition
10212 : diag::err_redefinition_different_kind;
10213 Diag(AliasLoc, DiagID) << Alias;
10214 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
10219 // The use of a nested name specifier may trigger deprecation warnings.
10220 DiagnoseUseOfDecl(ND, IdentLoc);
10222 NamespaceAliasDecl *AliasDecl =
10223 NamespaceAliasDecl::Create(Context, CurContext, NamespaceLoc, AliasLoc,
10224 Alias, SS.getWithLocInContext(Context),
10227 AliasDecl->setPreviousDecl(Prev);
10229 PushOnScopeChains(AliasDecl, S);
10234 struct SpecialMemberExceptionSpecInfo
10235 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
10236 SourceLocation Loc;
10237 Sema::ImplicitExceptionSpecification ExceptSpec;
10239 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
10240 Sema::CXXSpecialMember CSM,
10241 Sema::InheritedConstructorInfo *ICI,
10242 SourceLocation Loc)
10243 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
10245 bool visitBase(CXXBaseSpecifier *Base);
10246 bool visitField(FieldDecl *FD);
10248 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10251 void visitSubobjectCall(Subobject Subobj,
10252 Sema::SpecialMemberOverloadResult SMOR);
10256 bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
10257 auto *RT = Base->getType()->getAs<RecordType>();
10261 auto *BaseClass = cast<CXXRecordDecl>(RT->getDecl());
10262 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(BaseClass);
10263 if (auto *BaseCtor = SMOR.getMethod()) {
10264 visitSubobjectCall(Base, BaseCtor);
10268 visitClassSubobject(BaseClass, Base, 0);
10272 bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
10273 if (CSM == Sema::CXXDefaultConstructor && FD->hasInClassInitializer()) {
10274 Expr *E = FD->getInClassInitializer();
10276 // FIXME: It's a little wasteful to build and throw away a
10277 // CXXDefaultInitExpr here.
10278 // FIXME: We should have a single context note pointing at Loc, and
10279 // this location should be MD->getLocation() instead, since that's
10280 // the location where we actually use the default init expression.
10281 E = S.BuildCXXDefaultInitExpr(Loc, FD).get();
10283 ExceptSpec.CalledExpr(E);
10284 } else if (auto *RT = S.Context.getBaseElementType(FD->getType())
10285 ->getAs<RecordType>()) {
10286 visitClassSubobject(cast<CXXRecordDecl>(RT->getDecl()), FD,
10287 FD->getType().getCVRQualifiers());
10292 void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
10295 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
10296 bool IsMutable = Field && Field->isMutable();
10297 visitSubobjectCall(Subobj, lookupIn(Class, Quals, IsMutable));
10300 void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
10301 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
10302 // Note, if lookup fails, it doesn't matter what exception specification we
10303 // choose because the special member will be deleted.
10304 if (CXXMethodDecl *MD = SMOR.getMethod())
10305 ExceptSpec.CalledDecl(getSubobjectLoc(Subobj), MD);
10308 static Sema::ImplicitExceptionSpecification
10309 ComputeDefaultedSpecialMemberExceptionSpec(
10310 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, Sema::CXXSpecialMember CSM,
10311 Sema::InheritedConstructorInfo *ICI) {
10312 CXXRecordDecl *ClassDecl = MD->getParent();
10314 // C++ [except.spec]p14:
10315 // An implicitly declared special member function (Clause 12) shall have an
10316 // exception-specification. [...]
10317 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, Loc);
10318 if (ClassDecl->isInvalidDecl())
10319 return Info.ExceptSpec;
10321 // C++1z [except.spec]p7:
10322 // [Look for exceptions thrown by] a constructor selected [...] to
10323 // initialize a potentially constructed subobject,
10324 // C++1z [except.spec]p8:
10325 // The exception specification for an implicitly-declared destructor, or a
10326 // destructor without a noexcept-specifier, is potentially-throwing if and
10327 // only if any of the destructors for any of its potentially constructed
10328 // subojects is potentially throwing.
10329 // FIXME: We respect the first rule but ignore the "potentially constructed"
10330 // in the second rule to resolve a core issue (no number yet) that would have
10332 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
10333 // struct B : A {};
10334 // struct C : B { void f(); };
10335 // ... due to giving B::~B() a non-throwing exception specification.
10336 Info.visit(Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
10337 : Info.VisitAllBases);
10339 return Info.ExceptSpec;
10343 /// RAII object to register a special member as being currently declared.
10344 struct DeclaringSpecialMember {
10346 Sema::SpecialMemberDecl D;
10347 Sema::ContextRAII SavedContext;
10348 bool WasAlreadyBeingDeclared;
10350 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, Sema::CXXSpecialMember CSM)
10351 : S(S), D(RD, CSM), SavedContext(S, RD) {
10352 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(D).second;
10353 if (WasAlreadyBeingDeclared)
10354 // This almost never happens, but if it does, ensure that our cache
10355 // doesn't contain a stale result.
10356 S.SpecialMemberCache.clear();
10358 // Register a note to be produced if we encounter an error while
10359 // declaring the special member.
10360 Sema::CodeSynthesisContext Ctx;
10361 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
10362 // FIXME: We don't have a location to use here. Using the class's
10363 // location maintains the fiction that we declare all special members
10364 // with the class, but (1) it's not clear that lying about that helps our
10365 // users understand what's going on, and (2) there may be outer contexts
10366 // on the stack (some of which are relevant) and printing them exposes
10368 Ctx.PointOfInstantiation = RD->getLocation();
10370 Ctx.SpecialMember = CSM;
10371 S.pushCodeSynthesisContext(Ctx);
10374 ~DeclaringSpecialMember() {
10375 if (!WasAlreadyBeingDeclared) {
10376 S.SpecialMembersBeingDeclared.erase(D);
10377 S.popCodeSynthesisContext();
10381 /// \brief Are we already trying to declare this special member?
10382 bool isAlreadyBeingDeclared() const {
10383 return WasAlreadyBeingDeclared;
10388 void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
10389 // Look up any existing declarations, but don't trigger declaration of all
10390 // implicit special members with this name.
10391 DeclarationName Name = FD->getDeclName();
10392 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
10393 ForExternalRedeclaration);
10394 for (auto *D : FD->getParent()->lookup(Name))
10395 if (auto *Acceptable = R.getAcceptableDecl(D))
10396 R.addDecl(Acceptable);
10398 R.suppressDiagnostics();
10400 CheckFunctionDeclaration(S, FD, R, /*IsMemberSpecialization*/false);
10403 CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
10404 CXXRecordDecl *ClassDecl) {
10405 // C++ [class.ctor]p5:
10406 // A default constructor for a class X is a constructor of class X
10407 // that can be called without an argument. If there is no
10408 // user-declared constructor for class X, a default constructor is
10409 // implicitly declared. An implicitly-declared default constructor
10410 // is an inline public member of its class.
10411 assert(ClassDecl->needsImplicitDefaultConstructor() &&
10412 "Should not build implicit default constructor!");
10414 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDefaultConstructor);
10415 if (DSM.isAlreadyBeingDeclared())
10418 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
10419 CXXDefaultConstructor,
10422 // Create the actual constructor declaration.
10423 CanQualType ClassType
10424 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10425 SourceLocation ClassLoc = ClassDecl->getLocation();
10426 DeclarationName Name
10427 = Context.DeclarationNames.getCXXConstructorName(ClassType);
10428 DeclarationNameInfo NameInfo(Name, ClassLoc);
10429 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
10430 Context, ClassDecl, ClassLoc, NameInfo, /*Type*/QualType(),
10431 /*TInfo=*/nullptr, /*isExplicit=*/false, /*isInline=*/true,
10432 /*isImplicitlyDeclared=*/true, Constexpr);
10433 DefaultCon->setAccess(AS_public);
10434 DefaultCon->setDefaulted();
10436 if (getLangOpts().CUDA) {
10437 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDefaultConstructor,
10439 /* ConstRHS */ false,
10440 /* Diagnose */ false);
10443 // Build an exception specification pointing back at this constructor.
10444 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, DefaultCon);
10445 DefaultCon->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10447 // We don't need to use SpecialMemberIsTrivial here; triviality for default
10448 // constructors is easy to compute.
10449 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
10451 // Note that we have declared this constructor.
10452 ++ASTContext::NumImplicitDefaultConstructorsDeclared;
10454 Scope *S = getScopeForContext(ClassDecl);
10455 CheckImplicitSpecialMemberDeclaration(S, DefaultCon);
10457 if (ShouldDeleteSpecialMember(DefaultCon, CXXDefaultConstructor))
10458 SetDeclDeleted(DefaultCon, ClassLoc);
10461 PushOnScopeChains(DefaultCon, S, false);
10462 ClassDecl->addDecl(DefaultCon);
10467 void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
10468 CXXConstructorDecl *Constructor) {
10469 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
10470 !Constructor->doesThisDeclarationHaveABody() &&
10471 !Constructor->isDeleted()) &&
10472 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
10473 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10476 CXXRecordDecl *ClassDecl = Constructor->getParent();
10477 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
10479 SynthesizedFunctionScope Scope(*this, Constructor);
10481 // The exception specification is needed because we are defining the
10483 ResolveExceptionSpec(CurrentLocation,
10484 Constructor->getType()->castAs<FunctionProtoType>());
10485 MarkVTableUsed(CurrentLocation, ClassDecl);
10487 // Add a context note for diagnostics produced after this point.
10488 Scope.addContextNote(CurrentLocation);
10490 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
10491 Constructor->setInvalidDecl();
10495 SourceLocation Loc = Constructor->getLocEnd().isValid()
10496 ? Constructor->getLocEnd()
10497 : Constructor->getLocation();
10498 Constructor->setBody(new (Context) CompoundStmt(Loc));
10499 Constructor->markUsed(Context);
10501 if (ASTMutationListener *L = getASTMutationListener()) {
10502 L->CompletedImplicitDefinition(Constructor);
10505 DiagnoseUninitializedFields(*this, Constructor);
10508 void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
10509 // Perform any delayed checks on exception specifications.
10510 CheckDelayedMemberExceptionSpecs();
10513 /// Find or create the fake constructor we synthesize to model constructing an
10514 /// object of a derived class via a constructor of a base class.
10515 CXXConstructorDecl *
10516 Sema::findInheritingConstructor(SourceLocation Loc,
10517 CXXConstructorDecl *BaseCtor,
10518 ConstructorUsingShadowDecl *Shadow) {
10519 CXXRecordDecl *Derived = Shadow->getParent();
10520 SourceLocation UsingLoc = Shadow->getLocation();
10522 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
10523 // For now we use the name of the base class constructor as a member of the
10524 // derived class to indicate a (fake) inherited constructor name.
10525 DeclarationName Name = BaseCtor->getDeclName();
10527 // Check to see if we already have a fake constructor for this inherited
10528 // constructor call.
10529 for (NamedDecl *Ctor : Derived->lookup(Name))
10530 if (declaresSameEntity(cast<CXXConstructorDecl>(Ctor)
10531 ->getInheritedConstructor()
10534 return cast<CXXConstructorDecl>(Ctor);
10536 DeclarationNameInfo NameInfo(Name, UsingLoc);
10537 TypeSourceInfo *TInfo =
10538 Context.getTrivialTypeSourceInfo(BaseCtor->getType(), UsingLoc);
10539 FunctionProtoTypeLoc ProtoLoc =
10540 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
10542 // Check the inherited constructor is valid and find the list of base classes
10543 // from which it was inherited.
10544 InheritedConstructorInfo ICI(*this, Loc, Shadow);
10547 BaseCtor->isConstexpr() &&
10548 defaultedSpecialMemberIsConstexpr(*this, Derived, CXXDefaultConstructor,
10549 false, BaseCtor, &ICI);
10551 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
10552 Context, Derived, UsingLoc, NameInfo, TInfo->getType(), TInfo,
10553 BaseCtor->isExplicit(), /*Inline=*/true,
10554 /*ImplicitlyDeclared=*/true, Constexpr,
10555 InheritedConstructor(Shadow, BaseCtor));
10556 if (Shadow->isInvalidDecl())
10557 DerivedCtor->setInvalidDecl();
10559 // Build an unevaluated exception specification for this fake constructor.
10560 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
10561 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
10562 EPI.ExceptionSpec.Type = EST_Unevaluated;
10563 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
10564 DerivedCtor->setType(Context.getFunctionType(FPT->getReturnType(),
10565 FPT->getParamTypes(), EPI));
10567 // Build the parameter declarations.
10568 SmallVector<ParmVarDecl *, 16> ParamDecls;
10569 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
10570 TypeSourceInfo *TInfo =
10571 Context.getTrivialTypeSourceInfo(FPT->getParamType(I), UsingLoc);
10572 ParmVarDecl *PD = ParmVarDecl::Create(
10573 Context, DerivedCtor, UsingLoc, UsingLoc, /*IdentifierInfo=*/nullptr,
10574 FPT->getParamType(I), TInfo, SC_None, /*DefaultArg=*/nullptr);
10575 PD->setScopeInfo(0, I);
10577 // Ensure attributes are propagated onto parameters (this matters for
10578 // format, pass_object_size, ...).
10579 mergeDeclAttributes(PD, BaseCtor->getParamDecl(I));
10580 ParamDecls.push_back(PD);
10581 ProtoLoc.setParam(I, PD);
10584 // Set up the new constructor.
10585 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
10586 DerivedCtor->setAccess(BaseCtor->getAccess());
10587 DerivedCtor->setParams(ParamDecls);
10588 Derived->addDecl(DerivedCtor);
10590 if (ShouldDeleteSpecialMember(DerivedCtor, CXXDefaultConstructor, &ICI))
10591 SetDeclDeleted(DerivedCtor, UsingLoc);
10593 return DerivedCtor;
10596 void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
10597 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
10598 Ctor->getInheritedConstructor().getShadowDecl());
10599 ShouldDeleteSpecialMember(Ctor, CXXDefaultConstructor, &ICI,
10603 void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
10604 CXXConstructorDecl *Constructor) {
10605 CXXRecordDecl *ClassDecl = Constructor->getParent();
10606 assert(Constructor->getInheritedConstructor() &&
10607 !Constructor->doesThisDeclarationHaveABody() &&
10608 !Constructor->isDeleted());
10609 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
10612 // Initializations are performed "as if by a defaulted default constructor",
10613 // so enter the appropriate scope.
10614 SynthesizedFunctionScope Scope(*this, Constructor);
10616 // The exception specification is needed because we are defining the
10618 ResolveExceptionSpec(CurrentLocation,
10619 Constructor->getType()->castAs<FunctionProtoType>());
10620 MarkVTableUsed(CurrentLocation, ClassDecl);
10622 // Add a context note for diagnostics produced after this point.
10623 Scope.addContextNote(CurrentLocation);
10625 ConstructorUsingShadowDecl *Shadow =
10626 Constructor->getInheritedConstructor().getShadowDecl();
10627 CXXConstructorDecl *InheritedCtor =
10628 Constructor->getInheritedConstructor().getConstructor();
10630 // [class.inhctor.init]p1:
10631 // initialization proceeds as if a defaulted default constructor is used to
10632 // initialize the D object and each base class subobject from which the
10633 // constructor was inherited
10635 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
10636 CXXRecordDecl *RD = Shadow->getParent();
10637 SourceLocation InitLoc = Shadow->getLocation();
10639 // Build explicit initializers for all base classes from which the
10640 // constructor was inherited.
10641 SmallVector<CXXCtorInitializer*, 8> Inits;
10642 for (bool VBase : {false, true}) {
10643 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
10644 if (B.isVirtual() != VBase)
10647 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
10651 auto BaseCtor = ICI.findConstructorForBase(BaseRD, InheritedCtor);
10652 if (!BaseCtor.first)
10655 MarkFunctionReferenced(CurrentLocation, BaseCtor.first);
10656 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
10657 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
10659 auto *TInfo = Context.getTrivialTypeSourceInfo(B.getType(), InitLoc);
10660 Inits.push_back(new (Context) CXXCtorInitializer(
10661 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
10662 SourceLocation()));
10666 // We now proceed as if for a defaulted default constructor, with the relevant
10667 // initializers replaced.
10669 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Inits)) {
10670 Constructor->setInvalidDecl();
10674 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
10675 Constructor->markUsed(Context);
10677 if (ASTMutationListener *L = getASTMutationListener()) {
10678 L->CompletedImplicitDefinition(Constructor);
10681 DiagnoseUninitializedFields(*this, Constructor);
10684 CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
10685 // C++ [class.dtor]p2:
10686 // If a class has no user-declared destructor, a destructor is
10687 // declared implicitly. An implicitly-declared destructor is an
10688 // inline public member of its class.
10689 assert(ClassDecl->needsImplicitDestructor());
10691 DeclaringSpecialMember DSM(*this, ClassDecl, CXXDestructor);
10692 if (DSM.isAlreadyBeingDeclared())
10695 // Create the actual destructor declaration.
10696 CanQualType ClassType
10697 = Context.getCanonicalType(Context.getTypeDeclType(ClassDecl));
10698 SourceLocation ClassLoc = ClassDecl->getLocation();
10699 DeclarationName Name
10700 = Context.DeclarationNames.getCXXDestructorName(ClassType);
10701 DeclarationNameInfo NameInfo(Name, ClassLoc);
10702 CXXDestructorDecl *Destructor
10703 = CXXDestructorDecl::Create(Context, ClassDecl, ClassLoc, NameInfo,
10704 QualType(), nullptr, /*isInline=*/true,
10705 /*isImplicitlyDeclared=*/true);
10706 Destructor->setAccess(AS_public);
10707 Destructor->setDefaulted();
10709 if (getLangOpts().CUDA) {
10710 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXDestructor,
10712 /* ConstRHS */ false,
10713 /* Diagnose */ false);
10716 // Build an exception specification pointing back at this destructor.
10717 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(*this, Destructor);
10718 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10720 // We don't need to use SpecialMemberIsTrivial here; triviality for
10721 // destructors is easy to compute.
10722 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
10724 // Note that we have declared this destructor.
10725 ++ASTContext::NumImplicitDestructorsDeclared;
10727 Scope *S = getScopeForContext(ClassDecl);
10728 CheckImplicitSpecialMemberDeclaration(S, Destructor);
10730 // We can't check whether an implicit destructor is deleted before we complete
10731 // the definition of the class, because its validity depends on the alignment
10732 // of the class. We'll check this from ActOnFields once the class is complete.
10733 if (ClassDecl->isCompleteDefinition() &&
10734 ShouldDeleteSpecialMember(Destructor, CXXDestructor))
10735 SetDeclDeleted(Destructor, ClassLoc);
10737 // Introduce this destructor into its scope.
10739 PushOnScopeChains(Destructor, S, false);
10740 ClassDecl->addDecl(Destructor);
10745 void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
10746 CXXDestructorDecl *Destructor) {
10747 assert((Destructor->isDefaulted() &&
10748 !Destructor->doesThisDeclarationHaveABody() &&
10749 !Destructor->isDeleted()) &&
10750 "DefineImplicitDestructor - call it for implicit default dtor");
10751 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
10754 CXXRecordDecl *ClassDecl = Destructor->getParent();
10755 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
10757 SynthesizedFunctionScope Scope(*this, Destructor);
10759 // The exception specification is needed because we are defining the
10761 ResolveExceptionSpec(CurrentLocation,
10762 Destructor->getType()->castAs<FunctionProtoType>());
10763 MarkVTableUsed(CurrentLocation, ClassDecl);
10765 // Add a context note for diagnostics produced after this point.
10766 Scope.addContextNote(CurrentLocation);
10768 MarkBaseAndMemberDestructorsReferenced(Destructor->getLocation(),
10769 Destructor->getParent());
10771 if (CheckDestructor(Destructor)) {
10772 Destructor->setInvalidDecl();
10776 SourceLocation Loc = Destructor->getLocEnd().isValid()
10777 ? Destructor->getLocEnd()
10778 : Destructor->getLocation();
10779 Destructor->setBody(new (Context) CompoundStmt(Loc));
10780 Destructor->markUsed(Context);
10782 if (ASTMutationListener *L = getASTMutationListener()) {
10783 L->CompletedImplicitDefinition(Destructor);
10787 /// \brief Perform any semantic analysis which needs to be delayed until all
10788 /// pending class member declarations have been parsed.
10789 void Sema::ActOnFinishCXXMemberDecls() {
10790 // If the context is an invalid C++ class, just suppress these checks.
10791 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(CurContext)) {
10792 if (Record->isInvalidDecl()) {
10793 DelayedDefaultedMemberExceptionSpecs.clear();
10794 DelayedExceptionSpecChecks.clear();
10797 checkForMultipleExportedDefaultConstructors(*this, Record);
10801 void Sema::ActOnFinishCXXNonNestedClass(Decl *D) {
10802 referenceDLLExportedClassMethods();
10805 void Sema::referenceDLLExportedClassMethods() {
10806 if (!DelayedDllExportClasses.empty()) {
10807 // Calling ReferenceDllExportedMethods might cause the current function to
10808 // be called again, so use a local copy of DelayedDllExportClasses.
10809 SmallVector<CXXRecordDecl *, 4> WorkList;
10810 std::swap(DelayedDllExportClasses, WorkList);
10811 for (CXXRecordDecl *Class : WorkList)
10812 ReferenceDllExportedMethods(*this, Class);
10816 void Sema::AdjustDestructorExceptionSpec(CXXRecordDecl *ClassDecl,
10817 CXXDestructorDecl *Destructor) {
10818 assert(getLangOpts().CPlusPlus11 &&
10819 "adjusting dtor exception specs was introduced in c++11");
10821 // C++11 [class.dtor]p3:
10822 // A declaration of a destructor that does not have an exception-
10823 // specification is implicitly considered to have the same exception-
10824 // specification as an implicit declaration.
10825 const FunctionProtoType *DtorType = Destructor->getType()->
10826 getAs<FunctionProtoType>();
10827 if (DtorType->hasExceptionSpec())
10830 // Replace the destructor's type, building off the existing one. Fortunately,
10831 // the only thing of interest in the destructor type is its extended info.
10832 // The return and arguments are fixed.
10833 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
10834 EPI.ExceptionSpec.Type = EST_Unevaluated;
10835 EPI.ExceptionSpec.SourceDecl = Destructor;
10836 Destructor->setType(Context.getFunctionType(Context.VoidTy, None, EPI));
10838 // FIXME: If the destructor has a body that could throw, and the newly created
10839 // spec doesn't allow exceptions, we should emit a warning, because this
10840 // change in behavior can break conforming C++03 programs at runtime.
10841 // However, we don't have a body or an exception specification yet, so it
10842 // needs to be done somewhere else.
10846 /// \brief An abstract base class for all helper classes used in building the
10847 // copy/move operators. These classes serve as factory functions and help us
10848 // avoid using the same Expr* in the AST twice.
10849 class ExprBuilder {
10850 ExprBuilder(const ExprBuilder&) = delete;
10851 ExprBuilder &operator=(const ExprBuilder&) = delete;
10854 static Expr *assertNotNull(Expr *E) {
10855 assert(E && "Expression construction must not fail.");
10861 virtual ~ExprBuilder() {}
10863 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
10866 class RefBuilder: public ExprBuilder {
10871 Expr *build(Sema &S, SourceLocation Loc) const override {
10872 return assertNotNull(S.BuildDeclRefExpr(Var, VarType, VK_LValue, Loc).get());
10875 RefBuilder(VarDecl *Var, QualType VarType)
10876 : Var(Var), VarType(VarType) {}
10879 class ThisBuilder: public ExprBuilder {
10881 Expr *build(Sema &S, SourceLocation Loc) const override {
10882 return assertNotNull(S.ActOnCXXThis(Loc).getAs<Expr>());
10886 class CastBuilder: public ExprBuilder {
10887 const ExprBuilder &Builder;
10889 ExprValueKind Kind;
10890 const CXXCastPath &Path;
10893 Expr *build(Sema &S, SourceLocation Loc) const override {
10894 return assertNotNull(S.ImpCastExprToType(Builder.build(S, Loc), Type,
10895 CK_UncheckedDerivedToBase, Kind,
10899 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
10900 const CXXCastPath &Path)
10901 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
10904 class DerefBuilder: public ExprBuilder {
10905 const ExprBuilder &Builder;
10908 Expr *build(Sema &S, SourceLocation Loc) const override {
10909 return assertNotNull(
10910 S.CreateBuiltinUnaryOp(Loc, UO_Deref, Builder.build(S, Loc)).get());
10913 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10916 class MemberBuilder: public ExprBuilder {
10917 const ExprBuilder &Builder;
10921 LookupResult &MemberLookup;
10924 Expr *build(Sema &S, SourceLocation Loc) const override {
10925 return assertNotNull(S.BuildMemberReferenceExpr(
10926 Builder.build(S, Loc), Type, Loc, IsArrow, SS, SourceLocation(),
10927 nullptr, MemberLookup, nullptr, nullptr).get());
10930 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
10931 LookupResult &MemberLookup)
10932 : Builder(Builder), Type(Type), IsArrow(IsArrow),
10933 MemberLookup(MemberLookup) {}
10936 class MoveCastBuilder: public ExprBuilder {
10937 const ExprBuilder &Builder;
10940 Expr *build(Sema &S, SourceLocation Loc) const override {
10941 return assertNotNull(CastForMoving(S, Builder.build(S, Loc)));
10944 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10947 class LvalueConvBuilder: public ExprBuilder {
10948 const ExprBuilder &Builder;
10951 Expr *build(Sema &S, SourceLocation Loc) const override {
10952 return assertNotNull(
10953 S.DefaultLvalueConversion(Builder.build(S, Loc)).get());
10956 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
10959 class SubscriptBuilder: public ExprBuilder {
10960 const ExprBuilder &Base;
10961 const ExprBuilder &Index;
10964 Expr *build(Sema &S, SourceLocation Loc) const override {
10965 return assertNotNull(S.CreateBuiltinArraySubscriptExpr(
10966 Base.build(S, Loc), Loc, Index.build(S, Loc), Loc).get());
10969 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
10970 : Base(Base), Index(Index) {}
10973 } // end anonymous namespace
10975 /// When generating a defaulted copy or move assignment operator, if a field
10976 /// should be copied with __builtin_memcpy rather than via explicit assignments,
10977 /// do so. This optimization only applies for arrays of scalars, and for arrays
10978 /// of class type where the selected copy/move-assignment operator is trivial.
10980 buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
10981 const ExprBuilder &ToB, const ExprBuilder &FromB) {
10982 // Compute the size of the memory buffer to be copied.
10983 QualType SizeType = S.Context.getSizeType();
10984 llvm::APInt Size(S.Context.getTypeSize(SizeType),
10985 S.Context.getTypeSizeInChars(T).getQuantity());
10987 // Take the address of the field references for "from" and "to". We
10988 // directly construct UnaryOperators here because semantic analysis
10989 // does not permit us to take the address of an xvalue.
10990 Expr *From = FromB.build(S, Loc);
10991 From = new (S.Context) UnaryOperator(From, UO_AddrOf,
10992 S.Context.getPointerType(From->getType()),
10993 VK_RValue, OK_Ordinary, Loc);
10994 Expr *To = ToB.build(S, Loc);
10995 To = new (S.Context) UnaryOperator(To, UO_AddrOf,
10996 S.Context.getPointerType(To->getType()),
10997 VK_RValue, OK_Ordinary, Loc);
10999 const Type *E = T->getBaseElementTypeUnsafe();
11000 bool NeedsCollectableMemCpy =
11001 E->isRecordType() && E->getAs<RecordType>()->getDecl()->hasObjectMember();
11003 // Create a reference to the __builtin_objc_memmove_collectable function
11004 StringRef MemCpyName = NeedsCollectableMemCpy ?
11005 "__builtin_objc_memmove_collectable" :
11006 "__builtin_memcpy";
11007 LookupResult R(S, &S.Context.Idents.get(MemCpyName), Loc,
11008 Sema::LookupOrdinaryName);
11009 S.LookupName(R, S.TUScope, true);
11011 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
11013 // Something went horribly wrong earlier, and we will have complained
11015 return StmtError();
11017 ExprResult MemCpyRef = S.BuildDeclRefExpr(MemCpy, S.Context.BuiltinFnTy,
11018 VK_RValue, Loc, nullptr);
11019 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
11021 Expr *CallArgs[] = {
11022 To, From, IntegerLiteral::Create(S.Context, Size, SizeType, Loc)
11024 ExprResult Call = S.ActOnCallExpr(/*Scope=*/nullptr, MemCpyRef.get(),
11025 Loc, CallArgs, Loc);
11027 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
11028 return Call.getAs<Stmt>();
11031 /// \brief Builds a statement that copies/moves the given entity from \p From to
11034 /// This routine is used to copy/move the members of a class with an
11035 /// implicitly-declared copy/move assignment operator. When the entities being
11036 /// copied are arrays, this routine builds for loops to copy them.
11038 /// \param S The Sema object used for type-checking.
11040 /// \param Loc The location where the implicit copy/move is being generated.
11042 /// \param T The type of the expressions being copied/moved. Both expressions
11043 /// must have this type.
11045 /// \param To The expression we are copying/moving to.
11047 /// \param From The expression we are copying/moving from.
11049 /// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
11050 /// Otherwise, it's a non-static member subobject.
11052 /// \param Copying Whether we're copying or moving.
11054 /// \param Depth Internal parameter recording the depth of the recursion.
11056 /// \returns A statement or a loop that copies the expressions, or StmtResult(0)
11057 /// if a memcpy should be used instead.
11059 buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
11060 const ExprBuilder &To, const ExprBuilder &From,
11061 bool CopyingBaseSubobject, bool Copying,
11062 unsigned Depth = 0) {
11063 // C++11 [class.copy]p28:
11064 // Each subobject is assigned in the manner appropriate to its type:
11066 // - if the subobject is of class type, as if by a call to operator= with
11067 // the subobject as the object expression and the corresponding
11068 // subobject of x as a single function argument (as if by explicit
11069 // qualification; that is, ignoring any possible virtual overriding
11070 // functions in more derived classes);
11072 // C++03 [class.copy]p13:
11073 // - if the subobject is of class type, the copy assignment operator for
11074 // the class is used (as if by explicit qualification; that is,
11075 // ignoring any possible virtual overriding functions in more derived
11077 if (const RecordType *RecordTy = T->getAs<RecordType>()) {
11078 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RecordTy->getDecl());
11080 // Look for operator=.
11081 DeclarationName Name
11082 = S.Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11083 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
11084 S.LookupQualifiedName(OpLookup, ClassDecl, false);
11086 // Prior to C++11, filter out any result that isn't a copy/move-assignment
11088 if (!S.getLangOpts().CPlusPlus11) {
11089 LookupResult::Filter F = OpLookup.makeFilter();
11090 while (F.hasNext()) {
11091 NamedDecl *D = F.next();
11092 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D))
11093 if (Method->isCopyAssignmentOperator() ||
11094 (!Copying && Method->isMoveAssignmentOperator()))
11102 // Suppress the protected check (C++ [class.protected]) for each of the
11103 // assignment operators we found. This strange dance is required when
11104 // we're assigning via a base classes's copy-assignment operator. To
11105 // ensure that we're getting the right base class subobject (without
11106 // ambiguities), we need to cast "this" to that subobject type; to
11107 // ensure that we don't go through the virtual call mechanism, we need
11108 // to qualify the operator= name with the base class (see below). However,
11109 // this means that if the base class has a protected copy assignment
11110 // operator, the protected member access check will fail. So, we
11111 // rewrite "protected" access to "public" access in this case, since we
11112 // know by construction that we're calling from a derived class.
11113 if (CopyingBaseSubobject) {
11114 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
11116 if (L.getAccess() == AS_protected)
11117 L.setAccess(AS_public);
11121 // Create the nested-name-specifier that will be used to qualify the
11122 // reference to operator=; this is required to suppress the virtual
11125 const Type *CanonicalT = S.Context.getCanonicalType(T.getTypePtr());
11126 SS.MakeTrivial(S.Context,
11127 NestedNameSpecifier::Create(S.Context, nullptr, false,
11131 // Create the reference to operator=.
11132 ExprResult OpEqualRef
11133 = S.BuildMemberReferenceExpr(To.build(S, Loc), T, Loc, /*isArrow=*/false,
11134 SS, /*TemplateKWLoc=*/SourceLocation(),
11135 /*FirstQualifierInScope=*/nullptr,
11137 /*TemplateArgs=*/nullptr, /*S*/nullptr,
11138 /*SuppressQualifierCheck=*/true);
11139 if (OpEqualRef.isInvalid())
11140 return StmtError();
11142 // Build the call to the assignment operator.
11144 Expr *FromInst = From.build(S, Loc);
11145 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/nullptr,
11146 OpEqualRef.getAs<Expr>(),
11147 Loc, FromInst, Loc);
11148 if (Call.isInvalid())
11149 return StmtError();
11151 // If we built a call to a trivial 'operator=' while copying an array,
11152 // bail out. We'll replace the whole shebang with a memcpy.
11153 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Call.get());
11154 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
11155 return StmtResult((Stmt*)nullptr);
11157 // Convert to an expression-statement, and clean up any produced
11159 return S.ActOnExprStmt(Call);
11162 // - if the subobject is of scalar type, the built-in assignment
11163 // operator is used.
11164 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
11166 ExprResult Assignment = S.CreateBuiltinBinOp(
11167 Loc, BO_Assign, To.build(S, Loc), From.build(S, Loc));
11168 if (Assignment.isInvalid())
11169 return StmtError();
11170 return S.ActOnExprStmt(Assignment);
11173 // - if the subobject is an array, each element is assigned, in the
11174 // manner appropriate to the element type;
11176 // Construct a loop over the array bounds, e.g.,
11178 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
11180 // that will copy each of the array elements.
11181 QualType SizeType = S.Context.getSizeType();
11183 // Create the iteration variable.
11184 IdentifierInfo *IterationVarName = nullptr;
11186 SmallString<8> Str;
11187 llvm::raw_svector_ostream OS(Str);
11188 OS << "__i" << Depth;
11189 IterationVarName = &S.Context.Idents.get(OS.str());
11191 VarDecl *IterationVar = VarDecl::Create(S.Context, S.CurContext, Loc, Loc,
11192 IterationVarName, SizeType,
11193 S.Context.getTrivialTypeSourceInfo(SizeType, Loc),
11196 // Initialize the iteration variable to zero.
11197 llvm::APInt Zero(S.Context.getTypeSize(SizeType), 0);
11198 IterationVar->setInit(IntegerLiteral::Create(S.Context, Zero, SizeType, Loc));
11200 // Creates a reference to the iteration variable.
11201 RefBuilder IterationVarRef(IterationVar, SizeType);
11202 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
11204 // Create the DeclStmt that holds the iteration variable.
11205 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
11207 // Subscript the "from" and "to" expressions with the iteration variable.
11208 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
11209 MoveCastBuilder FromIndexMove(FromIndexCopy);
11210 const ExprBuilder *FromIndex;
11212 FromIndex = &FromIndexCopy;
11214 FromIndex = &FromIndexMove;
11216 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
11218 // Build the copy/move for an individual element of the array.
11220 buildSingleCopyAssignRecursively(S, Loc, ArrayTy->getElementType(),
11221 ToIndex, *FromIndex, CopyingBaseSubobject,
11222 Copying, Depth + 1);
11223 // Bail out if copying fails or if we determined that we should use memcpy.
11224 if (Copy.isInvalid() || !Copy.get())
11227 // Create the comparison against the array bound.
11229 = ArrayTy->getSize().zextOrTrunc(S.Context.getTypeSize(SizeType));
11231 = new (S.Context) BinaryOperator(IterationVarRefRVal.build(S, Loc),
11232 IntegerLiteral::Create(S.Context, Upper, SizeType, Loc),
11233 BO_NE, S.Context.BoolTy,
11234 VK_RValue, OK_Ordinary, Loc, FPOptions());
11236 // Create the pre-increment of the iteration variable.
11238 = new (S.Context) UnaryOperator(IterationVarRef.build(S, Loc), UO_PreInc,
11239 SizeType, VK_LValue, OK_Ordinary, Loc);
11241 // Construct the loop that copies all elements of this array.
11242 return S.ActOnForStmt(
11243 Loc, Loc, InitStmt,
11244 S.ActOnCondition(nullptr, Loc, Comparison, Sema::ConditionKind::Boolean),
11245 S.MakeFullDiscardedValueExpr(Increment), Loc, Copy.get());
11249 buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
11250 const ExprBuilder &To, const ExprBuilder &From,
11251 bool CopyingBaseSubobject, bool Copying) {
11252 // Maybe we should use a memcpy?
11253 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
11254 T.isTriviallyCopyableType(S.Context))
11255 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11257 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
11258 CopyingBaseSubobject,
11261 // If we ended up picking a trivial assignment operator for an array of a
11262 // non-trivially-copyable class type, just emit a memcpy.
11263 if (!Result.isInvalid() && !Result.get())
11264 return buildMemcpyForAssignmentOp(S, Loc, T, To, From);
11269 CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
11270 // Note: The following rules are largely analoguous to the copy
11271 // constructor rules. Note that virtual bases are not taken into account
11272 // for determining the argument type of the operator. Note also that
11273 // operators taking an object instead of a reference are allowed.
11274 assert(ClassDecl->needsImplicitCopyAssignment());
11276 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyAssignment);
11277 if (DSM.isAlreadyBeingDeclared())
11280 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11281 QualType RetType = Context.getLValueReferenceType(ArgType);
11282 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
11284 ArgType = ArgType.withConst();
11285 ArgType = Context.getLValueReferenceType(ArgType);
11287 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11291 // An implicitly-declared copy assignment operator is an inline public
11292 // member of its class.
11293 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11294 SourceLocation ClassLoc = ClassDecl->getLocation();
11295 DeclarationNameInfo NameInfo(Name, ClassLoc);
11296 CXXMethodDecl *CopyAssignment =
11297 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11298 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11299 /*isInline=*/true, Constexpr, SourceLocation());
11300 CopyAssignment->setAccess(AS_public);
11301 CopyAssignment->setDefaulted();
11302 CopyAssignment->setImplicit();
11304 if (getLangOpts().CUDA) {
11305 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyAssignment,
11307 /* ConstRHS */ Const,
11308 /* Diagnose */ false);
11311 // Build an exception specification pointing back at this member.
11312 FunctionProtoType::ExtProtoInfo EPI =
11313 getImplicitMethodEPI(*this, CopyAssignment);
11314 CopyAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11316 // Add the parameter to the operator.
11317 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyAssignment,
11318 ClassLoc, ClassLoc,
11319 /*Id=*/nullptr, ArgType,
11320 /*TInfo=*/nullptr, SC_None,
11322 CopyAssignment->setParams(FromParam);
11324 CopyAssignment->setTrivial(
11325 ClassDecl->needsOverloadResolutionForCopyAssignment()
11326 ? SpecialMemberIsTrivial(CopyAssignment, CXXCopyAssignment)
11327 : ClassDecl->hasTrivialCopyAssignment());
11329 // Note that we have added this copy-assignment operator.
11330 ++ASTContext::NumImplicitCopyAssignmentOperatorsDeclared;
11332 Scope *S = getScopeForContext(ClassDecl);
11333 CheckImplicitSpecialMemberDeclaration(S, CopyAssignment);
11335 if (ShouldDeleteSpecialMember(CopyAssignment, CXXCopyAssignment))
11336 SetDeclDeleted(CopyAssignment, ClassLoc);
11339 PushOnScopeChains(CopyAssignment, S, false);
11340 ClassDecl->addDecl(CopyAssignment);
11342 return CopyAssignment;
11345 /// Diagnose an implicit copy operation for a class which is odr-used, but
11346 /// which is deprecated because the class has a user-declared copy constructor,
11347 /// copy assignment operator, or destructor.
11348 static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
11349 assert(CopyOp->isImplicit());
11351 CXXRecordDecl *RD = CopyOp->getParent();
11352 CXXMethodDecl *UserDeclaredOperation = nullptr;
11354 // In Microsoft mode, assignment operations don't affect constructors and
11356 if (RD->hasUserDeclaredDestructor()) {
11357 UserDeclaredOperation = RD->getDestructor();
11358 } else if (!isa<CXXConstructorDecl>(CopyOp) &&
11359 RD->hasUserDeclaredCopyConstructor() &&
11360 !S.getLangOpts().MSVCCompat) {
11361 // Find any user-declared copy constructor.
11362 for (auto *I : RD->ctors()) {
11363 if (I->isCopyConstructor()) {
11364 UserDeclaredOperation = I;
11368 assert(UserDeclaredOperation);
11369 } else if (isa<CXXConstructorDecl>(CopyOp) &&
11370 RD->hasUserDeclaredCopyAssignment() &&
11371 !S.getLangOpts().MSVCCompat) {
11372 // Find any user-declared move assignment operator.
11373 for (auto *I : RD->methods()) {
11374 if (I->isCopyAssignmentOperator()) {
11375 UserDeclaredOperation = I;
11379 assert(UserDeclaredOperation);
11382 if (UserDeclaredOperation) {
11383 S.Diag(UserDeclaredOperation->getLocation(),
11384 diag::warn_deprecated_copy_operation)
11385 << RD << /*copy assignment*/!isa<CXXConstructorDecl>(CopyOp)
11386 << /*destructor*/isa<CXXDestructorDecl>(UserDeclaredOperation);
11390 void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
11391 CXXMethodDecl *CopyAssignOperator) {
11392 assert((CopyAssignOperator->isDefaulted() &&
11393 CopyAssignOperator->isOverloadedOperator() &&
11394 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
11395 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
11396 !CopyAssignOperator->isDeleted()) &&
11397 "DefineImplicitCopyAssignment called for wrong function");
11398 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
11401 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
11402 if (ClassDecl->isInvalidDecl()) {
11403 CopyAssignOperator->setInvalidDecl();
11407 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
11409 // The exception specification is needed because we are defining the
11411 ResolveExceptionSpec(CurrentLocation,
11412 CopyAssignOperator->getType()->castAs<FunctionProtoType>());
11414 // Add a context note for diagnostics produced after this point.
11415 Scope.addContextNote(CurrentLocation);
11417 // C++11 [class.copy]p18:
11418 // The [definition of an implicitly declared copy assignment operator] is
11419 // deprecated if the class has a user-declared copy constructor or a
11420 // user-declared destructor.
11421 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
11422 diagnoseDeprecatedCopyOperation(*this, CopyAssignOperator);
11424 // C++0x [class.copy]p30:
11425 // The implicitly-defined or explicitly-defaulted copy assignment operator
11426 // for a non-union class X performs memberwise copy assignment of its
11427 // subobjects. The direct base classes of X are assigned first, in the
11428 // order of their declaration in the base-specifier-list, and then the
11429 // immediate non-static data members of X are assigned, in the order in
11430 // which they were declared in the class definition.
11432 // The statements that form the synthesized function body.
11433 SmallVector<Stmt*, 8> Statements;
11435 // The parameter for the "other" object, which we are copying from.
11436 ParmVarDecl *Other = CopyAssignOperator->getParamDecl(0);
11437 Qualifiers OtherQuals = Other->getType().getQualifiers();
11438 QualType OtherRefType = Other->getType();
11439 if (const LValueReferenceType *OtherRef
11440 = OtherRefType->getAs<LValueReferenceType>()) {
11441 OtherRefType = OtherRef->getPointeeType();
11442 OtherQuals = OtherRefType.getQualifiers();
11445 // Our location for everything implicitly-generated.
11446 SourceLocation Loc = CopyAssignOperator->getLocEnd().isValid()
11447 ? CopyAssignOperator->getLocEnd()
11448 : CopyAssignOperator->getLocation();
11450 // Builds a DeclRefExpr for the "other" object.
11451 RefBuilder OtherRef(Other, OtherRefType);
11453 // Builds the "this" pointer.
11456 // Assign base classes.
11457 bool Invalid = false;
11458 for (auto &Base : ClassDecl->bases()) {
11459 // Form the assignment:
11460 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
11461 QualType BaseType = Base.getType().getUnqualifiedType();
11462 if (!BaseType->isRecordType()) {
11467 CXXCastPath BasePath;
11468 BasePath.push_back(&Base);
11470 // Construct the "from" expression, which is an implicit cast to the
11471 // appropriately-qualified base type.
11472 CastBuilder From(OtherRef, Context.getQualifiedType(BaseType, OtherQuals),
11473 VK_LValue, BasePath);
11475 // Dereference "this".
11476 DerefBuilder DerefThis(This);
11477 CastBuilder To(DerefThis,
11478 Context.getCVRQualifiedType(
11479 BaseType, CopyAssignOperator->getTypeQualifiers()),
11480 VK_LValue, BasePath);
11483 StmtResult Copy = buildSingleCopyAssign(*this, Loc, BaseType,
11485 /*CopyingBaseSubobject=*/true,
11487 if (Copy.isInvalid()) {
11488 CopyAssignOperator->setInvalidDecl();
11492 // Success! Record the copy.
11493 Statements.push_back(Copy.getAs<Expr>());
11496 // Assign non-static members.
11497 for (auto *Field : ClassDecl->fields()) {
11498 // FIXME: We should form some kind of AST representation for the implied
11499 // memcpy in a union copy operation.
11500 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11503 if (Field->isInvalidDecl()) {
11508 // Check for members of reference type; we can't copy those.
11509 if (Field->getType()->isReferenceType()) {
11510 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11511 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11512 Diag(Field->getLocation(), diag::note_declared_at);
11517 // Check for members of const-qualified, non-class type.
11518 QualType BaseType = Context.getBaseElementType(Field->getType());
11519 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11520 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11521 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11522 Diag(Field->getLocation(), diag::note_declared_at);
11527 // Suppress assigning zero-width bitfields.
11528 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11531 QualType FieldType = Field->getType().getNonReferenceType();
11532 if (FieldType->isIncompleteArrayType()) {
11533 assert(ClassDecl->hasFlexibleArrayMember() &&
11534 "Incomplete array type is not valid");
11538 // Build references to the field in the object we're copying from and to.
11539 CXXScopeSpec SS; // Intentionally empty
11540 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11542 MemberLookup.addDecl(Field);
11543 MemberLookup.resolveKind();
11545 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
11547 MemberBuilder To(This, getCurrentThisType(), /*IsArrow=*/true, MemberLookup);
11549 // Build the copy of this field.
11550 StmtResult Copy = buildSingleCopyAssign(*this, Loc, FieldType,
11552 /*CopyingBaseSubobject=*/false,
11554 if (Copy.isInvalid()) {
11555 CopyAssignOperator->setInvalidDecl();
11559 // Success! Record the copy.
11560 Statements.push_back(Copy.getAs<Stmt>());
11564 // Add a "return *this;"
11565 ExprResult ThisObj = CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11567 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11568 if (Return.isInvalid())
11571 Statements.push_back(Return.getAs<Stmt>());
11575 CopyAssignOperator->setInvalidDecl();
11581 CompoundScopeRAII CompoundScope(*this);
11582 Body = ActOnCompoundStmt(Loc, Loc, Statements,
11583 /*isStmtExpr=*/false);
11584 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11586 CopyAssignOperator->setBody(Body.getAs<Stmt>());
11587 CopyAssignOperator->markUsed(Context);
11589 if (ASTMutationListener *L = getASTMutationListener()) {
11590 L->CompletedImplicitDefinition(CopyAssignOperator);
11594 CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
11595 assert(ClassDecl->needsImplicitMoveAssignment());
11597 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveAssignment);
11598 if (DSM.isAlreadyBeingDeclared())
11601 // Note: The following rules are largely analoguous to the move
11602 // constructor rules.
11604 QualType ArgType = Context.getTypeDeclType(ClassDecl);
11605 QualType RetType = Context.getLValueReferenceType(ArgType);
11606 ArgType = Context.getRValueReferenceType(ArgType);
11608 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11612 // An implicitly-declared move assignment operator is an inline public
11613 // member of its class.
11614 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(OO_Equal);
11615 SourceLocation ClassLoc = ClassDecl->getLocation();
11616 DeclarationNameInfo NameInfo(Name, ClassLoc);
11617 CXXMethodDecl *MoveAssignment =
11618 CXXMethodDecl::Create(Context, ClassDecl, ClassLoc, NameInfo, QualType(),
11619 /*TInfo=*/nullptr, /*StorageClass=*/SC_None,
11620 /*isInline=*/true, Constexpr, SourceLocation());
11621 MoveAssignment->setAccess(AS_public);
11622 MoveAssignment->setDefaulted();
11623 MoveAssignment->setImplicit();
11625 if (getLangOpts().CUDA) {
11626 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveAssignment,
11628 /* ConstRHS */ false,
11629 /* Diagnose */ false);
11632 // Build an exception specification pointing back at this member.
11633 FunctionProtoType::ExtProtoInfo EPI =
11634 getImplicitMethodEPI(*this, MoveAssignment);
11635 MoveAssignment->setType(Context.getFunctionType(RetType, ArgType, EPI));
11637 // Add the parameter to the operator.
11638 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveAssignment,
11639 ClassLoc, ClassLoc,
11640 /*Id=*/nullptr, ArgType,
11641 /*TInfo=*/nullptr, SC_None,
11643 MoveAssignment->setParams(FromParam);
11645 MoveAssignment->setTrivial(
11646 ClassDecl->needsOverloadResolutionForMoveAssignment()
11647 ? SpecialMemberIsTrivial(MoveAssignment, CXXMoveAssignment)
11648 : ClassDecl->hasTrivialMoveAssignment());
11650 // Note that we have added this copy-assignment operator.
11651 ++ASTContext::NumImplicitMoveAssignmentOperatorsDeclared;
11653 Scope *S = getScopeForContext(ClassDecl);
11654 CheckImplicitSpecialMemberDeclaration(S, MoveAssignment);
11656 if (ShouldDeleteSpecialMember(MoveAssignment, CXXMoveAssignment)) {
11657 ClassDecl->setImplicitMoveAssignmentIsDeleted();
11658 SetDeclDeleted(MoveAssignment, ClassLoc);
11662 PushOnScopeChains(MoveAssignment, S, false);
11663 ClassDecl->addDecl(MoveAssignment);
11665 return MoveAssignment;
11668 /// Check if we're implicitly defining a move assignment operator for a class
11669 /// with virtual bases. Such a move assignment might move-assign the virtual
11670 /// base multiple times.
11671 static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
11672 SourceLocation CurrentLocation) {
11673 assert(!Class->isDependentContext() && "should not define dependent move");
11675 // Only a virtual base could get implicitly move-assigned multiple times.
11676 // Only a non-trivial move assignment can observe this. We only want to
11677 // diagnose if we implicitly define an assignment operator that assigns
11678 // two base classes, both of which move-assign the same virtual base.
11679 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
11680 Class->getNumBases() < 2)
11683 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
11684 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
11687 for (auto &BI : Class->bases()) {
11688 Worklist.push_back(&BI);
11689 while (!Worklist.empty()) {
11690 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
11691 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
11693 // If the base has no non-trivial move assignment operators,
11694 // we don't care about moves from it.
11695 if (!Base->hasNonTrivialMoveAssignment())
11698 // If there's nothing virtual here, skip it.
11699 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
11702 // If we're not actually going to call a move assignment for this base,
11703 // or the selected move assignment is trivial, skip it.
11704 Sema::SpecialMemberOverloadResult SMOR =
11705 S.LookupSpecialMember(Base, Sema::CXXMoveAssignment,
11706 /*ConstArg*/false, /*VolatileArg*/false,
11707 /*RValueThis*/true, /*ConstThis*/false,
11708 /*VolatileThis*/false);
11709 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
11710 !SMOR.getMethod()->isMoveAssignmentOperator())
11713 if (BaseSpec->isVirtual()) {
11714 // We're going to move-assign this virtual base, and its move
11715 // assignment operator is not trivial. If this can happen for
11716 // multiple distinct direct bases of Class, diagnose it. (If it
11717 // only happens in one base, we'll diagnose it when synthesizing
11718 // that base class's move assignment operator.)
11719 CXXBaseSpecifier *&Existing =
11720 VBases.insert(std::make_pair(Base->getCanonicalDecl(), &BI))
11722 if (Existing && Existing != &BI) {
11723 S.Diag(CurrentLocation, diag::warn_vbase_moved_multiple_times)
11725 S.Diag(Existing->getLocStart(), diag::note_vbase_moved_here)
11726 << (Base->getCanonicalDecl() ==
11727 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11728 << Base << Existing->getType() << Existing->getSourceRange();
11729 S.Diag(BI.getLocStart(), diag::note_vbase_moved_here)
11730 << (Base->getCanonicalDecl() ==
11731 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
11732 << Base << BI.getType() << BaseSpec->getSourceRange();
11734 // Only diagnose each vbase once.
11735 Existing = nullptr;
11738 // Only walk over bases that have defaulted move assignment operators.
11739 // We assume that any user-provided move assignment operator handles
11740 // the multiple-moves-of-vbase case itself somehow.
11741 if (!SMOR.getMethod()->isDefaulted())
11744 // We're going to move the base classes of Base. Add them to the list.
11745 for (auto &BI : Base->bases())
11746 Worklist.push_back(&BI);
11752 void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
11753 CXXMethodDecl *MoveAssignOperator) {
11754 assert((MoveAssignOperator->isDefaulted() &&
11755 MoveAssignOperator->isOverloadedOperator() &&
11756 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
11757 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
11758 !MoveAssignOperator->isDeleted()) &&
11759 "DefineImplicitMoveAssignment called for wrong function");
11760 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
11763 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
11764 if (ClassDecl->isInvalidDecl()) {
11765 MoveAssignOperator->setInvalidDecl();
11769 // C++0x [class.copy]p28:
11770 // The implicitly-defined or move assignment operator for a non-union class
11771 // X performs memberwise move assignment of its subobjects. The direct base
11772 // classes of X are assigned first, in the order of their declaration in the
11773 // base-specifier-list, and then the immediate non-static data members of X
11774 // are assigned, in the order in which they were declared in the class
11777 // Issue a warning if our implicit move assignment operator will move
11778 // from a virtual base more than once.
11779 checkMoveAssignmentForRepeatedMove(*this, ClassDecl, CurrentLocation);
11781 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
11783 // The exception specification is needed because we are defining the
11785 ResolveExceptionSpec(CurrentLocation,
11786 MoveAssignOperator->getType()->castAs<FunctionProtoType>());
11788 // Add a context note for diagnostics produced after this point.
11789 Scope.addContextNote(CurrentLocation);
11791 // The statements that form the synthesized function body.
11792 SmallVector<Stmt*, 8> Statements;
11794 // The parameter for the "other" object, which we are move from.
11795 ParmVarDecl *Other = MoveAssignOperator->getParamDecl(0);
11796 QualType OtherRefType = Other->getType()->
11797 getAs<RValueReferenceType>()->getPointeeType();
11798 assert(!OtherRefType.getQualifiers() &&
11799 "Bad argument type of defaulted move assignment");
11801 // Our location for everything implicitly-generated.
11802 SourceLocation Loc = MoveAssignOperator->getLocEnd().isValid()
11803 ? MoveAssignOperator->getLocEnd()
11804 : MoveAssignOperator->getLocation();
11806 // Builds a reference to the "other" object.
11807 RefBuilder OtherRef(Other, OtherRefType);
11809 MoveCastBuilder MoveOther(OtherRef);
11811 // Builds the "this" pointer.
11814 // Assign base classes.
11815 bool Invalid = false;
11816 for (auto &Base : ClassDecl->bases()) {
11817 // C++11 [class.copy]p28:
11818 // It is unspecified whether subobjects representing virtual base classes
11819 // are assigned more than once by the implicitly-defined copy assignment
11821 // FIXME: Do not assign to a vbase that will be assigned by some other base
11822 // class. For a move-assignment, this can result in the vbase being moved
11825 // Form the assignment:
11826 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
11827 QualType BaseType = Base.getType().getUnqualifiedType();
11828 if (!BaseType->isRecordType()) {
11833 CXXCastPath BasePath;
11834 BasePath.push_back(&Base);
11836 // Construct the "from" expression, which is an implicit cast to the
11837 // appropriately-qualified base type.
11838 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
11840 // Dereference "this".
11841 DerefBuilder DerefThis(This);
11843 // Implicitly cast "this" to the appropriately-qualified base type.
11844 CastBuilder To(DerefThis,
11845 Context.getCVRQualifiedType(
11846 BaseType, MoveAssignOperator->getTypeQualifiers()),
11847 VK_LValue, BasePath);
11850 StmtResult Move = buildSingleCopyAssign(*this, Loc, BaseType,
11852 /*CopyingBaseSubobject=*/true,
11853 /*Copying=*/false);
11854 if (Move.isInvalid()) {
11855 MoveAssignOperator->setInvalidDecl();
11859 // Success! Record the move.
11860 Statements.push_back(Move.getAs<Expr>());
11863 // Assign non-static members.
11864 for (auto *Field : ClassDecl->fields()) {
11865 // FIXME: We should form some kind of AST representation for the implied
11866 // memcpy in a union copy operation.
11867 if (Field->isUnnamedBitfield() || Field->getParent()->isUnion())
11870 if (Field->isInvalidDecl()) {
11875 // Check for members of reference type; we can't move those.
11876 if (Field->getType()->isReferenceType()) {
11877 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11878 << Context.getTagDeclType(ClassDecl) << 0 << Field->getDeclName();
11879 Diag(Field->getLocation(), diag::note_declared_at);
11884 // Check for members of const-qualified, non-class type.
11885 QualType BaseType = Context.getBaseElementType(Field->getType());
11886 if (!BaseType->getAs<RecordType>() && BaseType.isConstQualified()) {
11887 Diag(ClassDecl->getLocation(), diag::err_uninitialized_member_for_assign)
11888 << Context.getTagDeclType(ClassDecl) << 1 << Field->getDeclName();
11889 Diag(Field->getLocation(), diag::note_declared_at);
11894 // Suppress assigning zero-width bitfields.
11895 if (Field->isBitField() && Field->getBitWidthValue(Context) == 0)
11898 QualType FieldType = Field->getType().getNonReferenceType();
11899 if (FieldType->isIncompleteArrayType()) {
11900 assert(ClassDecl->hasFlexibleArrayMember() &&
11901 "Incomplete array type is not valid");
11905 // Build references to the field in the object we're copying from and to.
11906 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
11908 MemberLookup.addDecl(Field);
11909 MemberLookup.resolveKind();
11910 MemberBuilder From(MoveOther, OtherRefType,
11911 /*IsArrow=*/false, MemberLookup);
11912 MemberBuilder To(This, getCurrentThisType(),
11913 /*IsArrow=*/true, MemberLookup);
11915 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
11916 "Member reference with rvalue base must be rvalue except for reference "
11917 "members, which aren't allowed for move assignment.");
11919 // Build the move of this field.
11920 StmtResult Move = buildSingleCopyAssign(*this, Loc, FieldType,
11922 /*CopyingBaseSubobject=*/false,
11923 /*Copying=*/false);
11924 if (Move.isInvalid()) {
11925 MoveAssignOperator->setInvalidDecl();
11929 // Success! Record the copy.
11930 Statements.push_back(Move.getAs<Stmt>());
11934 // Add a "return *this;"
11935 ExprResult ThisObj =
11936 CreateBuiltinUnaryOp(Loc, UO_Deref, This.build(*this, Loc));
11938 StmtResult Return = BuildReturnStmt(Loc, ThisObj.get());
11939 if (Return.isInvalid())
11942 Statements.push_back(Return.getAs<Stmt>());
11946 MoveAssignOperator->setInvalidDecl();
11952 CompoundScopeRAII CompoundScope(*this);
11953 Body = ActOnCompoundStmt(Loc, Loc, Statements,
11954 /*isStmtExpr=*/false);
11955 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
11957 MoveAssignOperator->setBody(Body.getAs<Stmt>());
11958 MoveAssignOperator->markUsed(Context);
11960 if (ASTMutationListener *L = getASTMutationListener()) {
11961 L->CompletedImplicitDefinition(MoveAssignOperator);
11965 CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
11966 CXXRecordDecl *ClassDecl) {
11967 // C++ [class.copy]p4:
11968 // If the class definition does not explicitly declare a copy
11969 // constructor, one is declared implicitly.
11970 assert(ClassDecl->needsImplicitCopyConstructor());
11972 DeclaringSpecialMember DSM(*this, ClassDecl, CXXCopyConstructor);
11973 if (DSM.isAlreadyBeingDeclared())
11976 QualType ClassType = Context.getTypeDeclType(ClassDecl);
11977 QualType ArgType = ClassType;
11978 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
11980 ArgType = ArgType.withConst();
11981 ArgType = Context.getLValueReferenceType(ArgType);
11983 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
11984 CXXCopyConstructor,
11987 DeclarationName Name
11988 = Context.DeclarationNames.getCXXConstructorName(
11989 Context.getCanonicalType(ClassType));
11990 SourceLocation ClassLoc = ClassDecl->getLocation();
11991 DeclarationNameInfo NameInfo(Name, ClassLoc);
11993 // An implicitly-declared copy constructor is an inline public
11994 // member of its class.
11995 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
11996 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
11997 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
11999 CopyConstructor->setAccess(AS_public);
12000 CopyConstructor->setDefaulted();
12002 if (getLangOpts().CUDA) {
12003 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXCopyConstructor,
12005 /* ConstRHS */ Const,
12006 /* Diagnose */ false);
12009 // Build an exception specification pointing back at this member.
12010 FunctionProtoType::ExtProtoInfo EPI =
12011 getImplicitMethodEPI(*this, CopyConstructor);
12012 CopyConstructor->setType(
12013 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12015 // Add the parameter to the constructor.
12016 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, CopyConstructor,
12017 ClassLoc, ClassLoc,
12018 /*IdentifierInfo=*/nullptr,
12019 ArgType, /*TInfo=*/nullptr,
12021 CopyConstructor->setParams(FromParam);
12023 CopyConstructor->setTrivial(
12024 ClassDecl->needsOverloadResolutionForCopyConstructor()
12025 ? SpecialMemberIsTrivial(CopyConstructor, CXXCopyConstructor)
12026 : ClassDecl->hasTrivialCopyConstructor());
12028 // Note that we have declared this constructor.
12029 ++ASTContext::NumImplicitCopyConstructorsDeclared;
12031 Scope *S = getScopeForContext(ClassDecl);
12032 CheckImplicitSpecialMemberDeclaration(S, CopyConstructor);
12034 if (ShouldDeleteSpecialMember(CopyConstructor, CXXCopyConstructor)) {
12035 ClassDecl->setImplicitCopyConstructorIsDeleted();
12036 SetDeclDeleted(CopyConstructor, ClassLoc);
12040 PushOnScopeChains(CopyConstructor, S, false);
12041 ClassDecl->addDecl(CopyConstructor);
12043 return CopyConstructor;
12046 void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
12047 CXXConstructorDecl *CopyConstructor) {
12048 assert((CopyConstructor->isDefaulted() &&
12049 CopyConstructor->isCopyConstructor() &&
12050 !CopyConstructor->doesThisDeclarationHaveABody() &&
12051 !CopyConstructor->isDeleted()) &&
12052 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
12053 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
12056 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
12057 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
12059 SynthesizedFunctionScope Scope(*this, CopyConstructor);
12061 // The exception specification is needed because we are defining the
12063 ResolveExceptionSpec(CurrentLocation,
12064 CopyConstructor->getType()->castAs<FunctionProtoType>());
12065 MarkVTableUsed(CurrentLocation, ClassDecl);
12067 // Add a context note for diagnostics produced after this point.
12068 Scope.addContextNote(CurrentLocation);
12070 // C++11 [class.copy]p7:
12071 // The [definition of an implicitly declared copy constructor] is
12072 // deprecated if the class has a user-declared copy assignment operator
12073 // or a user-declared destructor.
12074 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
12075 diagnoseDeprecatedCopyOperation(*this, CopyConstructor);
12077 if (SetCtorInitializers(CopyConstructor, /*AnyErrors=*/false)) {
12078 CopyConstructor->setInvalidDecl();
12080 SourceLocation Loc = CopyConstructor->getLocEnd().isValid()
12081 ? CopyConstructor->getLocEnd()
12082 : CopyConstructor->getLocation();
12083 Sema::CompoundScopeRAII CompoundScope(*this);
12084 CopyConstructor->setBody(
12085 ActOnCompoundStmt(Loc, Loc, None, /*isStmtExpr=*/false).getAs<Stmt>());
12086 CopyConstructor->markUsed(Context);
12089 if (ASTMutationListener *L = getASTMutationListener()) {
12090 L->CompletedImplicitDefinition(CopyConstructor);
12094 CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
12095 CXXRecordDecl *ClassDecl) {
12096 assert(ClassDecl->needsImplicitMoveConstructor());
12098 DeclaringSpecialMember DSM(*this, ClassDecl, CXXMoveConstructor);
12099 if (DSM.isAlreadyBeingDeclared())
12102 QualType ClassType = Context.getTypeDeclType(ClassDecl);
12103 QualType ArgType = Context.getRValueReferenceType(ClassType);
12105 bool Constexpr = defaultedSpecialMemberIsConstexpr(*this, ClassDecl,
12106 CXXMoveConstructor,
12109 DeclarationName Name
12110 = Context.DeclarationNames.getCXXConstructorName(
12111 Context.getCanonicalType(ClassType));
12112 SourceLocation ClassLoc = ClassDecl->getLocation();
12113 DeclarationNameInfo NameInfo(Name, ClassLoc);
12115 // C++11 [class.copy]p11:
12116 // An implicitly-declared copy/move constructor is an inline public
12117 // member of its class.
12118 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
12119 Context, ClassDecl, ClassLoc, NameInfo, QualType(), /*TInfo=*/nullptr,
12120 /*isExplicit=*/false, /*isInline=*/true, /*isImplicitlyDeclared=*/true,
12122 MoveConstructor->setAccess(AS_public);
12123 MoveConstructor->setDefaulted();
12125 if (getLangOpts().CUDA) {
12126 inferCUDATargetForImplicitSpecialMember(ClassDecl, CXXMoveConstructor,
12128 /* ConstRHS */ false,
12129 /* Diagnose */ false);
12132 // Build an exception specification pointing back at this member.
12133 FunctionProtoType::ExtProtoInfo EPI =
12134 getImplicitMethodEPI(*this, MoveConstructor);
12135 MoveConstructor->setType(
12136 Context.getFunctionType(Context.VoidTy, ArgType, EPI));
12138 // Add the parameter to the constructor.
12139 ParmVarDecl *FromParam = ParmVarDecl::Create(Context, MoveConstructor,
12140 ClassLoc, ClassLoc,
12141 /*IdentifierInfo=*/nullptr,
12142 ArgType, /*TInfo=*/nullptr,
12144 MoveConstructor->setParams(FromParam);
12146 MoveConstructor->setTrivial(
12147 ClassDecl->needsOverloadResolutionForMoveConstructor()
12148 ? SpecialMemberIsTrivial(MoveConstructor, CXXMoveConstructor)
12149 : ClassDecl->hasTrivialMoveConstructor());
12151 // Note that we have declared this constructor.
12152 ++ASTContext::NumImplicitMoveConstructorsDeclared;
12154 Scope *S = getScopeForContext(ClassDecl);
12155 CheckImplicitSpecialMemberDeclaration(S, MoveConstructor);
12157 if (ShouldDeleteSpecialMember(MoveConstructor, CXXMoveConstructor)) {
12158 ClassDecl->setImplicitMoveConstructorIsDeleted();
12159 SetDeclDeleted(MoveConstructor, ClassLoc);
12163 PushOnScopeChains(MoveConstructor, S, false);
12164 ClassDecl->addDecl(MoveConstructor);
12166 return MoveConstructor;
12169 void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
12170 CXXConstructorDecl *MoveConstructor) {
12171 assert((MoveConstructor->isDefaulted() &&
12172 MoveConstructor->isMoveConstructor() &&
12173 !MoveConstructor->doesThisDeclarationHaveABody() &&
12174 !MoveConstructor->isDeleted()) &&
12175 "DefineImplicitMoveConstructor - call it for implicit move ctor");
12176 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
12179 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
12180 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
12182 SynthesizedFunctionScope Scope(*this, MoveConstructor);
12184 // The exception specification is needed because we are defining the
12186 ResolveExceptionSpec(CurrentLocation,
12187 MoveConstructor->getType()->castAs<FunctionProtoType>());
12188 MarkVTableUsed(CurrentLocation, ClassDecl);
12190 // Add a context note for diagnostics produced after this point.
12191 Scope.addContextNote(CurrentLocation);
12193 if (SetCtorInitializers(MoveConstructor, /*AnyErrors=*/false)) {
12194 MoveConstructor->setInvalidDecl();
12196 SourceLocation Loc = MoveConstructor->getLocEnd().isValid()
12197 ? MoveConstructor->getLocEnd()
12198 : MoveConstructor->getLocation();
12199 Sema::CompoundScopeRAII CompoundScope(*this);
12200 MoveConstructor->setBody(ActOnCompoundStmt(
12201 Loc, Loc, None, /*isStmtExpr=*/ false).getAs<Stmt>());
12202 MoveConstructor->markUsed(Context);
12205 if (ASTMutationListener *L = getASTMutationListener()) {
12206 L->CompletedImplicitDefinition(MoveConstructor);
12210 bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
12211 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(FD);
12214 void Sema::DefineImplicitLambdaToFunctionPointerConversion(
12215 SourceLocation CurrentLocation,
12216 CXXConversionDecl *Conv) {
12217 SynthesizedFunctionScope Scope(*this, Conv);
12218 assert(!Conv->getReturnType()->isUndeducedType());
12220 CXXRecordDecl *Lambda = Conv->getParent();
12221 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
12222 FunctionDecl *Invoker = Lambda->getLambdaStaticInvoker();
12224 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
12225 CallOp = InstantiateFunctionDeclaration(
12226 CallOp->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12230 Invoker = InstantiateFunctionDeclaration(
12231 Invoker->getDescribedFunctionTemplate(), TemplateArgs, CurrentLocation);
12236 if (CallOp->isInvalidDecl())
12239 // Mark the call operator referenced (and add to pending instantiations
12241 // For both the conversion and static-invoker template specializations
12242 // we construct their body's in this function, so no need to add them
12243 // to the PendingInstantiations.
12244 MarkFunctionReferenced(CurrentLocation, CallOp);
12246 // Fill in the __invoke function with a dummy implementation. IR generation
12247 // will fill in the actual details. Update its type in case it contained
12249 Invoker->markUsed(Context);
12250 Invoker->setReferenced();
12251 Invoker->setType(Conv->getReturnType()->getPointeeType());
12252 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
12254 // Construct the body of the conversion function { return __invoke; }.
12255 Expr *FunctionRef = BuildDeclRefExpr(Invoker, Invoker->getType(),
12256 VK_LValue, Conv->getLocation()).get();
12257 assert(FunctionRef && "Can't refer to __invoke function?");
12258 Stmt *Return = BuildReturnStmt(Conv->getLocation(), FunctionRef).get();
12259 Conv->setBody(CompoundStmt::Create(Context, Return, Conv->getLocation(),
12260 Conv->getLocation()));
12261 Conv->markUsed(Context);
12262 Conv->setReferenced();
12264 if (ASTMutationListener *L = getASTMutationListener()) {
12265 L->CompletedImplicitDefinition(Conv);
12266 L->CompletedImplicitDefinition(Invoker);
12272 void Sema::DefineImplicitLambdaToBlockPointerConversion(
12273 SourceLocation CurrentLocation,
12274 CXXConversionDecl *Conv)
12276 assert(!Conv->getParent()->isGenericLambda());
12278 SynthesizedFunctionScope Scope(*this, Conv);
12280 // Copy-initialize the lambda object as needed to capture it.
12281 Expr *This = ActOnCXXThis(CurrentLocation).get();
12282 Expr *DerefThis =CreateBuiltinUnaryOp(CurrentLocation, UO_Deref, This).get();
12284 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
12285 Conv->getLocation(),
12288 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
12289 // behavior. Note that only the general conversion function does this
12290 // (since it's unusable otherwise); in the case where we inline the
12291 // block literal, it has block literal lifetime semantics.
12292 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
12293 BuildBlock = ImplicitCastExpr::Create(Context, BuildBlock.get()->getType(),
12294 CK_CopyAndAutoreleaseBlockObject,
12295 BuildBlock.get(), nullptr, VK_RValue);
12297 if (BuildBlock.isInvalid()) {
12298 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12299 Conv->setInvalidDecl();
12303 // Create the return statement that returns the block from the conversion
12305 StmtResult Return = BuildReturnStmt(Conv->getLocation(), BuildBlock.get());
12306 if (Return.isInvalid()) {
12307 Diag(CurrentLocation, diag::note_lambda_to_block_conv);
12308 Conv->setInvalidDecl();
12312 // Set the body of the conversion function.
12313 Stmt *ReturnS = Return.get();
12314 Conv->setBody(CompoundStmt::Create(Context, ReturnS, Conv->getLocation(),
12315 Conv->getLocation()));
12316 Conv->markUsed(Context);
12318 // We're done; notify the mutation listener, if any.
12319 if (ASTMutationListener *L = getASTMutationListener()) {
12320 L->CompletedImplicitDefinition(Conv);
12324 /// \brief Determine whether the given list arguments contains exactly one
12325 /// "real" (non-default) argument.
12326 static bool hasOneRealArgument(MultiExprArg Args) {
12327 switch (Args.size()) {
12332 if (!Args[1]->isDefaultArgument())
12337 return !Args[0]->isDefaultArgument();
12344 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12345 NamedDecl *FoundDecl,
12346 CXXConstructorDecl *Constructor,
12347 MultiExprArg ExprArgs,
12348 bool HadMultipleCandidates,
12349 bool IsListInitialization,
12350 bool IsStdInitListInitialization,
12351 bool RequiresZeroInit,
12352 unsigned ConstructKind,
12353 SourceRange ParenRange) {
12354 bool Elidable = false;
12356 // C++0x [class.copy]p34:
12357 // When certain criteria are met, an implementation is allowed to
12358 // omit the copy/move construction of a class object, even if the
12359 // copy/move constructor and/or destructor for the object have
12360 // side effects. [...]
12361 // - when a temporary class object that has not been bound to a
12362 // reference (12.2) would be copied/moved to a class object
12363 // with the same cv-unqualified type, the copy/move operation
12364 // can be omitted by constructing the temporary object
12365 // directly into the target of the omitted copy/move
12366 if (ConstructKind == CXXConstructExpr::CK_Complete && Constructor &&
12367 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(ExprArgs)) {
12368 Expr *SubExpr = ExprArgs[0];
12369 Elidable = SubExpr->isTemporaryObject(
12370 Context, cast<CXXRecordDecl>(FoundDecl->getDeclContext()));
12373 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
12374 FoundDecl, Constructor,
12375 Elidable, ExprArgs, HadMultipleCandidates,
12376 IsListInitialization,
12377 IsStdInitListInitialization, RequiresZeroInit,
12378 ConstructKind, ParenRange);
12382 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12383 NamedDecl *FoundDecl,
12384 CXXConstructorDecl *Constructor,
12386 MultiExprArg ExprArgs,
12387 bool HadMultipleCandidates,
12388 bool IsListInitialization,
12389 bool IsStdInitListInitialization,
12390 bool RequiresZeroInit,
12391 unsigned ConstructKind,
12392 SourceRange ParenRange) {
12393 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(FoundDecl)) {
12394 Constructor = findInheritingConstructor(ConstructLoc, Constructor, Shadow);
12395 if (DiagnoseUseOfDecl(Constructor, ConstructLoc))
12396 return ExprError();
12399 return BuildCXXConstructExpr(
12400 ConstructLoc, DeclInitType, Constructor, Elidable, ExprArgs,
12401 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
12402 RequiresZeroInit, ConstructKind, ParenRange);
12405 /// BuildCXXConstructExpr - Creates a complete call to a constructor,
12406 /// including handling of its default argument expressions.
12408 Sema::BuildCXXConstructExpr(SourceLocation ConstructLoc, QualType DeclInitType,
12409 CXXConstructorDecl *Constructor,
12411 MultiExprArg ExprArgs,
12412 bool HadMultipleCandidates,
12413 bool IsListInitialization,
12414 bool IsStdInitListInitialization,
12415 bool RequiresZeroInit,
12416 unsigned ConstructKind,
12417 SourceRange ParenRange) {
12418 assert(declaresSameEntity(
12419 Constructor->getParent(),
12420 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
12421 "given constructor for wrong type");
12422 MarkFunctionReferenced(ConstructLoc, Constructor);
12423 if (getLangOpts().CUDA && !CheckCUDACall(ConstructLoc, Constructor))
12424 return ExprError();
12426 return CXXConstructExpr::Create(
12427 Context, DeclInitType, ConstructLoc, Constructor, Elidable,
12428 ExprArgs, HadMultipleCandidates, IsListInitialization,
12429 IsStdInitListInitialization, RequiresZeroInit,
12430 static_cast<CXXConstructExpr::ConstructionKind>(ConstructKind),
12434 ExprResult Sema::BuildCXXDefaultInitExpr(SourceLocation Loc, FieldDecl *Field) {
12435 assert(Field->hasInClassInitializer());
12437 // If we already have the in-class initializer nothing needs to be done.
12438 if (Field->getInClassInitializer())
12439 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12441 // If we might have already tried and failed to instantiate, don't try again.
12442 if (Field->isInvalidDecl())
12443 return ExprError();
12445 // Maybe we haven't instantiated the in-class initializer. Go check the
12446 // pattern FieldDecl to see if it has one.
12447 CXXRecordDecl *ParentRD = cast<CXXRecordDecl>(Field->getParent());
12449 if (isTemplateInstantiation(ParentRD->getTemplateSpecializationKind())) {
12450 CXXRecordDecl *ClassPattern = ParentRD->getTemplateInstantiationPattern();
12451 DeclContext::lookup_result Lookup =
12452 ClassPattern->lookup(Field->getDeclName());
12454 // Lookup can return at most two results: the pattern for the field, or the
12455 // injected class name of the parent record. No other member can have the
12456 // same name as the field.
12457 // In modules mode, lookup can return multiple results (coming from
12458 // different modules).
12459 assert((getLangOpts().Modules || (!Lookup.empty() && Lookup.size() <= 2)) &&
12460 "more than two lookup results for field name");
12461 FieldDecl *Pattern = dyn_cast<FieldDecl>(Lookup[0]);
12463 assert(isa<CXXRecordDecl>(Lookup[0]) &&
12464 "cannot have other non-field member with same name");
12465 for (auto L : Lookup)
12466 if (isa<FieldDecl>(L)) {
12467 Pattern = cast<FieldDecl>(L);
12470 assert(Pattern && "We must have set the Pattern!");
12473 if (!Pattern->hasInClassInitializer() ||
12474 InstantiateInClassInitializer(Loc, Field, Pattern,
12475 getTemplateInstantiationArgs(Field))) {
12476 // Don't diagnose this again.
12477 Field->setInvalidDecl();
12478 return ExprError();
12480 return CXXDefaultInitExpr::Create(Context, Loc, Field);
12484 // If the brace-or-equal-initializer of a non-static data member
12485 // invokes a defaulted default constructor of its class or of an
12486 // enclosing class in a potentially evaluated subexpression, the
12487 // program is ill-formed.
12489 // This resolution is unworkable: the exception specification of the
12490 // default constructor can be needed in an unevaluated context, in
12491 // particular, in the operand of a noexcept-expression, and we can be
12492 // unable to compute an exception specification for an enclosed class.
12494 // Any attempt to resolve the exception specification of a defaulted default
12495 // constructor before the initializer is lexically complete will ultimately
12496 // come here at which point we can diagnose it.
12497 RecordDecl *OutermostClass = ParentRD->getOuterLexicalRecordContext();
12498 Diag(Loc, diag::err_in_class_initializer_not_yet_parsed)
12499 << OutermostClass << Field;
12500 Diag(Field->getLocEnd(), diag::note_in_class_initializer_not_yet_parsed);
12501 // Recover by marking the field invalid, unless we're in a SFINAE context.
12502 if (!isSFINAEContext())
12503 Field->setInvalidDecl();
12504 return ExprError();
12507 void Sema::FinalizeVarWithDestructor(VarDecl *VD, const RecordType *Record) {
12508 if (VD->isInvalidDecl()) return;
12510 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Record->getDecl());
12511 if (ClassDecl->isInvalidDecl()) return;
12512 if (ClassDecl->hasIrrelevantDestructor()) return;
12513 if (ClassDecl->isDependentContext()) return;
12515 CXXDestructorDecl *Destructor = LookupDestructor(ClassDecl);
12516 MarkFunctionReferenced(VD->getLocation(), Destructor);
12517 CheckDestructorAccess(VD->getLocation(), Destructor,
12518 PDiag(diag::err_access_dtor_var)
12519 << VD->getDeclName()
12521 DiagnoseUseOfDecl(Destructor, VD->getLocation());
12523 if (Destructor->isTrivial()) return;
12524 if (!VD->hasGlobalStorage()) return;
12526 // Emit warning for non-trivial dtor in global scope (a real global,
12527 // class-static, function-static).
12528 Diag(VD->getLocation(), diag::warn_exit_time_destructor);
12530 // TODO: this should be re-enabled for static locals by !CXAAtExit
12531 if (!VD->isStaticLocal())
12532 Diag(VD->getLocation(), diag::warn_global_destructor);
12535 /// \brief Given a constructor and the set of arguments provided for the
12536 /// constructor, convert the arguments and add any required default arguments
12537 /// to form a proper call to this constructor.
12539 /// \returns true if an error occurred, false otherwise.
12541 Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
12542 MultiExprArg ArgsPtr,
12543 SourceLocation Loc,
12544 SmallVectorImpl<Expr*> &ConvertedArgs,
12545 bool AllowExplicit,
12546 bool IsListInitialization) {
12547 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
12548 unsigned NumArgs = ArgsPtr.size();
12549 Expr **Args = ArgsPtr.data();
12551 const FunctionProtoType *Proto
12552 = Constructor->getType()->getAs<FunctionProtoType>();
12553 assert(Proto && "Constructor without a prototype?");
12554 unsigned NumParams = Proto->getNumParams();
12556 // If too few arguments are available, we'll fill in the rest with defaults.
12557 if (NumArgs < NumParams)
12558 ConvertedArgs.reserve(NumParams);
12560 ConvertedArgs.reserve(NumArgs);
12562 VariadicCallType CallType =
12563 Proto->isVariadic() ? VariadicConstructor : VariadicDoesNotApply;
12564 SmallVector<Expr *, 8> AllArgs;
12565 bool Invalid = GatherArgumentsForCall(Loc, Constructor,
12567 llvm::makeArrayRef(Args, NumArgs),
12569 CallType, AllowExplicit,
12570 IsListInitialization);
12571 ConvertedArgs.append(AllArgs.begin(), AllArgs.end());
12573 DiagnoseSentinelCalls(Constructor, Loc, AllArgs);
12575 CheckConstructorCall(Constructor,
12576 llvm::makeArrayRef(AllArgs.data(), AllArgs.size()),
12583 CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
12584 const FunctionDecl *FnDecl) {
12585 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
12586 if (isa<NamespaceDecl>(DC)) {
12587 return SemaRef.Diag(FnDecl->getLocation(),
12588 diag::err_operator_new_delete_declared_in_namespace)
12589 << FnDecl->getDeclName();
12592 if (isa<TranslationUnitDecl>(DC) &&
12593 FnDecl->getStorageClass() == SC_Static) {
12594 return SemaRef.Diag(FnDecl->getLocation(),
12595 diag::err_operator_new_delete_declared_static)
12596 << FnDecl->getDeclName();
12603 CheckOperatorNewDeleteTypes(Sema &SemaRef, const FunctionDecl *FnDecl,
12604 CanQualType ExpectedResultType,
12605 CanQualType ExpectedFirstParamType,
12606 unsigned DependentParamTypeDiag,
12607 unsigned InvalidParamTypeDiag) {
12608 QualType ResultType =
12609 FnDecl->getType()->getAs<FunctionType>()->getReturnType();
12611 // Check that the result type is not dependent.
12612 if (ResultType->isDependentType())
12613 return SemaRef.Diag(FnDecl->getLocation(),
12614 diag::err_operator_new_delete_dependent_result_type)
12615 << FnDecl->getDeclName() << ExpectedResultType;
12617 // Check that the result type is what we expect.
12618 if (SemaRef.Context.getCanonicalType(ResultType) != ExpectedResultType)
12619 return SemaRef.Diag(FnDecl->getLocation(),
12620 diag::err_operator_new_delete_invalid_result_type)
12621 << FnDecl->getDeclName() << ExpectedResultType;
12623 // A function template must have at least 2 parameters.
12624 if (FnDecl->getDescribedFunctionTemplate() && FnDecl->getNumParams() < 2)
12625 return SemaRef.Diag(FnDecl->getLocation(),
12626 diag::err_operator_new_delete_template_too_few_parameters)
12627 << FnDecl->getDeclName();
12629 // The function decl must have at least 1 parameter.
12630 if (FnDecl->getNumParams() == 0)
12631 return SemaRef.Diag(FnDecl->getLocation(),
12632 diag::err_operator_new_delete_too_few_parameters)
12633 << FnDecl->getDeclName();
12635 // Check the first parameter type is not dependent.
12636 QualType FirstParamType = FnDecl->getParamDecl(0)->getType();
12637 if (FirstParamType->isDependentType())
12638 return SemaRef.Diag(FnDecl->getLocation(), DependentParamTypeDiag)
12639 << FnDecl->getDeclName() << ExpectedFirstParamType;
12641 // Check that the first parameter type is what we expect.
12642 if (SemaRef.Context.getCanonicalType(FirstParamType).getUnqualifiedType() !=
12643 ExpectedFirstParamType)
12644 return SemaRef.Diag(FnDecl->getLocation(), InvalidParamTypeDiag)
12645 << FnDecl->getDeclName() << ExpectedFirstParamType;
12651 CheckOperatorNewDeclaration(Sema &SemaRef, const FunctionDecl *FnDecl) {
12652 // C++ [basic.stc.dynamic.allocation]p1:
12653 // A program is ill-formed if an allocation function is declared in a
12654 // namespace scope other than global scope or declared static in global
12656 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12659 CanQualType SizeTy =
12660 SemaRef.Context.getCanonicalType(SemaRef.Context.getSizeType());
12662 // C++ [basic.stc.dynamic.allocation]p1:
12663 // The return type shall be void*. The first parameter shall have type
12665 if (CheckOperatorNewDeleteTypes(SemaRef, FnDecl, SemaRef.Context.VoidPtrTy,
12667 diag::err_operator_new_dependent_param_type,
12668 diag::err_operator_new_param_type))
12671 // C++ [basic.stc.dynamic.allocation]p1:
12672 // The first parameter shall not have an associated default argument.
12673 if (FnDecl->getParamDecl(0)->hasDefaultArg())
12674 return SemaRef.Diag(FnDecl->getLocation(),
12675 diag::err_operator_new_default_arg)
12676 << FnDecl->getDeclName() << FnDecl->getParamDecl(0)->getDefaultArgRange();
12682 CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
12683 // C++ [basic.stc.dynamic.deallocation]p1:
12684 // A program is ill-formed if deallocation functions are declared in a
12685 // namespace scope other than global scope or declared static in global
12687 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
12690 auto *MD = dyn_cast<CXXMethodDecl>(FnDecl);
12693 // Within a class C, the first parameter of a destroying operator delete
12694 // shall be of type C *. The first parameter of any other deallocation
12695 // function shall be of type void *.
12696 CanQualType ExpectedFirstParamType =
12697 MD && MD->isDestroyingOperatorDelete()
12698 ? SemaRef.Context.getCanonicalType(SemaRef.Context.getPointerType(
12699 SemaRef.Context.getRecordType(MD->getParent())))
12700 : SemaRef.Context.VoidPtrTy;
12702 // C++ [basic.stc.dynamic.deallocation]p2:
12703 // Each deallocation function shall return void
12704 if (CheckOperatorNewDeleteTypes(
12705 SemaRef, FnDecl, SemaRef.Context.VoidTy, ExpectedFirstParamType,
12706 diag::err_operator_delete_dependent_param_type,
12707 diag::err_operator_delete_param_type))
12711 // A destroying operator delete shall be a usual deallocation function.
12712 if (MD && !MD->getParent()->isDependentContext() &&
12713 MD->isDestroyingOperatorDelete() && !MD->isUsualDeallocationFunction()) {
12714 SemaRef.Diag(MD->getLocation(),
12715 diag::err_destroying_operator_delete_not_usual);
12722 /// CheckOverloadedOperatorDeclaration - Check whether the declaration
12723 /// of this overloaded operator is well-formed. If so, returns false;
12724 /// otherwise, emits appropriate diagnostics and returns true.
12725 bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
12726 assert(FnDecl && FnDecl->isOverloadedOperator() &&
12727 "Expected an overloaded operator declaration");
12729 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
12731 // C++ [over.oper]p5:
12732 // The allocation and deallocation functions, operator new,
12733 // operator new[], operator delete and operator delete[], are
12734 // described completely in 3.7.3. The attributes and restrictions
12735 // found in the rest of this subclause do not apply to them unless
12736 // explicitly stated in 3.7.3.
12737 if (Op == OO_Delete || Op == OO_Array_Delete)
12738 return CheckOperatorDeleteDeclaration(*this, FnDecl);
12740 if (Op == OO_New || Op == OO_Array_New)
12741 return CheckOperatorNewDeclaration(*this, FnDecl);
12743 // C++ [over.oper]p6:
12744 // An operator function shall either be a non-static member
12745 // function or be a non-member function and have at least one
12746 // parameter whose type is a class, a reference to a class, an
12747 // enumeration, or a reference to an enumeration.
12748 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(FnDecl)) {
12749 if (MethodDecl->isStatic())
12750 return Diag(FnDecl->getLocation(),
12751 diag::err_operator_overload_static) << FnDecl->getDeclName();
12753 bool ClassOrEnumParam = false;
12754 for (auto Param : FnDecl->parameters()) {
12755 QualType ParamType = Param->getType().getNonReferenceType();
12756 if (ParamType->isDependentType() || ParamType->isRecordType() ||
12757 ParamType->isEnumeralType()) {
12758 ClassOrEnumParam = true;
12763 if (!ClassOrEnumParam)
12764 return Diag(FnDecl->getLocation(),
12765 diag::err_operator_overload_needs_class_or_enum)
12766 << FnDecl->getDeclName();
12769 // C++ [over.oper]p8:
12770 // An operator function cannot have default arguments (8.3.6),
12771 // except where explicitly stated below.
12773 // Only the function-call operator allows default arguments
12774 // (C++ [over.call]p1).
12775 if (Op != OO_Call) {
12776 for (auto Param : FnDecl->parameters()) {
12777 if (Param->hasDefaultArg())
12778 return Diag(Param->getLocation(),
12779 diag::err_operator_overload_default_arg)
12780 << FnDecl->getDeclName() << Param->getDefaultArgRange();
12784 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
12785 { false, false, false }
12786 #define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
12787 , { Unary, Binary, MemberOnly }
12788 #include "clang/Basic/OperatorKinds.def"
12791 bool CanBeUnaryOperator = OperatorUses[Op][0];
12792 bool CanBeBinaryOperator = OperatorUses[Op][1];
12793 bool MustBeMemberOperator = OperatorUses[Op][2];
12795 // C++ [over.oper]p8:
12796 // [...] Operator functions cannot have more or fewer parameters
12797 // than the number required for the corresponding operator, as
12798 // described in the rest of this subclause.
12799 unsigned NumParams = FnDecl->getNumParams()
12800 + (isa<CXXMethodDecl>(FnDecl)? 1 : 0);
12801 if (Op != OO_Call &&
12802 ((NumParams == 1 && !CanBeUnaryOperator) ||
12803 (NumParams == 2 && !CanBeBinaryOperator) ||
12804 (NumParams < 1) || (NumParams > 2))) {
12805 // We have the wrong number of parameters.
12806 unsigned ErrorKind;
12807 if (CanBeUnaryOperator && CanBeBinaryOperator) {
12808 ErrorKind = 2; // 2 -> unary or binary.
12809 } else if (CanBeUnaryOperator) {
12810 ErrorKind = 0; // 0 -> unary
12812 assert(CanBeBinaryOperator &&
12813 "All non-call overloaded operators are unary or binary!");
12814 ErrorKind = 1; // 1 -> binary
12817 return Diag(FnDecl->getLocation(), diag::err_operator_overload_must_be)
12818 << FnDecl->getDeclName() << NumParams << ErrorKind;
12821 // Overloaded operators other than operator() cannot be variadic.
12822 if (Op != OO_Call &&
12823 FnDecl->getType()->getAs<FunctionProtoType>()->isVariadic()) {
12824 return Diag(FnDecl->getLocation(), diag::err_operator_overload_variadic)
12825 << FnDecl->getDeclName();
12828 // Some operators must be non-static member functions.
12829 if (MustBeMemberOperator && !isa<CXXMethodDecl>(FnDecl)) {
12830 return Diag(FnDecl->getLocation(),
12831 diag::err_operator_overload_must_be_member)
12832 << FnDecl->getDeclName();
12835 // C++ [over.inc]p1:
12836 // The user-defined function called operator++ implements the
12837 // prefix and postfix ++ operator. If this function is a member
12838 // function with no parameters, or a non-member function with one
12839 // parameter of class or enumeration type, it defines the prefix
12840 // increment operator ++ for objects of that type. If the function
12841 // is a member function with one parameter (which shall be of type
12842 // int) or a non-member function with two parameters (the second
12843 // of which shall be of type int), it defines the postfix
12844 // increment operator ++ for objects of that type.
12845 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
12846 ParmVarDecl *LastParam = FnDecl->getParamDecl(FnDecl->getNumParams() - 1);
12847 QualType ParamType = LastParam->getType();
12849 if (!ParamType->isSpecificBuiltinType(BuiltinType::Int) &&
12850 !ParamType->isDependentType())
12851 return Diag(LastParam->getLocation(),
12852 diag::err_operator_overload_post_incdec_must_be_int)
12853 << LastParam->getType() << (Op == OO_MinusMinus);
12860 checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
12861 FunctionTemplateDecl *TpDecl) {
12862 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
12864 // Must have one or two template parameters.
12865 if (TemplateParams->size() == 1) {
12866 NonTypeTemplateParmDecl *PmDecl =
12867 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(0));
12869 // The template parameter must be a char parameter pack.
12870 if (PmDecl && PmDecl->isTemplateParameterPack() &&
12871 SemaRef.Context.hasSameType(PmDecl->getType(), SemaRef.Context.CharTy))
12874 } else if (TemplateParams->size() == 2) {
12875 TemplateTypeParmDecl *PmType =
12876 dyn_cast<TemplateTypeParmDecl>(TemplateParams->getParam(0));
12877 NonTypeTemplateParmDecl *PmArgs =
12878 dyn_cast<NonTypeTemplateParmDecl>(TemplateParams->getParam(1));
12880 // The second template parameter must be a parameter pack with the
12881 // first template parameter as its type.
12882 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
12883 PmArgs->isTemplateParameterPack()) {
12884 const TemplateTypeParmType *TArgs =
12885 PmArgs->getType()->getAs<TemplateTypeParmType>();
12886 if (TArgs && TArgs->getDepth() == PmType->getDepth() &&
12887 TArgs->getIndex() == PmType->getIndex()) {
12888 if (!SemaRef.inTemplateInstantiation())
12889 SemaRef.Diag(TpDecl->getLocation(),
12890 diag::ext_string_literal_operator_template);
12896 SemaRef.Diag(TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
12897 diag::err_literal_operator_template)
12898 << TpDecl->getTemplateParameters()->getSourceRange();
12902 /// CheckLiteralOperatorDeclaration - Check whether the declaration
12903 /// of this literal operator function is well-formed. If so, returns
12904 /// false; otherwise, emits appropriate diagnostics and returns true.
12905 bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
12906 if (isa<CXXMethodDecl>(FnDecl)) {
12907 Diag(FnDecl->getLocation(), diag::err_literal_operator_outside_namespace)
12908 << FnDecl->getDeclName();
12912 if (FnDecl->isExternC()) {
12913 Diag(FnDecl->getLocation(), diag::err_literal_operator_extern_c);
12914 if (const LinkageSpecDecl *LSD =
12915 FnDecl->getDeclContext()->getExternCContext())
12916 Diag(LSD->getExternLoc(), diag::note_extern_c_begins_here);
12920 // This might be the definition of a literal operator template.
12921 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
12923 // This might be a specialization of a literal operator template.
12925 TpDecl = FnDecl->getPrimaryTemplate();
12927 // template <char...> type operator "" name() and
12928 // template <class T, T...> type operator "" name() are the only valid
12929 // template signatures, and the only valid signatures with no parameters.
12931 if (FnDecl->param_size() != 0) {
12932 Diag(FnDecl->getLocation(),
12933 diag::err_literal_operator_template_with_params);
12937 if (checkLiteralOperatorTemplateParameterList(*this, TpDecl))
12940 } else if (FnDecl->param_size() == 1) {
12941 const ParmVarDecl *Param = FnDecl->getParamDecl(0);
12943 QualType ParamType = Param->getType().getUnqualifiedType();
12945 // Only unsigned long long int, long double, any character type, and const
12946 // char * are allowed as the only parameters.
12947 if (ParamType->isSpecificBuiltinType(BuiltinType::ULongLong) ||
12948 ParamType->isSpecificBuiltinType(BuiltinType::LongDouble) ||
12949 Context.hasSameType(ParamType, Context.CharTy) ||
12950 Context.hasSameType(ParamType, Context.WideCharTy) ||
12951 Context.hasSameType(ParamType, Context.Char16Ty) ||
12952 Context.hasSameType(ParamType, Context.Char32Ty)) {
12953 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
12954 QualType InnerType = Ptr->getPointeeType();
12956 // Pointer parameter must be a const char *.
12957 if (!(Context.hasSameType(InnerType.getUnqualifiedType(),
12959 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
12960 Diag(Param->getSourceRange().getBegin(),
12961 diag::err_literal_operator_param)
12962 << ParamType << "'const char *'" << Param->getSourceRange();
12966 } else if (ParamType->isRealFloatingType()) {
12967 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12968 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
12971 } else if (ParamType->isIntegerType()) {
12972 Diag(Param->getSourceRange().getBegin(), diag::err_literal_operator_param)
12973 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
12977 Diag(Param->getSourceRange().getBegin(),
12978 diag::err_literal_operator_invalid_param)
12979 << ParamType << Param->getSourceRange();
12983 } else if (FnDecl->param_size() == 2) {
12984 FunctionDecl::param_iterator Param = FnDecl->param_begin();
12986 // First, verify that the first parameter is correct.
12988 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
12990 // Two parameter function must have a pointer to const as a
12991 // first parameter; let's strip those qualifiers.
12992 const PointerType *PT = FirstParamType->getAs<PointerType>();
12995 Diag((*Param)->getSourceRange().getBegin(),
12996 diag::err_literal_operator_param)
12997 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13001 QualType PointeeType = PT->getPointeeType();
13002 // First parameter must be const
13003 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
13004 Diag((*Param)->getSourceRange().getBegin(),
13005 diag::err_literal_operator_param)
13006 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13010 QualType InnerType = PointeeType.getUnqualifiedType();
13011 // Only const char *, const wchar_t*, const char16_t*, and const char32_t*
13012 // are allowed as the first parameter to a two-parameter function
13013 if (!(Context.hasSameType(InnerType, Context.CharTy) ||
13014 Context.hasSameType(InnerType, Context.WideCharTy) ||
13015 Context.hasSameType(InnerType, Context.Char16Ty) ||
13016 Context.hasSameType(InnerType, Context.Char32Ty))) {
13017 Diag((*Param)->getSourceRange().getBegin(),
13018 diag::err_literal_operator_param)
13019 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
13023 // Move on to the second and final parameter.
13026 // The second parameter must be a std::size_t.
13027 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
13028 if (!Context.hasSameType(SecondParamType, Context.getSizeType())) {
13029 Diag((*Param)->getSourceRange().getBegin(),
13030 diag::err_literal_operator_param)
13031 << SecondParamType << Context.getSizeType()
13032 << (*Param)->getSourceRange();
13036 Diag(FnDecl->getLocation(), diag::err_literal_operator_bad_param_count);
13040 // Parameters are good.
13042 // A parameter-declaration-clause containing a default argument is not
13043 // equivalent to any of the permitted forms.
13044 for (auto Param : FnDecl->parameters()) {
13045 if (Param->hasDefaultArg()) {
13046 Diag(Param->getDefaultArgRange().getBegin(),
13047 diag::err_literal_operator_default_argument)
13048 << Param->getDefaultArgRange();
13053 StringRef LiteralName
13054 = FnDecl->getDeclName().getCXXLiteralIdentifier()->getName();
13055 if (LiteralName[0] != '_' &&
13056 !getSourceManager().isInSystemHeader(FnDecl->getLocation())) {
13057 // C++11 [usrlit.suffix]p1:
13058 // Literal suffix identifiers that do not start with an underscore
13059 // are reserved for future standardization.
13060 Diag(FnDecl->getLocation(), diag::warn_user_literal_reserved)
13061 << StringLiteralParser::isValidUDSuffix(getLangOpts(), LiteralName);
13067 /// ActOnStartLinkageSpecification - Parsed the beginning of a C++
13068 /// linkage specification, including the language and (if present)
13069 /// the '{'. ExternLoc is the location of the 'extern', Lang is the
13070 /// language string literal. LBraceLoc, if valid, provides the location of
13071 /// the '{' brace. Otherwise, this linkage specification does not
13072 /// have any braces.
13073 Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
13075 SourceLocation LBraceLoc) {
13076 StringLiteral *Lit = cast<StringLiteral>(LangStr);
13077 if (!Lit->isAscii()) {
13078 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_not_ascii)
13079 << LangStr->getSourceRange();
13083 StringRef Lang = Lit->getString();
13084 LinkageSpecDecl::LanguageIDs Language;
13086 Language = LinkageSpecDecl::lang_c;
13087 else if (Lang == "C++")
13088 Language = LinkageSpecDecl::lang_cxx;
13090 Diag(LangStr->getExprLoc(), diag::err_language_linkage_spec_unknown)
13091 << LangStr->getSourceRange();
13095 // FIXME: Add all the various semantics of linkage specifications
13097 LinkageSpecDecl *D = LinkageSpecDecl::Create(Context, CurContext, ExternLoc,
13098 LangStr->getExprLoc(), Language,
13099 LBraceLoc.isValid());
13100 CurContext->addDecl(D);
13101 PushDeclContext(S, D);
13105 /// ActOnFinishLinkageSpecification - Complete the definition of
13106 /// the C++ linkage specification LinkageSpec. If RBraceLoc is
13107 /// valid, it's the position of the closing '}' brace in a linkage
13108 /// specification that uses braces.
13109 Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
13111 SourceLocation RBraceLoc) {
13112 if (RBraceLoc.isValid()) {
13113 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(LinkageSpec);
13114 LSDecl->setRBraceLoc(RBraceLoc);
13117 return LinkageSpec;
13120 Decl *Sema::ActOnEmptyDeclaration(Scope *S,
13121 AttributeList *AttrList,
13122 SourceLocation SemiLoc) {
13123 Decl *ED = EmptyDecl::Create(Context, CurContext, SemiLoc);
13124 // Attribute declarations appertain to empty declaration so we handle
13127 ProcessDeclAttributeList(S, ED, AttrList);
13129 CurContext->addDecl(ED);
13133 /// \brief Perform semantic analysis for the variable declaration that
13134 /// occurs within a C++ catch clause, returning the newly-created
13136 VarDecl *Sema::BuildExceptionDeclaration(Scope *S,
13137 TypeSourceInfo *TInfo,
13138 SourceLocation StartLoc,
13139 SourceLocation Loc,
13140 IdentifierInfo *Name) {
13141 bool Invalid = false;
13142 QualType ExDeclType = TInfo->getType();
13144 // Arrays and functions decay.
13145 if (ExDeclType->isArrayType())
13146 ExDeclType = Context.getArrayDecayedType(ExDeclType);
13147 else if (ExDeclType->isFunctionType())
13148 ExDeclType = Context.getPointerType(ExDeclType);
13150 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
13151 // The exception-declaration shall not denote a pointer or reference to an
13152 // incomplete type, other than [cv] void*.
13153 // N2844 forbids rvalue references.
13154 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
13155 Diag(Loc, diag::err_catch_rvalue_ref);
13159 if (ExDeclType->isVariablyModifiedType()) {
13160 Diag(Loc, diag::err_catch_variably_modified) << ExDeclType;
13164 QualType BaseType = ExDeclType;
13165 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
13166 unsigned DK = diag::err_catch_incomplete;
13167 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
13168 BaseType = Ptr->getPointeeType();
13170 DK = diag::err_catch_incomplete_ptr;
13171 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
13172 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
13173 BaseType = Ref->getPointeeType();
13175 DK = diag::err_catch_incomplete_ref;
13177 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
13178 !BaseType->isDependentType() && RequireCompleteType(Loc, BaseType, DK))
13181 if (!Invalid && !ExDeclType->isDependentType() &&
13182 RequireNonAbstractType(Loc, ExDeclType,
13183 diag::err_abstract_type_in_decl,
13184 AbstractVariableType))
13187 // Only the non-fragile NeXT runtime currently supports C++ catches
13188 // of ObjC types, and no runtime supports catching ObjC types by value.
13189 if (!Invalid && getLangOpts().ObjC1) {
13190 QualType T = ExDeclType;
13191 if (const ReferenceType *RT = T->getAs<ReferenceType>())
13192 T = RT->getPointeeType();
13194 if (T->isObjCObjectType()) {
13195 Diag(Loc, diag::err_objc_object_catch);
13197 } else if (T->isObjCObjectPointerType()) {
13198 // FIXME: should this be a test for macosx-fragile specifically?
13199 if (getLangOpts().ObjCRuntime.isFragile())
13200 Diag(Loc, diag::warn_objc_pointer_cxx_catch_fragile);
13204 VarDecl *ExDecl = VarDecl::Create(Context, CurContext, StartLoc, Loc, Name,
13205 ExDeclType, TInfo, SC_None);
13206 ExDecl->setExceptionVariable(true);
13208 // In ARC, infer 'retaining' for variables of retainable type.
13209 if (getLangOpts().ObjCAutoRefCount && inferObjCARCLifetime(ExDecl))
13212 if (!Invalid && !ExDeclType->isDependentType()) {
13213 if (const RecordType *recordType = ExDeclType->getAs<RecordType>()) {
13214 // Insulate this from anything else we might currently be parsing.
13215 EnterExpressionEvaluationContext scope(
13216 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
13218 // C++ [except.handle]p16:
13219 // The object declared in an exception-declaration or, if the
13220 // exception-declaration does not specify a name, a temporary (12.2) is
13221 // copy-initialized (8.5) from the exception object. [...]
13222 // The object is destroyed when the handler exits, after the destruction
13223 // of any automatic objects initialized within the handler.
13225 // We just pretend to initialize the object with itself, then make sure
13226 // it can be destroyed later.
13227 QualType initType = Context.getExceptionObjectType(ExDeclType);
13229 InitializedEntity entity =
13230 InitializedEntity::InitializeVariable(ExDecl);
13231 InitializationKind initKind =
13232 InitializationKind::CreateCopy(Loc, SourceLocation());
13234 Expr *opaqueValue =
13235 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
13236 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
13237 ExprResult result = sequence.Perform(*this, entity, initKind, opaqueValue);
13238 if (result.isInvalid())
13241 // If the constructor used was non-trivial, set this as the
13243 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
13244 if (!construct->getConstructor()->isTrivial()) {
13245 Expr *init = MaybeCreateExprWithCleanups(construct);
13246 ExDecl->setInit(init);
13249 // And make sure it's destructable.
13250 FinalizeVarWithDestructor(ExDecl, recordType);
13256 ExDecl->setInvalidDecl();
13261 /// ActOnExceptionDeclarator - Parsed the exception-declarator in a C++ catch
13263 Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
13264 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13265 bool Invalid = D.isInvalidType();
13267 // Check for unexpanded parameter packs.
13268 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
13269 UPPC_ExceptionType)) {
13270 TInfo = Context.getTrivialTypeSourceInfo(Context.IntTy,
13271 D.getIdentifierLoc());
13275 IdentifierInfo *II = D.getIdentifier();
13276 if (NamedDecl *PrevDecl = LookupSingleName(S, II, D.getIdentifierLoc(),
13277 LookupOrdinaryName,
13278 ForVisibleRedeclaration)) {
13279 // The scope should be freshly made just for us. There is just no way
13280 // it contains any previous declaration, except for function parameters in
13281 // a function-try-block's catch statement.
13282 assert(!S->isDeclScope(PrevDecl));
13283 if (isDeclInScope(PrevDecl, CurContext, S)) {
13284 Diag(D.getIdentifierLoc(), diag::err_redefinition)
13285 << D.getIdentifier();
13286 Diag(PrevDecl->getLocation(), diag::note_previous_definition);
13288 } else if (PrevDecl->isTemplateParameter())
13289 // Maybe we will complain about the shadowed template parameter.
13290 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
13293 if (D.getCXXScopeSpec().isSet() && !Invalid) {
13294 Diag(D.getIdentifierLoc(), diag::err_qualified_catch_declarator)
13295 << D.getCXXScopeSpec().getRange();
13299 VarDecl *ExDecl = BuildExceptionDeclaration(S, TInfo,
13301 D.getIdentifierLoc(),
13302 D.getIdentifier());
13304 ExDecl->setInvalidDecl();
13306 // Add the exception declaration into this scope.
13308 PushOnScopeChains(ExDecl, S);
13310 CurContext->addDecl(ExDecl);
13312 ProcessDeclAttributes(S, ExDecl, D);
13316 Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13318 Expr *AssertMessageExpr,
13319 SourceLocation RParenLoc) {
13320 StringLiteral *AssertMessage =
13321 AssertMessageExpr ? cast<StringLiteral>(AssertMessageExpr) : nullptr;
13323 if (DiagnoseUnexpandedParameterPack(AssertExpr, UPPC_StaticAssertExpression))
13326 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
13327 AssertMessage, RParenLoc, false);
13330 Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
13332 StringLiteral *AssertMessage,
13333 SourceLocation RParenLoc,
13335 assert(AssertExpr != nullptr && "Expected non-null condition");
13336 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
13338 // In a static_assert-declaration, the constant-expression shall be a
13339 // constant expression that can be contextually converted to bool.
13340 ExprResult Converted = PerformContextuallyConvertToBool(AssertExpr);
13341 if (Converted.isInvalid())
13345 if (!Failed && VerifyIntegerConstantExpression(Converted.get(), &Cond,
13346 diag::err_static_assert_expression_is_not_constant,
13347 /*AllowFold=*/false).isInvalid())
13350 if (!Failed && !Cond) {
13351 SmallString<256> MsgBuffer;
13352 llvm::raw_svector_ostream Msg(MsgBuffer);
13354 AssertMessage->printPretty(Msg, nullptr, getPrintingPolicy());
13356 Expr *InnerCond = nullptr;
13357 std::string InnerCondDescription;
13358 std::tie(InnerCond, InnerCondDescription) =
13359 findFailedBooleanCondition(Converted.get(),
13360 /*AllowTopLevelCond=*/false);
13362 Diag(StaticAssertLoc, diag::err_static_assert_requirement_failed)
13363 << InnerCondDescription << !AssertMessage
13364 << Msg.str() << InnerCond->getSourceRange();
13366 Diag(StaticAssertLoc, diag::err_static_assert_failed)
13367 << !AssertMessage << Msg.str() << AssertExpr->getSourceRange();
13373 ExprResult FullAssertExpr = ActOnFinishFullExpr(AssertExpr, StaticAssertLoc,
13374 /*DiscardedValue*/false,
13375 /*IsConstexpr*/true);
13376 if (FullAssertExpr.isInvalid())
13379 AssertExpr = FullAssertExpr.get();
13381 Decl *Decl = StaticAssertDecl::Create(Context, CurContext, StaticAssertLoc,
13382 AssertExpr, AssertMessage, RParenLoc,
13385 CurContext->addDecl(Decl);
13389 /// \brief Perform semantic analysis of the given friend type declaration.
13391 /// \returns A friend declaration that.
13392 FriendDecl *Sema::CheckFriendTypeDecl(SourceLocation LocStart,
13393 SourceLocation FriendLoc,
13394 TypeSourceInfo *TSInfo) {
13395 assert(TSInfo && "NULL TypeSourceInfo for friend type declaration");
13397 QualType T = TSInfo->getType();
13398 SourceRange TypeRange = TSInfo->getTypeLoc().getLocalSourceRange();
13400 // C++03 [class.friend]p2:
13401 // An elaborated-type-specifier shall be used in a friend declaration
13404 // * The class-key of the elaborated-type-specifier is required.
13405 if (!CodeSynthesisContexts.empty()) {
13406 // Do not complain about the form of friend template types during any kind
13407 // of code synthesis. For template instantiation, we will have complained
13408 // when the template was defined.
13410 if (!T->isElaboratedTypeSpecifier()) {
13411 // If we evaluated the type to a record type, suggest putting
13413 if (const RecordType *RT = T->getAs<RecordType>()) {
13414 RecordDecl *RD = RT->getDecl();
13416 SmallString<16> InsertionText(" ");
13417 InsertionText += RD->getKindName();
13419 Diag(TypeRange.getBegin(),
13420 getLangOpts().CPlusPlus11 ?
13421 diag::warn_cxx98_compat_unelaborated_friend_type :
13422 diag::ext_unelaborated_friend_type)
13423 << (unsigned) RD->getTagKind()
13425 << FixItHint::CreateInsertion(getLocForEndOfToken(FriendLoc),
13429 getLangOpts().CPlusPlus11 ?
13430 diag::warn_cxx98_compat_nonclass_type_friend :
13431 diag::ext_nonclass_type_friend)
13435 } else if (T->getAs<EnumType>()) {
13437 getLangOpts().CPlusPlus11 ?
13438 diag::warn_cxx98_compat_enum_friend :
13439 diag::ext_enum_friend)
13444 // C++11 [class.friend]p3:
13445 // A friend declaration that does not declare a function shall have one
13446 // of the following forms:
13447 // friend elaborated-type-specifier ;
13448 // friend simple-type-specifier ;
13449 // friend typename-specifier ;
13450 if (getLangOpts().CPlusPlus11 && LocStart != FriendLoc)
13451 Diag(FriendLoc, diag::err_friend_not_first_in_declaration) << T;
13454 // If the type specifier in a friend declaration designates a (possibly
13455 // cv-qualified) class type, that class is declared as a friend; otherwise,
13456 // the friend declaration is ignored.
13457 return FriendDecl::Create(Context, CurContext,
13458 TSInfo->getTypeLoc().getLocStart(), TSInfo,
13462 /// Handle a friend tag declaration where the scope specifier was
13464 Decl *Sema::ActOnTemplatedFriendTag(Scope *S, SourceLocation FriendLoc,
13465 unsigned TagSpec, SourceLocation TagLoc,
13467 IdentifierInfo *Name,
13468 SourceLocation NameLoc,
13469 AttributeList *Attr,
13470 MultiTemplateParamsArg TempParamLists) {
13471 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TagSpec);
13473 bool IsMemberSpecialization = false;
13474 bool Invalid = false;
13476 if (TemplateParameterList *TemplateParams =
13477 MatchTemplateParametersToScopeSpecifier(
13478 TagLoc, NameLoc, SS, nullptr, TempParamLists, /*friend*/ true,
13479 IsMemberSpecialization, Invalid)) {
13480 if (TemplateParams->size() > 0) {
13481 // This is a declaration of a class template.
13485 return CheckClassTemplate(S, TagSpec, TUK_Friend, TagLoc, SS, Name,
13486 NameLoc, Attr, TemplateParams, AS_public,
13487 /*ModulePrivateLoc=*/SourceLocation(),
13488 FriendLoc, TempParamLists.size() - 1,
13489 TempParamLists.data()).get();
13491 // The "template<>" header is extraneous.
13492 Diag(TemplateParams->getTemplateLoc(), diag::err_template_tag_noparams)
13493 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
13494 IsMemberSpecialization = true;
13498 if (Invalid) return nullptr;
13500 bool isAllExplicitSpecializations = true;
13501 for (unsigned I = TempParamLists.size(); I-- > 0; ) {
13502 if (TempParamLists[I]->size()) {
13503 isAllExplicitSpecializations = false;
13508 // FIXME: don't ignore attributes.
13510 // If it's explicit specializations all the way down, just forget
13511 // about the template header and build an appropriate non-templated
13512 // friend. TODO: for source fidelity, remember the headers.
13513 if (isAllExplicitSpecializations) {
13514 if (SS.isEmpty()) {
13515 bool Owned = false;
13516 bool IsDependent = false;
13517 return ActOnTag(S, TagSpec, TUK_Friend, TagLoc, SS, Name, NameLoc,
13519 /*ModulePrivateLoc=*/SourceLocation(),
13520 MultiTemplateParamsArg(), Owned, IsDependent,
13521 /*ScopedEnumKWLoc=*/SourceLocation(),
13522 /*ScopedEnumUsesClassTag=*/false,
13523 /*UnderlyingType=*/TypeResult(),
13524 /*IsTypeSpecifier=*/false,
13525 /*IsTemplateParamOrArg=*/false);
13528 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13529 ElaboratedTypeKeyword Keyword
13530 = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13531 QualType T = CheckTypenameType(Keyword, TagLoc, QualifierLoc,
13536 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13537 if (isa<DependentNameType>(T)) {
13538 DependentNameTypeLoc TL =
13539 TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13540 TL.setElaboratedKeywordLoc(TagLoc);
13541 TL.setQualifierLoc(QualifierLoc);
13542 TL.setNameLoc(NameLoc);
13544 ElaboratedTypeLoc TL = TSI->getTypeLoc().castAs<ElaboratedTypeLoc>();
13545 TL.setElaboratedKeywordLoc(TagLoc);
13546 TL.setQualifierLoc(QualifierLoc);
13547 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(NameLoc);
13550 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13551 TSI, FriendLoc, TempParamLists);
13552 Friend->setAccess(AS_public);
13553 CurContext->addDecl(Friend);
13557 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
13561 // Handle the case of a templated-scope friend class. e.g.
13562 // template <class T> class A<T>::B;
13563 // FIXME: we don't support these right now.
13564 Diag(NameLoc, diag::warn_template_qualified_friend_unsupported)
13565 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(CurContext);
13566 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Kind);
13567 QualType T = Context.getDependentNameType(ETK, SS.getScopeRep(), Name);
13568 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
13569 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
13570 TL.setElaboratedKeywordLoc(TagLoc);
13571 TL.setQualifierLoc(SS.getWithLocInContext(Context));
13572 TL.setNameLoc(NameLoc);
13574 FriendDecl *Friend = FriendDecl::Create(Context, CurContext, NameLoc,
13575 TSI, FriendLoc, TempParamLists);
13576 Friend->setAccess(AS_public);
13577 Friend->setUnsupportedFriend(true);
13578 CurContext->addDecl(Friend);
13583 /// Handle a friend type declaration. This works in tandem with
13586 /// Notes on friend class templates:
13588 /// We generally treat friend class declarations as if they were
13589 /// declaring a class. So, for example, the elaborated type specifier
13590 /// in a friend declaration is required to obey the restrictions of a
13591 /// class-head (i.e. no typedefs in the scope chain), template
13592 /// parameters are required to match up with simple template-ids, &c.
13593 /// However, unlike when declaring a template specialization, it's
13594 /// okay to refer to a template specialization without an empty
13595 /// template parameter declaration, e.g.
13596 /// friend class A<T>::B<unsigned>;
13597 /// We permit this as a special case; if there are any template
13598 /// parameters present at all, require proper matching, i.e.
13599 /// template <> template \<class T> friend class A<int>::B;
13600 Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
13601 MultiTemplateParamsArg TempParams) {
13602 SourceLocation Loc = DS.getLocStart();
13604 assert(DS.isFriendSpecified());
13605 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13607 // Try to convert the decl specifier to a type. This works for
13608 // friend templates because ActOnTag never produces a ClassTemplateDecl
13609 // for a TUK_Friend.
13610 Declarator TheDeclarator(DS, DeclaratorContext::MemberContext);
13611 TypeSourceInfo *TSI = GetTypeForDeclarator(TheDeclarator, S);
13612 QualType T = TSI->getType();
13613 if (TheDeclarator.isInvalidType())
13616 if (DiagnoseUnexpandedParameterPack(Loc, TSI, UPPC_FriendDeclaration))
13619 // This is definitely an error in C++98. It's probably meant to
13620 // be forbidden in C++0x, too, but the specification is just
13623 // The problem is with declarations like the following:
13624 // template <T> friend A<T>::foo;
13625 // where deciding whether a class C is a friend or not now hinges
13626 // on whether there exists an instantiation of A that causes
13627 // 'foo' to equal C. There are restrictions on class-heads
13628 // (which we declare (by fiat) elaborated friend declarations to
13629 // be) that makes this tractable.
13631 // FIXME: handle "template <> friend class A<T>;", which
13632 // is possibly well-formed? Who even knows?
13633 if (TempParams.size() && !T->isElaboratedTypeSpecifier()) {
13634 Diag(Loc, diag::err_tagless_friend_type_template)
13635 << DS.getSourceRange();
13639 // C++98 [class.friend]p1: A friend of a class is a function
13640 // or class that is not a member of the class . . .
13641 // This is fixed in DR77, which just barely didn't make the C++03
13642 // deadline. It's also a very silly restriction that seriously
13643 // affects inner classes and which nobody else seems to implement;
13644 // thus we never diagnose it, not even in -pedantic.
13646 // But note that we could warn about it: it's always useless to
13647 // friend one of your own members (it's not, however, worthless to
13648 // friend a member of an arbitrary specialization of your template).
13651 if (!TempParams.empty())
13652 D = FriendTemplateDecl::Create(Context, CurContext, Loc,
13655 DS.getFriendSpecLoc());
13657 D = CheckFriendTypeDecl(Loc, DS.getFriendSpecLoc(), TSI);
13662 D->setAccess(AS_public);
13663 CurContext->addDecl(D);
13668 NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
13669 MultiTemplateParamsArg TemplateParams) {
13670 const DeclSpec &DS = D.getDeclSpec();
13672 assert(DS.isFriendSpecified());
13673 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
13675 SourceLocation Loc = D.getIdentifierLoc();
13676 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
13678 // C++ [class.friend]p1
13679 // A friend of a class is a function or class....
13680 // Note that this sees through typedefs, which is intended.
13681 // It *doesn't* see through dependent types, which is correct
13682 // according to [temp.arg.type]p3:
13683 // If a declaration acquires a function type through a
13684 // type dependent on a template-parameter and this causes
13685 // a declaration that does not use the syntactic form of a
13686 // function declarator to have a function type, the program
13688 if (!TInfo->getType()->isFunctionType()) {
13689 Diag(Loc, diag::err_unexpected_friend);
13691 // It might be worthwhile to try to recover by creating an
13692 // appropriate declaration.
13696 // C++ [namespace.memdef]p3
13697 // - If a friend declaration in a non-local class first declares a
13698 // class or function, the friend class or function is a member
13699 // of the innermost enclosing namespace.
13700 // - The name of the friend is not found by simple name lookup
13701 // until a matching declaration is provided in that namespace
13702 // scope (either before or after the class declaration granting
13704 // - If a friend function is called, its name may be found by the
13705 // name lookup that considers functions from namespaces and
13706 // classes associated with the types of the function arguments.
13707 // - When looking for a prior declaration of a class or a function
13708 // declared as a friend, scopes outside the innermost enclosing
13709 // namespace scope are not considered.
13711 CXXScopeSpec &SS = D.getCXXScopeSpec();
13712 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
13713 DeclarationName Name = NameInfo.getName();
13716 // Check for unexpanded parameter packs.
13717 if (DiagnoseUnexpandedParameterPack(Loc, TInfo, UPPC_FriendDeclaration) ||
13718 DiagnoseUnexpandedParameterPack(NameInfo, UPPC_FriendDeclaration) ||
13719 DiagnoseUnexpandedParameterPack(SS, UPPC_FriendDeclaration))
13722 // The context we found the declaration in, or in which we should
13723 // create the declaration.
13725 Scope *DCScope = S;
13726 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13727 ForExternalRedeclaration);
13729 // There are five cases here.
13730 // - There's no scope specifier and we're in a local class. Only look
13731 // for functions declared in the immediately-enclosing block scope.
13732 // We recover from invalid scope qualifiers as if they just weren't there.
13733 FunctionDecl *FunctionContainingLocalClass = nullptr;
13734 if ((SS.isInvalid() || !SS.isSet()) &&
13735 (FunctionContainingLocalClass =
13736 cast<CXXRecordDecl>(CurContext)->isLocalClass())) {
13737 // C++11 [class.friend]p11:
13738 // If a friend declaration appears in a local class and the name
13739 // specified is an unqualified name, a prior declaration is
13740 // looked up without considering scopes that are outside the
13741 // innermost enclosing non-class scope. For a friend function
13742 // declaration, if there is no prior declaration, the program is
13745 // Find the innermost enclosing non-class scope. This is the block
13746 // scope containing the local class definition (or for a nested class,
13747 // the outer local class).
13748 DCScope = S->getFnParent();
13750 // Look up the function name in the scope.
13751 Previous.clear(LookupLocalFriendName);
13752 LookupName(Previous, S, /*AllowBuiltinCreation*/false);
13754 if (!Previous.empty()) {
13755 // All possible previous declarations must have the same context:
13756 // either they were declared at block scope or they are members of
13757 // one of the enclosing local classes.
13758 DC = Previous.getRepresentativeDecl()->getDeclContext();
13760 // This is ill-formed, but provide the context that we would have
13761 // declared the function in, if we were permitted to, for error recovery.
13762 DC = FunctionContainingLocalClass;
13764 adjustContextForLocalExternDecl(DC);
13766 // C++ [class.friend]p6:
13767 // A function can be defined in a friend declaration of a class if and
13768 // only if the class is a non-local class (9.8), the function name is
13769 // unqualified, and the function has namespace scope.
13770 if (D.isFunctionDefinition()) {
13771 Diag(NameInfo.getBeginLoc(), diag::err_friend_def_in_local_class);
13774 // - There's no scope specifier, in which case we just go to the
13775 // appropriate scope and look for a function or function template
13776 // there as appropriate.
13777 } else if (SS.isInvalid() || !SS.isSet()) {
13778 // C++11 [namespace.memdef]p3:
13779 // If the name in a friend declaration is neither qualified nor
13780 // a template-id and the declaration is a function or an
13781 // elaborated-type-specifier, the lookup to determine whether
13782 // the entity has been previously declared shall not consider
13783 // any scopes outside the innermost enclosing namespace.
13784 bool isTemplateId =
13785 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
13787 // Find the appropriate context according to the above.
13790 // Skip class contexts. If someone can cite chapter and verse
13791 // for this behavior, that would be nice --- it's what GCC and
13792 // EDG do, and it seems like a reasonable intent, but the spec
13793 // really only says that checks for unqualified existing
13794 // declarations should stop at the nearest enclosing namespace,
13795 // not that they should only consider the nearest enclosing
13797 while (DC->isRecord())
13798 DC = DC->getParent();
13800 DeclContext *LookupDC = DC;
13801 while (LookupDC->isTransparentContext())
13802 LookupDC = LookupDC->getParent();
13805 LookupQualifiedName(Previous, LookupDC);
13807 if (!Previous.empty()) {
13812 if (isTemplateId) {
13813 if (isa<TranslationUnitDecl>(LookupDC)) break;
13815 if (LookupDC->isFileContext()) break;
13817 LookupDC = LookupDC->getParent();
13820 DCScope = getScopeForDeclContext(S, DC);
13822 // - There's a non-dependent scope specifier, in which case we
13823 // compute it and do a previous lookup there for a function
13824 // or function template.
13825 } else if (!SS.getScopeRep()->isDependent()) {
13826 DC = computeDeclContext(SS);
13827 if (!DC) return nullptr;
13829 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
13831 LookupQualifiedName(Previous, DC);
13833 // Ignore things found implicitly in the wrong scope.
13834 // TODO: better diagnostics for this case. Suggesting the right
13835 // qualified scope would be nice...
13836 LookupResult::Filter F = Previous.makeFilter();
13837 while (F.hasNext()) {
13838 NamedDecl *D = F.next();
13839 if (!DC->InEnclosingNamespaceSetOf(
13840 D->getDeclContext()->getRedeclContext()))
13845 if (Previous.empty()) {
13846 D.setInvalidType();
13847 Diag(Loc, diag::err_qualified_friend_not_found)
13848 << Name << TInfo->getType();
13852 // C++ [class.friend]p1: A friend of a class is a function or
13853 // class that is not a member of the class . . .
13854 if (DC->Equals(CurContext))
13855 Diag(DS.getFriendSpecLoc(),
13856 getLangOpts().CPlusPlus11 ?
13857 diag::warn_cxx98_compat_friend_is_member :
13858 diag::err_friend_is_member);
13860 if (D.isFunctionDefinition()) {
13861 // C++ [class.friend]p6:
13862 // A function can be defined in a friend declaration of a class if and
13863 // only if the class is a non-local class (9.8), the function name is
13864 // unqualified, and the function has namespace scope.
13865 SemaDiagnosticBuilder DB
13866 = Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def);
13868 DB << SS.getScopeRep();
13869 if (DC->isFileContext())
13870 DB << FixItHint::CreateRemoval(SS.getRange());
13874 // - There's a scope specifier that does not match any template
13875 // parameter lists, in which case we use some arbitrary context,
13876 // create a method or method template, and wait for instantiation.
13877 // - There's a scope specifier that does match some template
13878 // parameter lists, which we don't handle right now.
13880 if (D.isFunctionDefinition()) {
13881 // C++ [class.friend]p6:
13882 // A function can be defined in a friend declaration of a class if and
13883 // only if the class is a non-local class (9.8), the function name is
13884 // unqualified, and the function has namespace scope.
13885 Diag(SS.getRange().getBegin(), diag::err_qualified_friend_def)
13886 << SS.getScopeRep();
13890 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
13893 if (!DC->isRecord()) {
13895 switch (D.getName().getKind()) {
13896 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13897 case UnqualifiedIdKind::IK_ConstructorName:
13900 case UnqualifiedIdKind::IK_DestructorName:
13903 case UnqualifiedIdKind::IK_ConversionFunctionId:
13906 case UnqualifiedIdKind::IK_DeductionGuideName:
13909 case UnqualifiedIdKind::IK_Identifier:
13910 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13911 case UnqualifiedIdKind::IK_LiteralOperatorId:
13912 case UnqualifiedIdKind::IK_OperatorFunctionId:
13913 case UnqualifiedIdKind::IK_TemplateId:
13916 // This implies that it has to be an operator or function.
13917 if (DiagArg >= 0) {
13918 Diag(Loc, diag::err_introducing_special_friend) << DiagArg;
13923 // FIXME: This is an egregious hack to cope with cases where the scope stack
13924 // does not contain the declaration context, i.e., in an out-of-line
13925 // definition of a class.
13926 Scope FakeDCScope(S, Scope::DeclScope, Diags);
13928 FakeDCScope.setEntity(DC);
13929 DCScope = &FakeDCScope;
13932 bool AddToScope = true;
13933 NamedDecl *ND = ActOnFunctionDeclarator(DCScope, D, DC, TInfo, Previous,
13934 TemplateParams, AddToScope);
13935 if (!ND) return nullptr;
13937 assert(ND->getLexicalDeclContext() == CurContext);
13939 // If we performed typo correction, we might have added a scope specifier
13940 // and changed the decl context.
13941 DC = ND->getDeclContext();
13943 // Add the function declaration to the appropriate lookup tables,
13944 // adjusting the redeclarations list as necessary. We don't
13945 // want to do this yet if the friending class is dependent.
13947 // Also update the scope-based lookup if the target context's
13948 // lookup context is in lexical scope.
13949 if (!CurContext->isDependentContext()) {
13950 DC = DC->getRedeclContext();
13951 DC->makeDeclVisibleInContext(ND);
13952 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
13953 PushOnScopeChains(ND, EnclosingScope, /*AddToContext=*/ false);
13956 FriendDecl *FrD = FriendDecl::Create(Context, CurContext,
13957 D.getIdentifierLoc(), ND,
13958 DS.getFriendSpecLoc());
13959 FrD->setAccess(AS_public);
13960 CurContext->addDecl(FrD);
13962 if (ND->isInvalidDecl()) {
13963 FrD->setInvalidDecl();
13965 if (DC->isRecord()) CheckFriendAccess(ND);
13968 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(ND))
13969 FD = FTD->getTemplatedDecl();
13971 FD = cast<FunctionDecl>(ND);
13973 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
13974 // default argument expression, that declaration shall be a definition
13975 // and shall be the only declaration of the function or function
13976 // template in the translation unit.
13977 if (functionDeclHasDefaultArgument(FD)) {
13978 // We can't look at FD->getPreviousDecl() because it may not have been set
13979 // if we're in a dependent context. If the function is known to be a
13980 // redeclaration, we will have narrowed Previous down to the right decl.
13981 if (D.isRedeclaration()) {
13982 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
13983 Diag(Previous.getRepresentativeDecl()->getLocation(),
13984 diag::note_previous_declaration);
13985 } else if (!D.isFunctionDefinition())
13986 Diag(FD->getLocation(), diag::err_friend_decl_with_def_arg_must_be_def);
13989 // Mark templated-scope function declarations as unsupported.
13990 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
13991 Diag(FD->getLocation(), diag::warn_template_qualified_friend_unsupported)
13992 << SS.getScopeRep() << SS.getRange()
13993 << cast<CXXRecordDecl>(CurContext);
13994 FrD->setUnsupportedFriend(true);
14001 void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc) {
14002 AdjustDeclIfTemplate(Dcl);
14004 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Dcl);
14006 Diag(DelLoc, diag::err_deleted_non_function);
14010 // Deleted function does not have a body.
14011 Fn->setWillHaveBody(false);
14013 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
14014 // Don't consider the implicit declaration we generate for explicit
14015 // specializations. FIXME: Do not generate these implicit declarations.
14016 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
14017 Prev->getPreviousDecl()) &&
14018 !Prev->isDefined()) {
14019 Diag(DelLoc, diag::err_deleted_decl_not_first);
14020 Diag(Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
14021 Prev->isImplicit() ? diag::note_previous_implicit_declaration
14022 : diag::note_previous_declaration);
14024 // If the declaration wasn't the first, we delete the function anyway for
14026 Fn = Fn->getCanonicalDecl();
14029 // dllimport/dllexport cannot be deleted.
14030 if (const InheritableAttr *DLLAttr = getDLLAttr(Fn)) {
14031 Diag(Fn->getLocation(), diag::err_attribute_dll_deleted) << DLLAttr;
14032 Fn->setInvalidDecl();
14035 if (Fn->isDeleted())
14038 // See if we're deleting a function which is already known to override a
14039 // non-deleted virtual function.
14040 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Fn)) {
14041 bool IssuedDiagnostic = false;
14042 for (const CXXMethodDecl *O : MD->overridden_methods()) {
14043 if (!(*MD->begin_overridden_methods())->isDeleted()) {
14044 if (!IssuedDiagnostic) {
14045 Diag(DelLoc, diag::err_deleted_override) << MD->getDeclName();
14046 IssuedDiagnostic = true;
14048 Diag(O->getLocation(), diag::note_overridden_virtual_function);
14051 // If this function was implicitly deleted because it was defaulted,
14052 // explain why it was deleted.
14053 if (IssuedDiagnostic && MD->isDefaulted())
14054 ShouldDeleteSpecialMember(MD, getSpecialMember(MD), nullptr,
14058 // C++11 [basic.start.main]p3:
14059 // A program that defines main as deleted [...] is ill-formed.
14061 Diag(DelLoc, diag::err_deleted_main);
14063 // C++11 [dcl.fct.def.delete]p4:
14064 // A deleted function is implicitly inline.
14065 Fn->setImplicitlyInline();
14066 Fn->setDeletedAsWritten();
14069 void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
14070 CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Dcl);
14073 if (MD->getParent()->isDependentType()) {
14074 MD->setDefaulted();
14075 MD->setExplicitlyDefaulted();
14079 CXXSpecialMember Member = getSpecialMember(MD);
14080 if (Member == CXXInvalid) {
14081 if (!MD->isInvalidDecl())
14082 Diag(DefaultLoc, diag::err_default_special_members);
14086 MD->setDefaulted();
14087 MD->setExplicitlyDefaulted();
14089 // Unset that we will have a body for this function. We might not,
14090 // if it turns out to be trivial, and we don't need this marking now
14091 // that we've marked it as defaulted.
14092 MD->setWillHaveBody(false);
14094 // If this definition appears within the record, do the checking when
14095 // the record is complete.
14096 const FunctionDecl *Primary = MD;
14097 if (const FunctionDecl *Pattern = MD->getTemplateInstantiationPattern())
14098 // Ask the template instantiation pattern that actually had the
14099 // '= default' on it.
14102 // If the method was defaulted on its first declaration, we will have
14103 // already performed the checking in CheckCompletedCXXClass. Such a
14104 // declaration doesn't trigger an implicit definition.
14105 if (Primary->getCanonicalDecl()->isDefaulted())
14108 CheckExplicitlyDefaultedSpecialMember(MD);
14110 if (!MD->isInvalidDecl())
14111 DefineImplicitSpecialMember(*this, MD, DefaultLoc);
14113 Diag(DefaultLoc, diag::err_default_special_members);
14117 static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
14118 for (Stmt *SubStmt : S->children()) {
14121 if (isa<ReturnStmt>(SubStmt))
14122 Self.Diag(SubStmt->getLocStart(),
14123 diag::err_return_in_constructor_handler);
14124 if (!isa<Expr>(SubStmt))
14125 SearchForReturnInStmt(Self, SubStmt);
14129 void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
14130 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
14131 CXXCatchStmt *Handler = TryBlock->getHandler(I);
14132 SearchForReturnInStmt(*this, Handler);
14136 bool Sema::CheckOverridingFunctionAttributes(const CXXMethodDecl *New,
14137 const CXXMethodDecl *Old) {
14138 const auto *NewFT = New->getType()->getAs<FunctionProtoType>();
14139 const auto *OldFT = Old->getType()->getAs<FunctionProtoType>();
14141 if (OldFT->hasExtParameterInfos()) {
14142 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
14143 // A parameter of the overriding method should be annotated with noescape
14144 // if the corresponding parameter of the overridden method is annotated.
14145 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
14146 !NewFT->getExtParameterInfo(I).isNoEscape()) {
14147 Diag(New->getParamDecl(I)->getLocation(),
14148 diag::warn_overriding_method_missing_noescape);
14149 Diag(Old->getParamDecl(I)->getLocation(),
14150 diag::note_overridden_marked_noescape);
14154 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
14156 // If the calling conventions match, everything is fine
14157 if (NewCC == OldCC)
14160 // If the calling conventions mismatch because the new function is static,
14161 // suppress the calling convention mismatch error; the error about static
14162 // function override (err_static_overrides_virtual from
14163 // Sema::CheckFunctionDeclaration) is more clear.
14164 if (New->getStorageClass() == SC_Static)
14167 Diag(New->getLocation(),
14168 diag::err_conflicting_overriding_cc_attributes)
14169 << New->getDeclName() << New->getType() << Old->getType();
14170 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
14174 bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
14175 const CXXMethodDecl *Old) {
14176 QualType NewTy = New->getType()->getAs<FunctionType>()->getReturnType();
14177 QualType OldTy = Old->getType()->getAs<FunctionType>()->getReturnType();
14179 if (Context.hasSameType(NewTy, OldTy) ||
14180 NewTy->isDependentType() || OldTy->isDependentType())
14183 // Check if the return types are covariant
14184 QualType NewClassTy, OldClassTy;
14186 /// Both types must be pointers or references to classes.
14187 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
14188 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
14189 NewClassTy = NewPT->getPointeeType();
14190 OldClassTy = OldPT->getPointeeType();
14192 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
14193 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
14194 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
14195 NewClassTy = NewRT->getPointeeType();
14196 OldClassTy = OldRT->getPointeeType();
14201 // The return types aren't either both pointers or references to a class type.
14202 if (NewClassTy.isNull()) {
14203 Diag(New->getLocation(),
14204 diag::err_different_return_type_for_overriding_virtual_function)
14205 << New->getDeclName() << NewTy << OldTy
14206 << New->getReturnTypeSourceRange();
14207 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14208 << Old->getReturnTypeSourceRange();
14213 if (!Context.hasSameUnqualifiedType(NewClassTy, OldClassTy)) {
14214 // C++14 [class.virtual]p8:
14215 // If the class type in the covariant return type of D::f differs from
14216 // that of B::f, the class type in the return type of D::f shall be
14217 // complete at the point of declaration of D::f or shall be the class
14219 if (const RecordType *RT = NewClassTy->getAs<RecordType>()) {
14220 if (!RT->isBeingDefined() &&
14221 RequireCompleteType(New->getLocation(), NewClassTy,
14222 diag::err_covariant_return_incomplete,
14223 New->getDeclName()))
14227 // Check if the new class derives from the old class.
14228 if (!IsDerivedFrom(New->getLocation(), NewClassTy, OldClassTy)) {
14229 Diag(New->getLocation(), diag::err_covariant_return_not_derived)
14230 << New->getDeclName() << NewTy << OldTy
14231 << New->getReturnTypeSourceRange();
14232 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14233 << Old->getReturnTypeSourceRange();
14237 // Check if we the conversion from derived to base is valid.
14238 if (CheckDerivedToBaseConversion(
14239 NewClassTy, OldClassTy,
14240 diag::err_covariant_return_inaccessible_base,
14241 diag::err_covariant_return_ambiguous_derived_to_base_conv,
14242 New->getLocation(), New->getReturnTypeSourceRange(),
14243 New->getDeclName(), nullptr)) {
14244 // FIXME: this note won't trigger for delayed access control
14245 // diagnostics, and it's impossible to get an undelayed error
14246 // here from access control during the original parse because
14247 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
14248 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14249 << Old->getReturnTypeSourceRange();
14254 // The qualifiers of the return types must be the same.
14255 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
14256 Diag(New->getLocation(),
14257 diag::err_covariant_return_type_different_qualifications)
14258 << New->getDeclName() << NewTy << OldTy
14259 << New->getReturnTypeSourceRange();
14260 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14261 << Old->getReturnTypeSourceRange();
14266 // The new class type must have the same or less qualifiers as the old type.
14267 if (NewClassTy.isMoreQualifiedThan(OldClassTy)) {
14268 Diag(New->getLocation(),
14269 diag::err_covariant_return_type_class_type_more_qualified)
14270 << New->getDeclName() << NewTy << OldTy
14271 << New->getReturnTypeSourceRange();
14272 Diag(Old->getLocation(), diag::note_overridden_virtual_function)
14273 << Old->getReturnTypeSourceRange();
14280 /// \brief Mark the given method pure.
14282 /// \param Method the method to be marked pure.
14284 /// \param InitRange the source range that covers the "0" initializer.
14285 bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
14286 SourceLocation EndLoc = InitRange.getEnd();
14287 if (EndLoc.isValid())
14288 Method->setRangeEnd(EndLoc);
14290 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
14295 if (!Method->isInvalidDecl())
14296 Diag(Method->getLocation(), diag::err_non_virtual_pure)
14297 << Method->getDeclName() << InitRange;
14301 void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
14302 if (D->getFriendObjectKind())
14303 Diag(D->getLocation(), diag::err_pure_friend);
14304 else if (auto *M = dyn_cast<CXXMethodDecl>(D))
14305 CheckPureMethod(M, ZeroLoc);
14307 Diag(D->getLocation(), diag::err_illegal_initializer);
14310 /// \brief Determine whether the given declaration is a global variable or
14311 /// static data member.
14312 static bool isNonlocalVariable(const Decl *D) {
14313 if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(D))
14314 return Var->hasGlobalStorage();
14319 /// Invoked when we are about to parse an initializer for the declaration
14322 /// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
14323 /// static data member of class X, names should be looked up in the scope of
14324 /// class X. If the declaration had a scope specifier, a scope will have
14325 /// been created and passed in for this purpose. Otherwise, S will be null.
14326 void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
14327 // If there is no declaration, there was an error parsing it.
14328 if (!D || D->isInvalidDecl())
14331 // We will always have a nested name specifier here, but this declaration
14332 // might not be out of line if the specifier names the current namespace:
14335 if (S && D->isOutOfLine())
14336 EnterDeclaratorContext(S, D->getDeclContext());
14338 // If we are parsing the initializer for a static data member, push a
14339 // new expression evaluation context that is associated with this static
14341 if (isNonlocalVariable(D))
14342 PushExpressionEvaluationContext(
14343 ExpressionEvaluationContext::PotentiallyEvaluated, D);
14346 /// Invoked after we are finished parsing an initializer for the declaration D.
14347 void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
14348 // If there is no declaration, there was an error parsing it.
14349 if (!D || D->isInvalidDecl())
14352 if (isNonlocalVariable(D))
14353 PopExpressionEvaluationContext();
14355 if (S && D->isOutOfLine())
14356 ExitDeclaratorContext(S);
14359 /// ActOnCXXConditionDeclarationExpr - Parsed a condition declaration of a
14360 /// C++ if/switch/while/for statement.
14361 /// e.g: "if (int x = f()) {...}"
14362 DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
14364 // The declarator shall not specify a function or an array.
14365 // The type-specifier-seq shall not contain typedef and shall not declare a
14366 // new class or enumeration.
14367 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
14368 "Parser allowed 'typedef' as storage class of condition decl.");
14370 Decl *Dcl = ActOnDeclarator(S, D);
14374 if (isa<FunctionDecl>(Dcl)) { // The declarator shall not specify a function.
14375 Diag(Dcl->getLocation(), diag::err_invalid_use_of_function_type)
14376 << D.getSourceRange();
14383 void Sema::LoadExternalVTableUses() {
14384 if (!ExternalSource)
14387 SmallVector<ExternalVTableUse, 4> VTables;
14388 ExternalSource->ReadUsedVTables(VTables);
14389 SmallVector<VTableUse, 4> NewUses;
14390 for (unsigned I = 0, N = VTables.size(); I != N; ++I) {
14391 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos
14392 = VTablesUsed.find(VTables[I].Record);
14393 // Even if a definition wasn't required before, it may be required now.
14394 if (Pos != VTablesUsed.end()) {
14395 if (!Pos->second && VTables[I].DefinitionRequired)
14396 Pos->second = true;
14400 VTablesUsed[VTables[I].Record] = VTables[I].DefinitionRequired;
14401 NewUses.push_back(VTableUse(VTables[I].Record, VTables[I].Location));
14404 VTableUses.insert(VTableUses.begin(), NewUses.begin(), NewUses.end());
14407 void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
14408 bool DefinitionRequired) {
14409 // Ignore any vtable uses in unevaluated operands or for classes that do
14410 // not have a vtable.
14411 if (!Class->isDynamicClass() || Class->isDependentContext() ||
14412 CurContext->isDependentContext() || isUnevaluatedContext())
14415 // Try to insert this class into the map.
14416 LoadExternalVTableUses();
14417 Class = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14418 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
14419 Pos = VTablesUsed.insert(std::make_pair(Class, DefinitionRequired));
14421 // If we already had an entry, check to see if we are promoting this vtable
14422 // to require a definition. If so, we need to reappend to the VTableUses
14423 // list, since we may have already processed the first entry.
14424 if (DefinitionRequired && !Pos.first->second) {
14425 Pos.first->second = true;
14427 // Otherwise, we can early exit.
14431 // The Microsoft ABI requires that we perform the destructor body
14432 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
14433 // the deleting destructor is emitted with the vtable, not with the
14434 // destructor definition as in the Itanium ABI.
14435 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
14436 CXXDestructorDecl *DD = Class->getDestructor();
14437 if (DD && DD->isVirtual() && !DD->isDeleted()) {
14438 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
14439 // If this is an out-of-line declaration, marking it referenced will
14440 // not do anything. Manually call CheckDestructor to look up operator
14442 ContextRAII SavedContext(*this, DD);
14443 CheckDestructor(DD);
14445 MarkFunctionReferenced(Loc, Class->getDestructor());
14451 // Local classes need to have their virtual members marked
14452 // immediately. For all other classes, we mark their virtual members
14453 // at the end of the translation unit.
14454 if (Class->isLocalClass())
14455 MarkVirtualMembersReferenced(Loc, Class);
14457 VTableUses.push_back(std::make_pair(Class, Loc));
14460 bool Sema::DefineUsedVTables() {
14461 LoadExternalVTableUses();
14462 if (VTableUses.empty())
14465 // Note: The VTableUses vector could grow as a result of marking
14466 // the members of a class as "used", so we check the size each
14467 // time through the loop and prefer indices (which are stable) to
14468 // iterators (which are not).
14469 bool DefinedAnything = false;
14470 for (unsigned I = 0; I != VTableUses.size(); ++I) {
14471 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
14474 TemplateSpecializationKind ClassTSK =
14475 Class->getTemplateSpecializationKind();
14477 SourceLocation Loc = VTableUses[I].second;
14479 bool DefineVTable = true;
14481 // If this class has a key function, but that key function is
14482 // defined in another translation unit, we don't need to emit the
14483 // vtable even though we're using it.
14484 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(Class);
14485 if (KeyFunction && !KeyFunction->hasBody()) {
14486 // The key function is in another translation unit.
14487 DefineVTable = false;
14488 TemplateSpecializationKind TSK =
14489 KeyFunction->getTemplateSpecializationKind();
14490 assert(TSK != TSK_ExplicitInstantiationDefinition &&
14491 TSK != TSK_ImplicitInstantiation &&
14492 "Instantiations don't have key functions");
14494 } else if (!KeyFunction) {
14495 // If we have a class with no key function that is the subject
14496 // of an explicit instantiation declaration, suppress the
14497 // vtable; it will live with the explicit instantiation
14499 bool IsExplicitInstantiationDeclaration =
14500 ClassTSK == TSK_ExplicitInstantiationDeclaration;
14501 for (auto R : Class->redecls()) {
14502 TemplateSpecializationKind TSK
14503 = cast<CXXRecordDecl>(R)->getTemplateSpecializationKind();
14504 if (TSK == TSK_ExplicitInstantiationDeclaration)
14505 IsExplicitInstantiationDeclaration = true;
14506 else if (TSK == TSK_ExplicitInstantiationDefinition) {
14507 IsExplicitInstantiationDeclaration = false;
14512 if (IsExplicitInstantiationDeclaration)
14513 DefineVTable = false;
14516 // The exception specifications for all virtual members may be needed even
14517 // if we are not providing an authoritative form of the vtable in this TU.
14518 // We may choose to emit it available_externally anyway.
14519 if (!DefineVTable) {
14520 MarkVirtualMemberExceptionSpecsNeeded(Loc, Class);
14524 // Mark all of the virtual members of this class as referenced, so
14525 // that we can build a vtable. Then, tell the AST consumer that a
14526 // vtable for this class is required.
14527 DefinedAnything = true;
14528 MarkVirtualMembersReferenced(Loc, Class);
14529 CXXRecordDecl *Canonical = cast<CXXRecordDecl>(Class->getCanonicalDecl());
14530 if (VTablesUsed[Canonical])
14531 Consumer.HandleVTable(Class);
14533 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
14534 // no key function or the key function is inlined. Don't warn in C++ ABIs
14535 // that lack key functions, since the user won't be able to make one.
14536 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
14537 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation) {
14538 const FunctionDecl *KeyFunctionDef = nullptr;
14539 if (!KeyFunction || (KeyFunction->hasBody(KeyFunctionDef) &&
14540 KeyFunctionDef->isInlined())) {
14541 Diag(Class->getLocation(),
14542 ClassTSK == TSK_ExplicitInstantiationDefinition
14543 ? diag::warn_weak_template_vtable
14544 : diag::warn_weak_vtable)
14549 VTableUses.clear();
14551 return DefinedAnything;
14554 void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
14555 const CXXRecordDecl *RD) {
14556 for (const auto *I : RD->methods())
14557 if (I->isVirtual() && !I->isPure())
14558 ResolveExceptionSpec(Loc, I->getType()->castAs<FunctionProtoType>());
14561 void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
14562 const CXXRecordDecl *RD) {
14563 // Mark all functions which will appear in RD's vtable as used.
14564 CXXFinalOverriderMap FinalOverriders;
14565 RD->getFinalOverriders(FinalOverriders);
14566 for (CXXFinalOverriderMap::const_iterator I = FinalOverriders.begin(),
14567 E = FinalOverriders.end();
14569 for (OverridingMethods::const_iterator OI = I->second.begin(),
14570 OE = I->second.end();
14572 assert(OI->second.size() > 0 && "no final overrider");
14573 CXXMethodDecl *Overrider = OI->second.front().Method;
14575 // C++ [basic.def.odr]p2:
14576 // [...] A virtual member function is used if it is not pure. [...]
14577 if (!Overrider->isPure())
14578 MarkFunctionReferenced(Loc, Overrider);
14582 // Only classes that have virtual bases need a VTT.
14583 if (RD->getNumVBases() == 0)
14586 for (const auto &I : RD->bases()) {
14587 const CXXRecordDecl *Base =
14588 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
14589 if (Base->getNumVBases() == 0)
14591 MarkVirtualMembersReferenced(Loc, Base);
14595 /// SetIvarInitializers - This routine builds initialization ASTs for the
14596 /// Objective-C implementation whose ivars need be initialized.
14597 void Sema::SetIvarInitializers(ObjCImplementationDecl *ObjCImplementation) {
14598 if (!getLangOpts().CPlusPlus)
14600 if (ObjCInterfaceDecl *OID = ObjCImplementation->getClassInterface()) {
14601 SmallVector<ObjCIvarDecl*, 8> ivars;
14602 CollectIvarsToConstructOrDestruct(OID, ivars);
14605 SmallVector<CXXCtorInitializer*, 32> AllToInit;
14606 for (unsigned i = 0; i < ivars.size(); i++) {
14607 FieldDecl *Field = ivars[i];
14608 if (Field->isInvalidDecl())
14611 CXXCtorInitializer *Member;
14612 InitializedEntity InitEntity = InitializedEntity::InitializeMember(Field);
14613 InitializationKind InitKind =
14614 InitializationKind::CreateDefault(ObjCImplementation->getLocation());
14616 InitializationSequence InitSeq(*this, InitEntity, InitKind, None);
14617 ExprResult MemberInit =
14618 InitSeq.Perform(*this, InitEntity, InitKind, None);
14619 MemberInit = MaybeCreateExprWithCleanups(MemberInit);
14620 // Note, MemberInit could actually come back empty if no initialization
14621 // is required (e.g., because it would call a trivial default constructor)
14622 if (!MemberInit.get() || MemberInit.isInvalid())
14626 new (Context) CXXCtorInitializer(Context, Field, SourceLocation(),
14628 MemberInit.getAs<Expr>(),
14630 AllToInit.push_back(Member);
14632 // Be sure that the destructor is accessible and is marked as referenced.
14633 if (const RecordType *RecordTy =
14634 Context.getBaseElementType(Field->getType())
14635 ->getAs<RecordType>()) {
14636 CXXRecordDecl *RD = cast<CXXRecordDecl>(RecordTy->getDecl());
14637 if (CXXDestructorDecl *Destructor = LookupDestructor(RD)) {
14638 MarkFunctionReferenced(Field->getLocation(), Destructor);
14639 CheckDestructorAccess(Field->getLocation(), Destructor,
14640 PDiag(diag::err_access_dtor_ivar)
14641 << Context.getBaseElementType(Field->getType()));
14645 ObjCImplementation->setIvarInitializers(Context,
14646 AllToInit.data(), AllToInit.size());
14651 void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
14652 llvm::SmallSet<CXXConstructorDecl*, 4> &Valid,
14653 llvm::SmallSet<CXXConstructorDecl*, 4> &Invalid,
14654 llvm::SmallSet<CXXConstructorDecl*, 4> &Current,
14656 if (Ctor->isInvalidDecl())
14659 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
14661 // Target may not be determinable yet, for instance if this is a dependent
14662 // call in an uninstantiated template.
14664 const FunctionDecl *FNTarget = nullptr;
14665 (void)Target->hasBody(FNTarget);
14666 Target = const_cast<CXXConstructorDecl*>(
14667 cast_or_null<CXXConstructorDecl>(FNTarget));
14670 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
14671 // Avoid dereferencing a null pointer here.
14672 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
14674 if (!Current.insert(Canonical).second)
14677 // We know that beyond here, we aren't chaining into a cycle.
14678 if (!Target || !Target->isDelegatingConstructor() ||
14679 Target->isInvalidDecl() || Valid.count(TCanonical)) {
14680 Valid.insert(Current.begin(), Current.end());
14682 // We've hit a cycle.
14683 } else if (TCanonical == Canonical || Invalid.count(TCanonical) ||
14684 Current.count(TCanonical)) {
14685 // If we haven't diagnosed this cycle yet, do so now.
14686 if (!Invalid.count(TCanonical)) {
14687 S.Diag((*Ctor->init_begin())->getSourceLocation(),
14688 diag::warn_delegating_ctor_cycle)
14691 // Don't add a note for a function delegating directly to itself.
14692 if (TCanonical != Canonical)
14693 S.Diag(Target->getLocation(), diag::note_it_delegates_to);
14695 CXXConstructorDecl *C = Target;
14696 while (C->getCanonicalDecl() != Canonical) {
14697 const FunctionDecl *FNTarget = nullptr;
14698 (void)C->getTargetConstructor()->hasBody(FNTarget);
14699 assert(FNTarget && "Ctor cycle through bodiless function");
14701 C = const_cast<CXXConstructorDecl*>(
14702 cast<CXXConstructorDecl>(FNTarget));
14703 S.Diag(C->getLocation(), diag::note_which_delegates_to);
14707 Invalid.insert(Current.begin(), Current.end());
14710 DelegatingCycleHelper(Target, Valid, Invalid, Current, S);
14715 void Sema::CheckDelegatingCtorCycles() {
14716 llvm::SmallSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
14718 for (DelegatingCtorDeclsType::iterator
14719 I = DelegatingCtorDecls.begin(ExternalSource),
14720 E = DelegatingCtorDecls.end();
14722 DelegatingCycleHelper(*I, Valid, Invalid, Current, *this);
14724 for (llvm::SmallSet<CXXConstructorDecl *, 4>::iterator CI = Invalid.begin(),
14725 CE = Invalid.end();
14727 (*CI)->setInvalidDecl();
14731 /// \brief AST visitor that finds references to the 'this' expression.
14732 class FindCXXThisExpr : public RecursiveASTVisitor<FindCXXThisExpr> {
14736 explicit FindCXXThisExpr(Sema &S) : S(S) { }
14738 bool VisitCXXThisExpr(CXXThisExpr *E) {
14739 S.Diag(E->getLocation(), diag::err_this_static_member_func)
14740 << E->isImplicit();
14746 bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
14747 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14751 TypeLoc TL = TSInfo->getTypeLoc();
14752 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14756 // C++11 [expr.prim.general]p3:
14757 // [The expression this] shall not appear before the optional
14758 // cv-qualifier-seq and it shall not appear within the declaration of a
14759 // static member function (although its type and value category are defined
14760 // within a static member function as they are within a non-static member
14761 // function). [ Note: this is because declaration matching does not occur
14762 // until the complete declarator is known. - end note ]
14763 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14764 FindCXXThisExpr Finder(*this);
14766 // If the return type came after the cv-qualifier-seq, check it now.
14767 if (Proto->hasTrailingReturn() &&
14768 !Finder.TraverseTypeLoc(ProtoTL.getReturnLoc()))
14771 // Check the exception specification.
14772 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
14775 return checkThisInStaticMemberFunctionAttributes(Method);
14778 bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
14779 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
14783 TypeLoc TL = TSInfo->getTypeLoc();
14784 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
14788 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
14789 FindCXXThisExpr Finder(*this);
14791 switch (Proto->getExceptionSpecType()) {
14793 case EST_Uninstantiated:
14794 case EST_Unevaluated:
14795 case EST_BasicNoexcept:
14796 case EST_DynamicNone:
14801 case EST_ComputedNoexcept:
14802 if (!Finder.TraverseStmt(Proto->getNoexceptExpr()))
14807 for (const auto &E : Proto->exceptions()) {
14808 if (!Finder.TraverseType(E))
14817 bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
14818 FindCXXThisExpr Finder(*this);
14820 // Check attributes.
14821 for (const auto *A : Method->attrs()) {
14822 // FIXME: This should be emitted by tblgen.
14823 Expr *Arg = nullptr;
14824 ArrayRef<Expr *> Args;
14825 if (const auto *G = dyn_cast<GuardedByAttr>(A))
14827 else if (const auto *G = dyn_cast<PtGuardedByAttr>(A))
14829 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(A))
14830 Args = llvm::makeArrayRef(AA->args_begin(), AA->args_size());
14831 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(A))
14832 Args = llvm::makeArrayRef(AB->args_begin(), AB->args_size());
14833 else if (const auto *ETLF = dyn_cast<ExclusiveTrylockFunctionAttr>(A)) {
14834 Arg = ETLF->getSuccessValue();
14835 Args = llvm::makeArrayRef(ETLF->args_begin(), ETLF->args_size());
14836 } else if (const auto *STLF = dyn_cast<SharedTrylockFunctionAttr>(A)) {
14837 Arg = STLF->getSuccessValue();
14838 Args = llvm::makeArrayRef(STLF->args_begin(), STLF->args_size());
14839 } else if (const auto *LR = dyn_cast<LockReturnedAttr>(A))
14840 Arg = LR->getArg();
14841 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(A))
14842 Args = llvm::makeArrayRef(LE->args_begin(), LE->args_size());
14843 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(A))
14844 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14845 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(A))
14846 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14847 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(A))
14848 Args = llvm::makeArrayRef(AC->args_begin(), AC->args_size());
14849 else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(A))
14850 Args = llvm::makeArrayRef(RC->args_begin(), RC->args_size());
14852 if (Arg && !Finder.TraverseStmt(Arg))
14855 for (unsigned I = 0, N = Args.size(); I != N; ++I) {
14856 if (!Finder.TraverseStmt(Args[I]))
14864 void Sema::checkExceptionSpecification(
14865 bool IsTopLevel, ExceptionSpecificationType EST,
14866 ArrayRef<ParsedType> DynamicExceptions,
14867 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
14868 SmallVectorImpl<QualType> &Exceptions,
14869 FunctionProtoType::ExceptionSpecInfo &ESI) {
14870 Exceptions.clear();
14872 if (EST == EST_Dynamic) {
14873 Exceptions.reserve(DynamicExceptions.size());
14874 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
14875 // FIXME: Preserve type source info.
14876 QualType ET = GetTypeFromParser(DynamicExceptions[ei]);
14879 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
14880 collectUnexpandedParameterPacks(ET, Unexpanded);
14881 if (!Unexpanded.empty()) {
14882 DiagnoseUnexpandedParameterPacks(
14883 DynamicExceptionRanges[ei].getBegin(), UPPC_ExceptionType,
14889 // Check that the type is valid for an exception spec, and
14891 if (!CheckSpecifiedExceptionType(ET, DynamicExceptionRanges[ei]))
14892 Exceptions.push_back(ET);
14894 ESI.Exceptions = Exceptions;
14898 if (EST == EST_ComputedNoexcept) {
14899 // If an error occurred, there's no expression here.
14900 if (NoexceptExpr) {
14901 assert((NoexceptExpr->isTypeDependent() ||
14902 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
14904 "Parser should have made sure that the expression is boolean");
14905 if (IsTopLevel && NoexceptExpr &&
14906 DiagnoseUnexpandedParameterPack(NoexceptExpr)) {
14907 ESI.Type = EST_BasicNoexcept;
14911 if (!NoexceptExpr->isValueDependent()) {
14912 ExprResult Result = VerifyIntegerConstantExpression(
14913 NoexceptExpr, nullptr, diag::err_noexcept_needs_constant_expression,
14914 /*AllowFold*/ false);
14915 if (Result.isInvalid()) {
14916 ESI.Type = EST_BasicNoexcept;
14919 NoexceptExpr = Result.get();
14921 ESI.NoexceptExpr = NoexceptExpr;
14927 void Sema::actOnDelayedExceptionSpecification(Decl *MethodD,
14928 ExceptionSpecificationType EST,
14929 SourceRange SpecificationRange,
14930 ArrayRef<ParsedType> DynamicExceptions,
14931 ArrayRef<SourceRange> DynamicExceptionRanges,
14932 Expr *NoexceptExpr) {
14936 // Dig out the method we're referring to.
14937 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(MethodD))
14938 MethodD = FunTmpl->getTemplatedDecl();
14940 CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(MethodD);
14944 // Check the exception specification.
14945 llvm::SmallVector<QualType, 4> Exceptions;
14946 FunctionProtoType::ExceptionSpecInfo ESI;
14947 checkExceptionSpecification(/*IsTopLevel*/true, EST, DynamicExceptions,
14948 DynamicExceptionRanges, NoexceptExpr, Exceptions,
14951 // Update the exception specification on the function type.
14952 Context.adjustExceptionSpec(Method, ESI, /*AsWritten*/true);
14954 if (Method->isStatic())
14955 checkThisInStaticMemberFunctionExceptionSpec(Method);
14957 if (Method->isVirtual()) {
14958 // Check overrides, which we previously had to delay.
14959 for (const CXXMethodDecl *O : Method->overridden_methods())
14960 CheckOverridingFunctionExceptionSpec(Method, O);
14964 /// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
14966 MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
14967 SourceLocation DeclStart,
14968 Declarator &D, Expr *BitWidth,
14969 InClassInitStyle InitStyle,
14970 AccessSpecifier AS,
14971 AttributeList *MSPropertyAttr) {
14972 IdentifierInfo *II = D.getIdentifier();
14974 Diag(DeclStart, diag::err_anonymous_property);
14977 SourceLocation Loc = D.getIdentifierLoc();
14979 TypeSourceInfo *TInfo = GetTypeForDeclarator(D, S);
14980 QualType T = TInfo->getType();
14981 if (getLangOpts().CPlusPlus) {
14982 CheckExtraCXXDefaultArguments(D);
14984 if (DiagnoseUnexpandedParameterPack(D.getIdentifierLoc(), TInfo,
14985 UPPC_DataMemberType)) {
14986 D.setInvalidType();
14988 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
14992 DiagnoseFunctionSpecifiers(D.getDeclSpec());
14994 if (D.getDeclSpec().isInlineSpecified())
14995 Diag(D.getDeclSpec().getInlineSpecLoc(), diag::err_inline_non_function)
14996 << getLangOpts().CPlusPlus17;
14997 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
14998 Diag(D.getDeclSpec().getThreadStorageClassSpecLoc(),
14999 diag::err_invalid_thread)
15000 << DeclSpec::getSpecifierName(TSCS);
15002 // Check to see if this name was declared as a member previously
15003 NamedDecl *PrevDecl = nullptr;
15004 LookupResult Previous(*this, II, Loc, LookupMemberName,
15005 ForVisibleRedeclaration);
15006 LookupName(Previous, S);
15007 switch (Previous.getResultKind()) {
15008 case LookupResult::Found:
15009 case LookupResult::FoundUnresolvedValue:
15010 PrevDecl = Previous.getAsSingle<NamedDecl>();
15013 case LookupResult::FoundOverloaded:
15014 PrevDecl = Previous.getRepresentativeDecl();
15017 case LookupResult::NotFound:
15018 case LookupResult::NotFoundInCurrentInstantiation:
15019 case LookupResult::Ambiguous:
15023 if (PrevDecl && PrevDecl->isTemplateParameter()) {
15024 // Maybe we will complain about the shadowed template parameter.
15025 DiagnoseTemplateParameterShadow(D.getIdentifierLoc(), PrevDecl);
15026 // Just pretend that we didn't see the previous declaration.
15027 PrevDecl = nullptr;
15030 if (PrevDecl && !isDeclInScope(PrevDecl, Record, S))
15031 PrevDecl = nullptr;
15033 SourceLocation TSSL = D.getLocStart();
15034 const AttributeList::PropertyData &Data = MSPropertyAttr->getPropertyData();
15035 MSPropertyDecl *NewPD = MSPropertyDecl::Create(
15036 Context, Record, Loc, II, T, TInfo, TSSL, Data.GetterId, Data.SetterId);
15037 ProcessDeclAttributes(TUScope, NewPD, D);
15038 NewPD->setAccess(AS);
15040 if (NewPD->isInvalidDecl())
15041 Record->setInvalidDecl();
15043 if (D.getDeclSpec().isModulePrivateSpecified())
15044 NewPD->setModulePrivate();
15046 if (NewPD->isInvalidDecl() && PrevDecl) {
15047 // Don't introduce NewFD into scope; there's already something
15048 // with the same name in the same scope.
15050 PushOnScopeChains(NewPD, S);
15052 Record->addDecl(NewPD);