clang 19.0.0git
SemaDeclCXX.cpp
Go to the documentation of this file.
1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
15#include "clang/AST/ASTLambda.h"
18#include "clang/AST/CharUnits.h"
20#include "clang/AST/DeclCXX.h"
23#include "clang/AST/Expr.h"
24#include "clang/AST/ExprCXX.h"
28#include "clang/AST/TypeLoc.h"
37#include "clang/Sema/DeclSpec.h"
40#include "clang/Sema/Lookup.h"
43#include "clang/Sema/Scope.h"
46#include "clang/Sema/Template.h"
47#include "llvm/ADT/ArrayRef.h"
48#include "llvm/ADT/STLExtras.h"
49#include "llvm/ADT/ScopeExit.h"
50#include "llvm/ADT/SmallString.h"
51#include "llvm/ADT/StringExtras.h"
52#include "llvm/Support/ConvertUTF.h"
53#include "llvm/Support/SaveAndRestore.h"
54#include <map>
55#include <optional>
56#include <set>
57
58using namespace clang;
59
60//===----------------------------------------------------------------------===//
61// CheckDefaultArgumentVisitor
62//===----------------------------------------------------------------------===//
63
64namespace {
65/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
66/// the default argument of a parameter to determine whether it
67/// contains any ill-formed subexpressions. For example, this will
68/// diagnose the use of local variables or parameters within the
69/// default argument expression.
70class CheckDefaultArgumentVisitor
71 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
72 Sema &S;
73 const Expr *DefaultArg;
74
75public:
76 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
77 : S(S), DefaultArg(DefaultArg) {}
78
79 bool VisitExpr(const Expr *Node);
80 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
81 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
82 bool VisitLambdaExpr(const LambdaExpr *Lambda);
83 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
84};
85
86/// VisitExpr - Visit all of the children of this expression.
87bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
88 bool IsInvalid = false;
89 for (const Stmt *SubStmt : Node->children())
90 if (SubStmt)
91 IsInvalid |= Visit(SubStmt);
92 return IsInvalid;
93}
94
95/// VisitDeclRefExpr - Visit a reference to a declaration, to
96/// determine whether this declaration can be used in the default
97/// argument expression.
98bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
99 const ValueDecl *Decl = dyn_cast<ValueDecl>(DRE->getDecl());
100
101 if (!isa<VarDecl, BindingDecl>(Decl))
102 return false;
103
104 if (const auto *Param = dyn_cast<ParmVarDecl>(Decl)) {
105 // C++ [dcl.fct.default]p9:
106 // [...] parameters of a function shall not be used in default
107 // argument expressions, even if they are not evaluated. [...]
108 //
109 // C++17 [dcl.fct.default]p9 (by CWG 2082):
110 // [...] A parameter shall not appear as a potentially-evaluated
111 // expression in a default argument. [...]
112 //
113 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
114 return S.Diag(DRE->getBeginLoc(),
115 diag::err_param_default_argument_references_param)
116 << Param->getDeclName() << DefaultArg->getSourceRange();
117 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
118 // C++ [dcl.fct.default]p7:
119 // Local variables shall not be used in default argument
120 // expressions.
121 //
122 // C++17 [dcl.fct.default]p7 (by CWG 2082):
123 // A local variable shall not appear as a potentially-evaluated
124 // expression in a default argument.
125 //
126 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
127 // Note: A local variable cannot be odr-used (6.3) in a default
128 // argument.
129 //
130 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
131 return S.Diag(DRE->getBeginLoc(),
132 diag::err_param_default_argument_references_local)
133 << Decl << DefaultArg->getSourceRange();
134 }
135 return false;
136}
137
138/// VisitCXXThisExpr - Visit a C++ "this" expression.
139bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
140 // C++ [dcl.fct.default]p8:
141 // The keyword this shall not be used in a default argument of a
142 // member function.
143 return S.Diag(ThisE->getBeginLoc(),
144 diag::err_param_default_argument_references_this)
145 << ThisE->getSourceRange();
146}
147
148bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
149 const PseudoObjectExpr *POE) {
150 bool Invalid = false;
151 for (const Expr *E : POE->semantics()) {
152 // Look through bindings.
153 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(E)) {
154 E = OVE->getSourceExpr();
155 assert(E && "pseudo-object binding without source expression?");
156 }
157
158 Invalid |= Visit(E);
159 }
160 return Invalid;
161}
162
163bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
164 // [expr.prim.lambda.capture]p9
165 // a lambda-expression appearing in a default argument cannot implicitly or
166 // explicitly capture any local entity. Such a lambda-expression can still
167 // have an init-capture if any full-expression in its initializer satisfies
168 // the constraints of an expression appearing in a default argument.
169 bool Invalid = false;
170 for (const LambdaCapture &LC : Lambda->captures()) {
171 if (!Lambda->isInitCapture(&LC))
172 return S.Diag(LC.getLocation(), diag::err_lambda_capture_default_arg);
173 // Init captures are always VarDecl.
174 auto *D = cast<VarDecl>(LC.getCapturedVar());
175 Invalid |= Visit(D->getInit());
176 }
177 return Invalid;
178}
179} // namespace
180
181void
183 const CXXMethodDecl *Method) {
184 // If we have an MSAny spec already, don't bother.
185 if (!Method || ComputedEST == EST_MSAny)
186 return;
187
188 const FunctionProtoType *Proto
189 = Method->getType()->getAs<FunctionProtoType>();
190 Proto = Self->ResolveExceptionSpec(CallLoc, Proto);
191 if (!Proto)
192 return;
193
195
196 // If we have a throw-all spec at this point, ignore the function.
197 if (ComputedEST == EST_None)
198 return;
199
200 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
201 EST = EST_BasicNoexcept;
202
203 switch (EST) {
204 case EST_Unparsed:
206 case EST_Unevaluated:
207 llvm_unreachable("should not see unresolved exception specs here");
208
209 // If this function can throw any exceptions, make a note of that.
210 case EST_MSAny:
211 case EST_None:
212 // FIXME: Whichever we see last of MSAny and None determines our result.
213 // We should make a consistent, order-independent choice here.
214 ClearExceptions();
215 ComputedEST = EST;
216 return;
218 ClearExceptions();
219 ComputedEST = EST_None;
220 return;
221 // FIXME: If the call to this decl is using any of its default arguments, we
222 // need to search them for potentially-throwing calls.
223 // If this function has a basic noexcept, it doesn't affect the outcome.
225 case EST_NoexceptTrue:
226 case EST_NoThrow:
227 return;
228 // If we're still at noexcept(true) and there's a throw() callee,
229 // change to that specification.
230 case EST_DynamicNone:
231 if (ComputedEST == EST_BasicNoexcept)
232 ComputedEST = EST_DynamicNone;
233 return;
235 llvm_unreachable(
236 "should not generate implicit declarations for dependent cases");
237 case EST_Dynamic:
238 break;
239 }
240 assert(EST == EST_Dynamic && "EST case not considered earlier.");
241 assert(ComputedEST != EST_None &&
242 "Shouldn't collect exceptions when throw-all is guaranteed.");
243 ComputedEST = EST_Dynamic;
244 // Record the exceptions in this function's exception specification.
245 for (const auto &E : Proto->exceptions())
246 if (ExceptionsSeen.insert(Self->Context.getCanonicalType(E)).second)
247 Exceptions.push_back(E);
248}
249
251 if (!S || ComputedEST == EST_MSAny)
252 return;
253
254 // FIXME:
255 //
256 // C++0x [except.spec]p14:
257 // [An] implicit exception-specification specifies the type-id T if and
258 // only if T is allowed by the exception-specification of a function directly
259 // invoked by f's implicit definition; f shall allow all exceptions if any
260 // function it directly invokes allows all exceptions, and f shall allow no
261 // exceptions if every function it directly invokes allows no exceptions.
262 //
263 // Note in particular that if an implicit exception-specification is generated
264 // for a function containing a throw-expression, that specification can still
265 // be noexcept(true).
266 //
267 // Note also that 'directly invoked' is not defined in the standard, and there
268 // is no indication that we should only consider potentially-evaluated calls.
269 //
270 // Ultimately we should implement the intent of the standard: the exception
271 // specification should be the set of exceptions which can be thrown by the
272 // implicit definition. For now, we assume that any non-nothrow expression can
273 // throw any exception.
274
275 if (Self->canThrow(S))
276 ComputedEST = EST_None;
277}
278
280 SourceLocation EqualLoc) {
281 if (RequireCompleteType(Param->getLocation(), Param->getType(),
282 diag::err_typecheck_decl_incomplete_type))
283 return true;
284
285 // C++ [dcl.fct.default]p5
286 // A default argument expression is implicitly converted (clause
287 // 4) to the parameter type. The default argument expression has
288 // the same semantic constraints as the initializer expression in
289 // a declaration of a variable of the parameter type, using the
290 // copy-initialization semantics (8.5).
292 Param);
294 EqualLoc);
295 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
296 ExprResult Result = InitSeq.Perform(*this, Entity, Kind, Arg);
297 if (Result.isInvalid())
298 return true;
299 Arg = Result.getAs<Expr>();
300
301 CheckCompletedExpr(Arg, EqualLoc);
303
304 return Arg;
305}
306
308 SourceLocation EqualLoc) {
309 // Add the default argument to the parameter
310 Param->setDefaultArg(Arg);
311
312 // We have already instantiated this parameter; provide each of the
313 // instantiations with the uninstantiated default argument.
314 UnparsedDefaultArgInstantiationsMap::iterator InstPos
316 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
317 for (unsigned I = 0, N = InstPos->second.size(); I != N; ++I)
318 InstPos->second[I]->setUninstantiatedDefaultArg(Arg);
319
320 // We're done tracking this parameter's instantiations.
322 }
323}
324
325/// ActOnParamDefaultArgument - Check whether the default argument
326/// provided for a function parameter is well-formed. If so, attach it
327/// to the parameter declaration.
328void
330 Expr *DefaultArg) {
331 if (!param || !DefaultArg)
332 return;
333
334 ParmVarDecl *Param = cast<ParmVarDecl>(param);
335 UnparsedDefaultArgLocs.erase(Param);
336
337 // Default arguments are only permitted in C++
338 if (!getLangOpts().CPlusPlus) {
339 Diag(EqualLoc, diag::err_param_default_argument)
340 << DefaultArg->getSourceRange();
341 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
342 }
343
344 // Check for unexpanded parameter packs.
346 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
347
348 // C++11 [dcl.fct.default]p3
349 // A default argument expression [...] shall not be specified for a
350 // parameter pack.
351 if (Param->isParameterPack()) {
352 Diag(EqualLoc, diag::err_param_default_argument_on_parameter_pack)
353 << DefaultArg->getSourceRange();
354 // Recover by discarding the default argument.
355 Param->setDefaultArg(nullptr);
356 return;
357 }
358
359 ExprResult Result = ConvertParamDefaultArgument(Param, DefaultArg, EqualLoc);
360 if (Result.isInvalid())
361 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
362
363 DefaultArg = Result.getAs<Expr>();
364
365 // Check that the default argument is well-formed
366 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
367 if (DefaultArgChecker.Visit(DefaultArg))
368 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
369
370 SetParamDefaultArgument(Param, DefaultArg, EqualLoc);
371}
372
373/// ActOnParamUnparsedDefaultArgument - We've seen a default
374/// argument for a function parameter, but we can't parse it yet
375/// because we're inside a class definition. Note that this default
376/// argument will be parsed later.
378 SourceLocation EqualLoc,
379 SourceLocation ArgLoc) {
380 if (!param)
381 return;
382
383 ParmVarDecl *Param = cast<ParmVarDecl>(param);
384 Param->setUnparsedDefaultArg();
385 UnparsedDefaultArgLocs[Param] = ArgLoc;
386}
387
388/// ActOnParamDefaultArgumentError - Parsing or semantic analysis of
389/// the default argument for the parameter param failed.
391 Expr *DefaultArg) {
392 if (!param)
393 return;
394
395 ParmVarDecl *Param = cast<ParmVarDecl>(param);
396 Param->setInvalidDecl();
397 UnparsedDefaultArgLocs.erase(Param);
398 ExprResult RE;
399 if (DefaultArg) {
400 RE = CreateRecoveryExpr(EqualLoc, DefaultArg->getEndLoc(), {DefaultArg},
401 Param->getType().getNonReferenceType());
402 } else {
403 RE = CreateRecoveryExpr(EqualLoc, EqualLoc, {},
404 Param->getType().getNonReferenceType());
405 }
406 Param->setDefaultArg(RE.get());
407}
408
409/// CheckExtraCXXDefaultArguments - Check for any extra default
410/// arguments in the declarator, which is not a function declaration
411/// or definition and therefore is not permitted to have default
412/// arguments. This routine should be invoked for every declarator
413/// that is not a function declaration or definition.
415 // C++ [dcl.fct.default]p3
416 // A default argument expression shall be specified only in the
417 // parameter-declaration-clause of a function declaration or in a
418 // template-parameter (14.1). It shall not be specified for a
419 // parameter pack. If it is specified in a
420 // parameter-declaration-clause, it shall not occur within a
421 // declarator or abstract-declarator of a parameter-declaration.
422 bool MightBeFunction = D.isFunctionDeclarationContext();
423 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
424 DeclaratorChunk &chunk = D.getTypeObject(i);
425 if (chunk.Kind == DeclaratorChunk::Function) {
426 if (MightBeFunction) {
427 // This is a function declaration. It can have default arguments, but
428 // keep looking in case its return type is a function type with default
429 // arguments.
430 MightBeFunction = false;
431 continue;
432 }
433 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
434 ++argIdx) {
435 ParmVarDecl *Param = cast<ParmVarDecl>(chunk.Fun.Params[argIdx].Param);
436 if (Param->hasUnparsedDefaultArg()) {
437 std::unique_ptr<CachedTokens> Toks =
438 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
439 SourceRange SR;
440 if (Toks->size() > 1)
441 SR = SourceRange((*Toks)[1].getLocation(),
442 Toks->back().getLocation());
443 else
444 SR = UnparsedDefaultArgLocs[Param];
445 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
446 << SR;
447 } else if (Param->getDefaultArg()) {
448 Diag(Param->getLocation(), diag::err_param_default_argument_nonfunc)
449 << Param->getDefaultArg()->getSourceRange();
450 Param->setDefaultArg(nullptr);
451 }
452 }
453 } else if (chunk.Kind != DeclaratorChunk::Paren) {
454 MightBeFunction = false;
455 }
456 }
457}
458
460 return llvm::any_of(FD->parameters(), [](ParmVarDecl *P) {
461 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
462 });
463}
464
465/// MergeCXXFunctionDecl - Merge two declarations of the same C++
466/// function, once we already know that they have the same
467/// type. Subroutine of MergeFunctionDecl. Returns true if there was an
468/// error, false otherwise.
470 Scope *S) {
471 bool Invalid = false;
472
473 // The declaration context corresponding to the scope is the semantic
474 // parent, unless this is a local function declaration, in which case
475 // it is that surrounding function.
476 DeclContext *ScopeDC = New->isLocalExternDecl()
477 ? New->getLexicalDeclContext()
478 : New->getDeclContext();
479
480 // Find the previous declaration for the purpose of default arguments.
481 FunctionDecl *PrevForDefaultArgs = Old;
482 for (/**/; PrevForDefaultArgs;
483 // Don't bother looking back past the latest decl if this is a local
484 // extern declaration; nothing else could work.
485 PrevForDefaultArgs = New->isLocalExternDecl()
486 ? nullptr
487 : PrevForDefaultArgs->getPreviousDecl()) {
488 // Ignore hidden declarations.
489 if (!LookupResult::isVisible(*this, PrevForDefaultArgs))
490 continue;
491
492 if (S && !isDeclInScope(PrevForDefaultArgs, ScopeDC, S) &&
493 !New->isCXXClassMember()) {
494 // Ignore default arguments of old decl if they are not in
495 // the same scope and this is not an out-of-line definition of
496 // a member function.
497 continue;
498 }
499
500 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
501 // If only one of these is a local function declaration, then they are
502 // declared in different scopes, even though isDeclInScope may think
503 // they're in the same scope. (If both are local, the scope check is
504 // sufficient, and if neither is local, then they are in the same scope.)
505 continue;
506 }
507
508 // We found the right previous declaration.
509 break;
510 }
511
512 // C++ [dcl.fct.default]p4:
513 // For non-template functions, default arguments can be added in
514 // later declarations of a function in the same
515 // scope. Declarations in different scopes have completely
516 // distinct sets of default arguments. That is, declarations in
517 // inner scopes do not acquire default arguments from
518 // declarations in outer scopes, and vice versa. In a given
519 // function declaration, all parameters subsequent to a
520 // parameter with a default argument shall have default
521 // arguments supplied in this or previous declarations. A
522 // default argument shall not be redefined by a later
523 // declaration (not even to the same value).
524 //
525 // C++ [dcl.fct.default]p6:
526 // Except for member functions of class templates, the default arguments
527 // in a member function definition that appears outside of the class
528 // definition are added to the set of default arguments provided by the
529 // member function declaration in the class definition.
530 for (unsigned p = 0, NumParams = PrevForDefaultArgs
531 ? PrevForDefaultArgs->getNumParams()
532 : 0;
533 p < NumParams; ++p) {
534 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(p);
535 ParmVarDecl *NewParam = New->getParamDecl(p);
536
537 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
538 bool NewParamHasDfl = NewParam->hasDefaultArg();
539
540 if (OldParamHasDfl && NewParamHasDfl) {
541 unsigned DiagDefaultParamID =
542 diag::err_param_default_argument_redefinition;
543
544 // MSVC accepts that default parameters be redefined for member functions
545 // of template class. The new default parameter's value is ignored.
546 Invalid = true;
547 if (getLangOpts().MicrosoftExt) {
548 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(New);
549 if (MD && MD->getParent()->getDescribedClassTemplate()) {
550 // Merge the old default argument into the new parameter.
551 NewParam->setHasInheritedDefaultArg();
552 if (OldParam->hasUninstantiatedDefaultArg())
554 OldParam->getUninstantiatedDefaultArg());
555 else
556 NewParam->setDefaultArg(OldParam->getInit());
557 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
558 Invalid = false;
559 }
560 }
561
562 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
563 // hint here. Alternatively, we could walk the type-source information
564 // for NewParam to find the last source location in the type... but it
565 // isn't worth the effort right now. This is the kind of test case that
566 // is hard to get right:
567 // int f(int);
568 // void g(int (*fp)(int) = f);
569 // void g(int (*fp)(int) = &f);
570 Diag(NewParam->getLocation(), DiagDefaultParamID)
571 << NewParam->getDefaultArgRange();
572
573 // Look for the function declaration where the default argument was
574 // actually written, which may be a declaration prior to Old.
575 for (auto Older = PrevForDefaultArgs;
576 OldParam->hasInheritedDefaultArg(); /**/) {
577 Older = Older->getPreviousDecl();
578 OldParam = Older->getParamDecl(p);
579 }
580
581 Diag(OldParam->getLocation(), diag::note_previous_definition)
582 << OldParam->getDefaultArgRange();
583 } else if (OldParamHasDfl) {
584 // Merge the old default argument into the new parameter unless the new
585 // function is a friend declaration in a template class. In the latter
586 // case the default arguments will be inherited when the friend
587 // declaration will be instantiated.
588 if (New->getFriendObjectKind() == Decl::FOK_None ||
590 // It's important to use getInit() here; getDefaultArg()
591 // strips off any top-level ExprWithCleanups.
592 NewParam->setHasInheritedDefaultArg();
593 if (OldParam->hasUnparsedDefaultArg())
594 NewParam->setUnparsedDefaultArg();
595 else if (OldParam->hasUninstantiatedDefaultArg())
597 OldParam->getUninstantiatedDefaultArg());
598 else
599 NewParam->setDefaultArg(OldParam->getInit());
600 }
601 } else if (NewParamHasDfl) {
602 if (New->getDescribedFunctionTemplate()) {
603 // Paragraph 4, quoted above, only applies to non-template functions.
604 Diag(NewParam->getLocation(),
605 diag::err_param_default_argument_template_redecl)
606 << NewParam->getDefaultArgRange();
607 Diag(PrevForDefaultArgs->getLocation(),
608 diag::note_template_prev_declaration)
609 << false;
610 } else if (New->getTemplateSpecializationKind()
613 // C++ [temp.expr.spec]p21:
614 // Default function arguments shall not be specified in a declaration
615 // or a definition for one of the following explicit specializations:
616 // - the explicit specialization of a function template;
617 // - the explicit specialization of a member function template;
618 // - the explicit specialization of a member function of a class
619 // template where the class template specialization to which the
620 // member function specialization belongs is implicitly
621 // instantiated.
622 Diag(NewParam->getLocation(), diag::err_template_spec_default_arg)
624 << New->getDeclName()
625 << NewParam->getDefaultArgRange();
626 } else if (New->getDeclContext()->isDependentContext()) {
627 // C++ [dcl.fct.default]p6 (DR217):
628 // Default arguments for a member function of a class template shall
629 // be specified on the initial declaration of the member function
630 // within the class template.
631 //
632 // Reading the tea leaves a bit in DR217 and its reference to DR205
633 // leads me to the conclusion that one cannot add default function
634 // arguments for an out-of-line definition of a member function of a
635 // dependent type.
636 int WhichKind = 2;
638 = dyn_cast<CXXRecordDecl>(New->getDeclContext())) {
639 if (Record->getDescribedClassTemplate())
640 WhichKind = 0;
641 else if (isa<ClassTemplatePartialSpecializationDecl>(Record))
642 WhichKind = 1;
643 else
644 WhichKind = 2;
645 }
646
647 Diag(NewParam->getLocation(),
648 diag::err_param_default_argument_member_template_redecl)
649 << WhichKind
650 << NewParam->getDefaultArgRange();
651 }
652 }
653 }
654
655 // DR1344: If a default argument is added outside a class definition and that
656 // default argument makes the function a special member function, the program
657 // is ill-formed. This can only happen for constructors.
658 if (isa<CXXConstructorDecl>(New) &&
660 CXXSpecialMember NewSM = getSpecialMember(cast<CXXMethodDecl>(New)),
661 OldSM = getSpecialMember(cast<CXXMethodDecl>(Old));
662 if (NewSM != OldSM) {
663 ParmVarDecl *NewParam = New->getParamDecl(New->getMinRequiredArguments());
664 assert(NewParam->hasDefaultArg());
665 Diag(NewParam->getLocation(), diag::err_default_arg_makes_ctor_special)
666 << NewParam->getDefaultArgRange() << NewSM;
667 Diag(Old->getLocation(), diag::note_previous_declaration);
668 }
669 }
670
671 const FunctionDecl *Def;
672 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
673 // template has a constexpr specifier then all its declarations shall
674 // contain the constexpr specifier.
675 if (New->getConstexprKind() != Old->getConstexprKind()) {
676 Diag(New->getLocation(), diag::err_constexpr_redecl_mismatch)
677 << New << static_cast<int>(New->getConstexprKind())
678 << static_cast<int>(Old->getConstexprKind());
679 Diag(Old->getLocation(), diag::note_previous_declaration);
680 Invalid = true;
681 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
682 Old->isDefined(Def) &&
683 // If a friend function is inlined but does not have 'inline'
684 // specifier, it is a definition. Do not report attribute conflict
685 // in this case, redefinition will be diagnosed later.
686 (New->isInlineSpecified() ||
688 // C++11 [dcl.fcn.spec]p4:
689 // If the definition of a function appears in a translation unit before its
690 // first declaration as inline, the program is ill-formed.
691 Diag(New->getLocation(), diag::err_inline_decl_follows_def) << New;
692 Diag(Def->getLocation(), diag::note_previous_definition);
693 Invalid = true;
694 }
695
696 // C++17 [temp.deduct.guide]p3:
697 // Two deduction guide declarations in the same translation unit
698 // for the same class template shall not have equivalent
699 // parameter-declaration-clauses.
700 if (isa<CXXDeductionGuideDecl>(New) &&
702 Diag(New->getLocation(), diag::err_deduction_guide_redeclared);
703 Diag(Old->getLocation(), diag::note_previous_declaration);
704 }
705
706 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
707 // argument expression, that declaration shall be a definition and shall be
708 // the only declaration of the function or function template in the
709 // translation unit.
712 Diag(New->getLocation(), diag::err_friend_decl_with_def_arg_redeclared);
713 Diag(Old->getLocation(), diag::note_previous_declaration);
714 Invalid = true;
715 }
716
717 // C++11 [temp.friend]p4 (DR329):
718 // When a function is defined in a friend function declaration in a class
719 // template, the function is instantiated when the function is odr-used.
720 // The same restrictions on multiple declarations and definitions that
721 // apply to non-template function declarations and definitions also apply
722 // to these implicit definitions.
723 const FunctionDecl *OldDefinition = nullptr;
725 Old->isDefined(OldDefinition, true))
726 CheckForFunctionRedefinition(New, OldDefinition);
727
728 return Invalid;
729}
730
733 ? diag::warn_cxx23_placeholder_var_definition
734 : diag::ext_placeholder_var_definition);
735}
736
737NamedDecl *
739 MultiTemplateParamsArg TemplateParamLists) {
740 assert(D.isDecompositionDeclarator());
742
743 // The syntax only allows a decomposition declarator as a simple-declaration,
744 // a for-range-declaration, or a condition in Clang, but we parse it in more
745 // cases than that.
747 Diag(Decomp.getLSquareLoc(), diag::err_decomp_decl_context)
748 << Decomp.getSourceRange();
749 return nullptr;
750 }
751
752 if (!TemplateParamLists.empty()) {
753 // FIXME: There's no rule against this, but there are also no rules that
754 // would actually make it usable, so we reject it for now.
755 Diag(TemplateParamLists.front()->getTemplateLoc(),
756 diag::err_decomp_decl_template);
757 return nullptr;
758 }
759
760 Diag(Decomp.getLSquareLoc(),
762 ? diag::ext_decomp_decl
764 ? diag::ext_decomp_decl_cond
765 : diag::warn_cxx14_compat_decomp_decl)
766 << Decomp.getSourceRange();
767
768 // The semantic context is always just the current context.
769 DeclContext *const DC = CurContext;
770
771 // C++17 [dcl.dcl]/8:
772 // The decl-specifier-seq shall contain only the type-specifier auto
773 // and cv-qualifiers.
774 // C++20 [dcl.dcl]/8:
775 // If decl-specifier-seq contains any decl-specifier other than static,
776 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
777 // C++23 [dcl.pre]/6:
778 // Each decl-specifier in the decl-specifier-seq shall be static,
779 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
780 auto &DS = D.getDeclSpec();
781 {
782 // Note: While constrained-auto needs to be checked, we do so separately so
783 // we can emit a better diagnostic.
784 SmallVector<StringRef, 8> BadSpecifiers;
785 SmallVector<SourceLocation, 8> BadSpecifierLocs;
786 SmallVector<StringRef, 8> CPlusPlus20Specifiers;
787 SmallVector<SourceLocation, 8> CPlusPlus20SpecifierLocs;
788 if (auto SCS = DS.getStorageClassSpec()) {
789 if (SCS == DeclSpec::SCS_static) {
790 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(SCS));
791 CPlusPlus20SpecifierLocs.push_back(DS.getStorageClassSpecLoc());
792 } else {
793 BadSpecifiers.push_back(DeclSpec::getSpecifierName(SCS));
794 BadSpecifierLocs.push_back(DS.getStorageClassSpecLoc());
795 }
796 }
797 if (auto TSCS = DS.getThreadStorageClassSpec()) {
798 CPlusPlus20Specifiers.push_back(DeclSpec::getSpecifierName(TSCS));
799 CPlusPlus20SpecifierLocs.push_back(DS.getThreadStorageClassSpecLoc());
800 }
801 if (DS.hasConstexprSpecifier()) {
802 BadSpecifiers.push_back(
803 DeclSpec::getSpecifierName(DS.getConstexprSpecifier()));
804 BadSpecifierLocs.push_back(DS.getConstexprSpecLoc());
805 }
806 if (DS.isInlineSpecified()) {
807 BadSpecifiers.push_back("inline");
808 BadSpecifierLocs.push_back(DS.getInlineSpecLoc());
809 }
810
811 if (!BadSpecifiers.empty()) {
812 auto &&Err = Diag(BadSpecifierLocs.front(), diag::err_decomp_decl_spec);
813 Err << (int)BadSpecifiers.size()
814 << llvm::join(BadSpecifiers.begin(), BadSpecifiers.end(), " ");
815 // Don't add FixItHints to remove the specifiers; we do still respect
816 // them when building the underlying variable.
817 for (auto Loc : BadSpecifierLocs)
818 Err << SourceRange(Loc, Loc);
819 } else if (!CPlusPlus20Specifiers.empty()) {
820 auto &&Warn = Diag(CPlusPlus20SpecifierLocs.front(),
822 ? diag::warn_cxx17_compat_decomp_decl_spec
823 : diag::ext_decomp_decl_spec);
824 Warn << (int)CPlusPlus20Specifiers.size()
825 << llvm::join(CPlusPlus20Specifiers.begin(),
826 CPlusPlus20Specifiers.end(), " ");
827 for (auto Loc : CPlusPlus20SpecifierLocs)
828 Warn << SourceRange(Loc, Loc);
829 }
830 // We can't recover from it being declared as a typedef.
831 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
832 return nullptr;
833 }
834
835 // C++2a [dcl.struct.bind]p1:
836 // A cv that includes volatile is deprecated
837 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
839 Diag(DS.getVolatileSpecLoc(),
840 diag::warn_deprecated_volatile_structured_binding);
841
843 QualType R = TInfo->getType();
844
847 D.setInvalidType();
848
849 // The syntax only allows a single ref-qualifier prior to the decomposition
850 // declarator. No other declarator chunks are permitted. Also check the type
851 // specifier here.
852 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
853 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
854 (D.getNumTypeObjects() == 1 &&
856 Diag(Decomp.getLSquareLoc(),
857 (D.hasGroupingParens() ||
858 (D.getNumTypeObjects() &&
860 ? diag::err_decomp_decl_parens
861 : diag::err_decomp_decl_type)
862 << R;
863
864 // In most cases, there's no actual problem with an explicitly-specified
865 // type, but a function type won't work here, and ActOnVariableDeclarator
866 // shouldn't be called for such a type.
867 if (R->isFunctionType())
868 D.setInvalidType();
869 }
870
871 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
872 if (DS.isConstrainedAuto()) {
873 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
874 assert(TemplRep->Kind == TNK_Concept_template &&
875 "No other template kind should be possible for a constrained auto");
876
877 SourceRange TemplRange{TemplRep->TemplateNameLoc,
878 TemplRep->RAngleLoc.isValid()
879 ? TemplRep->RAngleLoc
880 : TemplRep->TemplateNameLoc};
881 Diag(TemplRep->TemplateNameLoc, diag::err_decomp_decl_constraint)
882 << TemplRange << FixItHint::CreateRemoval(TemplRange);
883 }
884
885 // Build the BindingDecls.
887
888 // Build the BindingDecls.
889 for (auto &B : D.getDecompositionDeclarator().bindings()) {
890 // Check for name conflicts.
891 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
892 IdentifierInfo *VarName = B.Name;
893 assert(VarName && "Cannot have an unnamed binding declaration");
894
898 /*CreateBuiltins*/DC->getRedeclContext()->isTranslationUnit());
899
900 // It's not permitted to shadow a template parameter name.
901 if (Previous.isSingleResult() &&
902 Previous.getFoundDecl()->isTemplateParameter()) {
904 Previous.getFoundDecl());
905 Previous.clear();
906 }
907
908 auto *BD = BindingDecl::Create(Context, DC, B.NameLoc, VarName);
909
910 // Find the shadowed declaration before filtering for scope.
911 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
913 : nullptr;
914
915 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
916 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
917 FilterLookupForScope(Previous, DC, S, ConsiderLinkage,
918 /*AllowInlineNamespace*/false);
919
920 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
921 DC->isFunctionOrMethod() && VarName->isPlaceholder();
922 if (!Previous.empty()) {
923 if (IsPlaceholder) {
924 bool sameDC = (Previous.end() - 1)
925 ->getDeclContext()
926 ->getRedeclContext()
927 ->Equals(DC->getRedeclContext());
928 if (sameDC &&
929 isDeclInScope(*(Previous.end() - 1), CurContext, S, false)) {
930 Previous.clear();
932 }
933 } else {
934 auto *Old = Previous.getRepresentativeDecl();
935 Diag(B.NameLoc, diag::err_redefinition) << B.Name;
936 Diag(Old->getLocation(), diag::note_previous_definition);
937 }
938 } else if (ShadowedDecl && !D.isRedeclaration()) {
939 CheckShadow(BD, ShadowedDecl, Previous);
940 }
941 PushOnScopeChains(BD, S, true);
942 Bindings.push_back(BD);
943 ParsingInitForAutoVars.insert(BD);
944 }
945
946 // There are no prior lookup results for the variable itself, because it
947 // is unnamed.
948 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
949 Decomp.getLSquareLoc());
952
953 // Build the variable that holds the non-decomposed object.
954 bool AddToScope = true;
955 NamedDecl *New =
956 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
957 MultiTemplateParamsArg(), AddToScope, Bindings);
958 if (AddToScope) {
959 S->AddDecl(New);
961 }
962
965
966 return New;
967}
968
971 QualType DecompType, const llvm::APSInt &NumElems, QualType ElemType,
972 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
973 if ((int64_t)Bindings.size() != NumElems) {
974 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
975 << DecompType << (unsigned)Bindings.size()
976 << (unsigned)NumElems.getLimitedValue(UINT_MAX)
977 << toString(NumElems, 10) << (NumElems < Bindings.size());
978 return true;
979 }
980
981 unsigned I = 0;
982 for (auto *B : Bindings) {
983 SourceLocation Loc = B->getLocation();
984 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
985 if (E.isInvalid())
986 return true;
987 E = GetInit(Loc, E.get(), I++);
988 if (E.isInvalid())
989 return true;
990 B->setBinding(ElemType, E.get());
991 }
992
993 return false;
994}
995
998 ValueDecl *Src, QualType DecompType,
999 const llvm::APSInt &NumElems,
1000 QualType ElemType) {
1002 S, Bindings, Src, DecompType, NumElems, ElemType,
1003 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1004 ExprResult E = S.ActOnIntegerConstant(Loc, I);
1005 if (E.isInvalid())
1006 return ExprError();
1007 return S.CreateBuiltinArraySubscriptExpr(Base, Loc, E.get(), Loc);
1008 });
1009}
1010
1012 ValueDecl *Src, QualType DecompType,
1013 const ConstantArrayType *CAT) {
1014 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1015 llvm::APSInt(CAT->getSize()),
1016 CAT->getElementType());
1017}
1018
1020 ValueDecl *Src, QualType DecompType,
1021 const VectorType *VT) {
1023 S, Bindings, Src, DecompType, llvm::APSInt::get(VT->getNumElements()),
1025 DecompType.getQualifiers()));
1026}
1027
1030 ValueDecl *Src, QualType DecompType,
1031 const ComplexType *CT) {
1033 S, Bindings, Src, DecompType, llvm::APSInt::get(2),
1035 DecompType.getQualifiers()),
1036 [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1037 return S.CreateBuiltinUnaryOp(Loc, I ? UO_Imag : UO_Real, Base);
1038 });
1039}
1040
1043 const TemplateParameterList *Params) {
1045 llvm::raw_svector_ostream OS(SS);
1046 bool First = true;
1047 unsigned I = 0;
1048 for (auto &Arg : Args.arguments()) {
1049 if (!First)
1050 OS << ", ";
1051 Arg.getArgument().print(PrintingPolicy, OS,
1053 PrintingPolicy, Params, I));
1054 First = false;
1055 I++;
1056 }
1057 return std::string(OS.str());
1058}
1059
1060static bool lookupStdTypeTraitMember(Sema &S, LookupResult &TraitMemberLookup,
1061 SourceLocation Loc, StringRef Trait,
1063 unsigned DiagID) {
1064 auto DiagnoseMissing = [&] {
1065 if (DiagID)
1066 S.Diag(Loc, DiagID) << printTemplateArgs(S.Context.getPrintingPolicy(),
1067 Args, /*Params*/ nullptr);
1068 return true;
1069 };
1070
1071 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1073 if (!Std)
1074 return DiagnoseMissing();
1075
1076 // Look up the trait itself, within namespace std. We can diagnose various
1077 // problems with this lookup even if we've been asked to not diagnose a
1078 // missing specialization, because this can only fail if the user has been
1079 // declaring their own names in namespace std or we don't support the
1080 // standard library implementation in use.
1084 return DiagnoseMissing();
1085 if (Result.isAmbiguous())
1086 return true;
1087
1088 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1089 if (!TraitTD) {
1090 Result.suppressDiagnostics();
1091 NamedDecl *Found = *Result.begin();
1092 S.Diag(Loc, diag::err_std_type_trait_not_class_template) << Trait;
1093 S.Diag(Found->getLocation(), diag::note_declared_at);
1094 return true;
1095 }
1096
1097 // Build the template-id.
1098 QualType TraitTy = S.CheckTemplateIdType(TemplateName(TraitTD), Loc, Args);
1099 if (TraitTy.isNull())
1100 return true;
1101 if (!S.isCompleteType(Loc, TraitTy)) {
1102 if (DiagID)
1104 Loc, TraitTy, DiagID,
1106 TraitTD->getTemplateParameters()));
1107 return true;
1108 }
1109
1110 CXXRecordDecl *RD = TraitTy->getAsCXXRecordDecl();
1111 assert(RD && "specialization of class template is not a class?");
1112
1113 // Look up the member of the trait type.
1114 S.LookupQualifiedName(TraitMemberLookup, RD);
1115 return TraitMemberLookup.isAmbiguous();
1116}
1117
1120 uint64_t I) {
1122 return S.getTrivialTemplateArgumentLoc(Arg, T, Loc);
1123}
1124
1128}
1129
1130namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1131
1132static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1133 llvm::APSInt &Size) {
1136
1139
1140 // Form template argument list for tuple_size<T>.
1141 TemplateArgumentListInfo Args(Loc, Loc);
1143
1144 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1145 // it's not tuple-like.
1146 if (lookupStdTypeTraitMember(S, R, Loc, "tuple_size", Args, /*DiagID*/ 0) ||
1147 R.empty())
1148 return IsTupleLike::NotTupleLike;
1149
1150 // If we get this far, we've committed to the tuple interpretation, but
1151 // we can still fail if there actually isn't a usable ::value.
1152
1153 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1154 LookupResult &R;
1156 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1157 : R(R), Args(Args) {}
1158 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1159 SourceLocation Loc) override {
1160 return S.Diag(Loc, diag::err_decomp_decl_std_tuple_size_not_constant)
1162 /*Params*/ nullptr);
1163 }
1164 } Diagnoser(R, Args);
1165
1166 ExprResult E =
1167 S.BuildDeclarationNameExpr(CXXScopeSpec(), R, /*NeedsADL*/false);
1168 if (E.isInvalid())
1169 return IsTupleLike::Error;
1170
1171 E = S.VerifyIntegerConstantExpression(E.get(), &Size, Diagnoser);
1172 if (E.isInvalid())
1173 return IsTupleLike::Error;
1174
1175 return IsTupleLike::TupleLike;
1176}
1177
1178/// \return std::tuple_element<I, T>::type.
1180 unsigned I, QualType T) {
1181 // Form template argument list for tuple_element<I, T>.
1182 TemplateArgumentListInfo Args(Loc, Loc);
1183 Args.addArgument(
1186
1187 DeclarationName TypeDN = S.PP.getIdentifierInfo("type");
1188 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1190 S, R, Loc, "tuple_element", Args,
1191 diag::err_decomp_decl_std_tuple_element_not_specialized))
1192 return QualType();
1193
1194 auto *TD = R.getAsSingle<TypeDecl>();
1195 if (!TD) {
1197 S.Diag(Loc, diag::err_decomp_decl_std_tuple_element_not_specialized)
1199 /*Params*/ nullptr);
1200 if (!R.empty())
1201 S.Diag(R.getRepresentativeDecl()->getLocation(), diag::note_declared_at);
1202 return QualType();
1203 }
1204
1205 return S.Context.getTypeDeclType(TD);
1206}
1207
1208namespace {
1209struct InitializingBinding {
1210 Sema &S;
1211 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1215 Ctx.Entity = BD;
1217 }
1218 ~InitializingBinding() {
1220 }
1221};
1222}
1223
1226 VarDecl *Src, QualType DecompType,
1227 const llvm::APSInt &TupleSize) {
1228 if ((int64_t)Bindings.size() != TupleSize) {
1229 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1230 << DecompType << (unsigned)Bindings.size()
1231 << (unsigned)TupleSize.getLimitedValue(UINT_MAX)
1232 << toString(TupleSize, 10) << (TupleSize < Bindings.size());
1233 return true;
1234 }
1235
1236 if (Bindings.empty())
1237 return false;
1238
1239 DeclarationName GetDN = S.PP.getIdentifierInfo("get");
1240
1241 // [dcl.decomp]p3:
1242 // The unqualified-id get is looked up in the scope of E by class member
1243 // access lookup ...
1244 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1245 bool UseMemberGet = false;
1246 if (S.isCompleteType(Src->getLocation(), DecompType)) {
1247 if (auto *RD = DecompType->getAsCXXRecordDecl())
1248 S.LookupQualifiedName(MemberGet, RD);
1249 if (MemberGet.isAmbiguous())
1250 return true;
1251 // ... and if that finds at least one declaration that is a function
1252 // template whose first template parameter is a non-type parameter ...
1253 for (NamedDecl *D : MemberGet) {
1254 if (FunctionTemplateDecl *FTD =
1255 dyn_cast<FunctionTemplateDecl>(D->getUnderlyingDecl())) {
1256 TemplateParameterList *TPL = FTD->getTemplateParameters();
1257 if (TPL->size() != 0 &&
1258 isa<NonTypeTemplateParmDecl>(TPL->getParam(0))) {
1259 // ... the initializer is e.get<i>().
1260 UseMemberGet = true;
1261 break;
1262 }
1263 }
1264 }
1265 }
1266
1267 unsigned I = 0;
1268 for (auto *B : Bindings) {
1269 InitializingBinding InitContext(S, B);
1270 SourceLocation Loc = B->getLocation();
1271
1272 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1273 if (E.isInvalid())
1274 return true;
1275
1276 // e is an lvalue if the type of the entity is an lvalue reference and
1277 // an xvalue otherwise
1278 if (!Src->getType()->isLValueReferenceType())
1279 E = ImplicitCastExpr::Create(S.Context, E.get()->getType(), CK_NoOp,
1280 E.get(), nullptr, VK_XValue,
1282
1283 TemplateArgumentListInfo Args(Loc, Loc);
1284 Args.addArgument(
1286
1287 if (UseMemberGet) {
1288 // if [lookup of member get] finds at least one declaration, the
1289 // initializer is e.get<i-1>().
1290 E = S.BuildMemberReferenceExpr(E.get(), DecompType, Loc, false,
1291 CXXScopeSpec(), SourceLocation(), nullptr,
1292 MemberGet, &Args, nullptr);
1293 if (E.isInvalid())
1294 return true;
1295
1296 E = S.BuildCallExpr(nullptr, E.get(), Loc, std::nullopt, Loc);
1297 } else {
1298 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1299 // in the associated namespaces.
1302 DeclarationNameInfo(GetDN, Loc), /*RequiresADL*/ true, &Args,
1304 /*KnownDependent=*/false);
1305
1306 Expr *Arg = E.get();
1307 E = S.BuildCallExpr(nullptr, Get, Loc, Arg, Loc);
1308 }
1309 if (E.isInvalid())
1310 return true;
1311 Expr *Init = E.get();
1312
1313 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1314 QualType T = getTupleLikeElementType(S, Loc, I, DecompType);
1315 if (T.isNull())
1316 return true;
1317
1318 // each vi is a variable of type "reference to T" initialized with the
1319 // initializer, where the reference is an lvalue reference if the
1320 // initializer is an lvalue and an rvalue reference otherwise
1321 QualType RefType =
1322 S.BuildReferenceType(T, E.get()->isLValue(), Loc, B->getDeclName());
1323 if (RefType.isNull())
1324 return true;
1325 auto *RefVD = VarDecl::Create(
1326 S.Context, Src->getDeclContext(), Loc, Loc,
1327 B->getDeclName().getAsIdentifierInfo(), RefType,
1329 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1330 RefVD->setTSCSpec(Src->getTSCSpec());
1331 RefVD->setImplicit();
1332 if (Src->isInlineSpecified())
1333 RefVD->setInlineSpecified();
1334 RefVD->getLexicalDeclContext()->addHiddenDecl(RefVD);
1335
1338 InitializationSequence Seq(S, Entity, Kind, Init);
1339 E = Seq.Perform(S, Entity, Kind, Init);
1340 if (E.isInvalid())
1341 return true;
1342 E = S.ActOnFinishFullExpr(E.get(), Loc, /*DiscardedValue*/ false);
1343 if (E.isInvalid())
1344 return true;
1345 RefVD->setInit(E.get());
1347
1349 DeclarationNameInfo(B->getDeclName(), Loc),
1350 RefVD);
1351 if (E.isInvalid())
1352 return true;
1353
1354 B->setBinding(T, E.get());
1355 I++;
1356 }
1357
1358 return false;
1359}
1360
1361/// Find the base class to decompose in a built-in decomposition of a class type.
1362/// This base class search is, unfortunately, not quite like any other that we
1363/// perform anywhere else in C++.
1365 const CXXRecordDecl *RD,
1366 CXXCastPath &BasePath) {
1367 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1368 CXXBasePath &Path) {
1369 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1370 };
1371
1372 const CXXRecordDecl *ClassWithFields = nullptr;
1374 if (RD->hasDirectFields())
1375 // [dcl.decomp]p4:
1376 // Otherwise, all of E's non-static data members shall be public direct
1377 // members of E ...
1378 ClassWithFields = RD;
1379 else {
1380 // ... or of ...
1381 CXXBasePaths Paths;
1382 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1383 if (!RD->lookupInBases(BaseHasFields, Paths)) {
1384 // If no classes have fields, just decompose RD itself. (This will work
1385 // if and only if zero bindings were provided.)
1386 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(RD), AS_public);
1387 }
1388
1389 CXXBasePath *BestPath = nullptr;
1390 for (auto &P : Paths) {
1391 if (!BestPath)
1392 BestPath = &P;
1393 else if (!S.Context.hasSameType(P.back().Base->getType(),
1394 BestPath->back().Base->getType())) {
1395 // ... the same ...
1396 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1397 << false << RD << BestPath->back().Base->getType()
1398 << P.back().Base->getType();
1399 return DeclAccessPair();
1400 } else if (P.Access < BestPath->Access) {
1401 BestPath = &P;
1402 }
1403 }
1404
1405 // ... unambiguous ...
1406 QualType BaseType = BestPath->back().Base->getType();
1407 if (Paths.isAmbiguous(S.Context.getCanonicalType(BaseType))) {
1408 S.Diag(Loc, diag::err_decomp_decl_ambiguous_base)
1409 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1410 return DeclAccessPair();
1411 }
1412
1413 // ... [accessible, implied by other rules] base class of E.
1414 S.CheckBaseClassAccess(Loc, BaseType, S.Context.getRecordType(RD),
1415 *BestPath, diag::err_decomp_decl_inaccessible_base);
1416 AS = BestPath->Access;
1417
1418 ClassWithFields = BaseType->getAsCXXRecordDecl();
1419 S.BuildBasePathArray(Paths, BasePath);
1420 }
1421
1422 // The above search did not check whether the selected class itself has base
1423 // classes with fields, so check that now.
1424 CXXBasePaths Paths;
1425 if (ClassWithFields->lookupInBases(BaseHasFields, Paths)) {
1426 S.Diag(Loc, diag::err_decomp_decl_multiple_bases_with_members)
1427 << (ClassWithFields == RD) << RD << ClassWithFields
1428 << Paths.front().back().Base->getType();
1429 return DeclAccessPair();
1430 }
1431
1432 return DeclAccessPair::make(const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1433}
1434
1436 ValueDecl *Src, QualType DecompType,
1437 const CXXRecordDecl *OrigRD) {
1438 if (S.RequireCompleteType(Src->getLocation(), DecompType,
1439 diag::err_incomplete_type))
1440 return true;
1441
1442 CXXCastPath BasePath;
1443 DeclAccessPair BasePair =
1444 findDecomposableBaseClass(S, Src->getLocation(), OrigRD, BasePath);
1445 const CXXRecordDecl *RD = cast_or_null<CXXRecordDecl>(BasePair.getDecl());
1446 if (!RD)
1447 return true;
1449 DecompType.getQualifiers());
1450
1451 auto DiagnoseBadNumberOfBindings = [&]() -> bool {
1452 unsigned NumFields = llvm::count_if(
1453 RD->fields(), [](FieldDecl *FD) { return !FD->isUnnamedBitfield(); });
1454 assert(Bindings.size() != NumFields);
1455 S.Diag(Src->getLocation(), diag::err_decomp_decl_wrong_number_bindings)
1456 << DecompType << (unsigned)Bindings.size() << NumFields << NumFields
1457 << (NumFields < Bindings.size());
1458 return true;
1459 };
1460
1461 // all of E's non-static data members shall be [...] well-formed
1462 // when named as e.name in the context of the structured binding,
1463 // E shall not have an anonymous union member, ...
1464 unsigned I = 0;
1465 for (auto *FD : RD->fields()) {
1466 if (FD->isUnnamedBitfield())
1467 continue;
1468
1469 // All the non-static data members are required to be nameable, so they
1470 // must all have names.
1471 if (!FD->getDeclName()) {
1472 if (RD->isLambda()) {
1473 S.Diag(Src->getLocation(), diag::err_decomp_decl_lambda);
1474 S.Diag(RD->getLocation(), diag::note_lambda_decl);
1475 return true;
1476 }
1477
1478 if (FD->isAnonymousStructOrUnion()) {
1479 S.Diag(Src->getLocation(), diag::err_decomp_decl_anon_union_member)
1480 << DecompType << FD->getType()->isUnionType();
1481 S.Diag(FD->getLocation(), diag::note_declared_at);
1482 return true;
1483 }
1484
1485 // FIXME: Are there any other ways we could have an anonymous member?
1486 }
1487
1488 // We have a real field to bind.
1489 if (I >= Bindings.size())
1490 return DiagnoseBadNumberOfBindings();
1491 auto *B = Bindings[I++];
1492 SourceLocation Loc = B->getLocation();
1493
1494 // The field must be accessible in the context of the structured binding.
1495 // We already checked that the base class is accessible.
1496 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1497 // const_cast here.
1499 Loc, const_cast<CXXRecordDecl *>(OrigRD),
1501 BasePair.getAccess(), FD->getAccess())));
1502
1503 // Initialize the binding to Src.FD.
1504 ExprResult E = S.BuildDeclRefExpr(Src, DecompType, VK_LValue, Loc);
1505 if (E.isInvalid())
1506 return true;
1507 E = S.ImpCastExprToType(E.get(), BaseType, CK_UncheckedDerivedToBase,
1508 VK_LValue, &BasePath);
1509 if (E.isInvalid())
1510 return true;
1511 E = S.BuildFieldReferenceExpr(E.get(), /*IsArrow*/ false, Loc,
1512 CXXScopeSpec(), FD,
1513 DeclAccessPair::make(FD, FD->getAccess()),
1514 DeclarationNameInfo(FD->getDeclName(), Loc));
1515 if (E.isInvalid())
1516 return true;
1517
1518 // If the type of the member is T, the referenced type is cv T, where cv is
1519 // the cv-qualification of the decomposition expression.
1520 //
1521 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1522 // 'const' to the type of the field.
1523 Qualifiers Q = DecompType.getQualifiers();
1524 if (FD->isMutable())
1525 Q.removeConst();
1526 B->setBinding(S.BuildQualifiedType(FD->getType(), Loc, Q), E.get());
1527 }
1528
1529 if (I != Bindings.size())
1530 return DiagnoseBadNumberOfBindings();
1531
1532 return false;
1533}
1534
1536 QualType DecompType = DD->getType();
1537
1538 // If the type of the decomposition is dependent, then so is the type of
1539 // each binding.
1540 if (DecompType->isDependentType()) {
1541 for (auto *B : DD->bindings())
1542 B->setType(Context.DependentTy);
1543 return;
1544 }
1545
1546 DecompType = DecompType.getNonReferenceType();
1548
1549 // C++1z [dcl.decomp]/2:
1550 // If E is an array type [...]
1551 // As an extension, we also support decomposition of built-in complex and
1552 // vector types.
1553 if (auto *CAT = Context.getAsConstantArrayType(DecompType)) {
1554 if (checkArrayDecomposition(*this, Bindings, DD, DecompType, CAT))
1555 DD->setInvalidDecl();
1556 return;
1557 }
1558 if (auto *VT = DecompType->getAs<VectorType>()) {
1559 if (checkVectorDecomposition(*this, Bindings, DD, DecompType, VT))
1560 DD->setInvalidDecl();
1561 return;
1562 }
1563 if (auto *CT = DecompType->getAs<ComplexType>()) {
1564 if (checkComplexDecomposition(*this, Bindings, DD, DecompType, CT))
1565 DD->setInvalidDecl();
1566 return;
1567 }
1568
1569 // C++1z [dcl.decomp]/3:
1570 // if the expression std::tuple_size<E>::value is a well-formed integral
1571 // constant expression, [...]
1572 llvm::APSInt TupleSize(32);
1573 switch (isTupleLike(*this, DD->getLocation(), DecompType, TupleSize)) {
1574 case IsTupleLike::Error:
1575 DD->setInvalidDecl();
1576 return;
1577
1578 case IsTupleLike::TupleLike:
1579 if (checkTupleLikeDecomposition(*this, Bindings, DD, DecompType, TupleSize))
1580 DD->setInvalidDecl();
1581 return;
1582
1583 case IsTupleLike::NotTupleLike:
1584 break;
1585 }
1586
1587 // C++1z [dcl.dcl]/8:
1588 // [E shall be of array or non-union class type]
1589 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1590 if (!RD || RD->isUnion()) {
1591 Diag(DD->getLocation(), diag::err_decomp_decl_unbindable_type)
1592 << DD << !RD << DecompType;
1593 DD->setInvalidDecl();
1594 return;
1595 }
1596
1597 // C++1z [dcl.decomp]/4:
1598 // all of E's non-static data members shall be [...] direct members of
1599 // E or of the same unambiguous public base class of E, ...
1600 if (checkMemberDecomposition(*this, Bindings, DD, DecompType, RD))
1601 DD->setInvalidDecl();
1602}
1603
1604/// Merge the exception specifications of two variable declarations.
1605///
1606/// This is called when there's a redeclaration of a VarDecl. The function
1607/// checks if the redeclaration might have an exception specification and
1608/// validates compatibility and merges the specs if necessary.
1610 // Shortcut if exceptions are disabled.
1611 if (!getLangOpts().CXXExceptions)
1612 return;
1613
1614 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1615 "Should only be called if types are otherwise the same.");
1616
1617 QualType NewType = New->getType();
1618 QualType OldType = Old->getType();
1619
1620 // We're only interested in pointers and references to functions, as well
1621 // as pointers to member functions.
1622 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1623 NewType = R->getPointeeType();
1624 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1625 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1626 NewType = P->getPointeeType();
1627 OldType = OldType->castAs<PointerType>()->getPointeeType();
1628 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1629 NewType = M->getPointeeType();
1630 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1631 }
1632
1633 if (!NewType->isFunctionProtoType())
1634 return;
1635
1636 // There's lots of special cases for functions. For function pointers, system
1637 // libraries are hopefully not as broken so that we don't need these
1638 // workarounds.
1640 OldType->getAs<FunctionProtoType>(), Old->getLocation(),
1641 NewType->getAs<FunctionProtoType>(), New->getLocation())) {
1642 New->setInvalidDecl();
1643 }
1644}
1645
1646/// CheckCXXDefaultArguments - Verify that the default arguments for a
1647/// function declaration are well-formed according to C++
1648/// [dcl.fct.default].
1650 unsigned NumParams = FD->getNumParams();
1651 unsigned ParamIdx = 0;
1652
1653 // This checking doesn't make sense for explicit specializations; their
1654 // default arguments are determined by the declaration we're specializing,
1655 // not by FD.
1657 return;
1658 if (auto *FTD = FD->getDescribedFunctionTemplate())
1659 if (FTD->isMemberSpecialization())
1660 return;
1661
1662 // Find first parameter with a default argument
1663 for (; ParamIdx < NumParams; ++ParamIdx) {
1664 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1665 if (Param->hasDefaultArg())
1666 break;
1667 }
1668
1669 // C++20 [dcl.fct.default]p4:
1670 // In a given function declaration, each parameter subsequent to a parameter
1671 // with a default argument shall have a default argument supplied in this or
1672 // a previous declaration, unless the parameter was expanded from a
1673 // parameter pack, or shall be a function parameter pack.
1674 for (; ParamIdx < NumParams; ++ParamIdx) {
1675 ParmVarDecl *Param = FD->getParamDecl(ParamIdx);
1676 if (!Param->hasDefaultArg() && !Param->isParameterPack() &&
1679 if (Param->isInvalidDecl())
1680 /* We already complained about this parameter. */;
1681 else if (Param->getIdentifier())
1682 Diag(Param->getLocation(),
1683 diag::err_param_default_argument_missing_name)
1684 << Param->getIdentifier();
1685 else
1686 Diag(Param->getLocation(),
1687 diag::err_param_default_argument_missing);
1688 }
1689 }
1690}
1691
1692/// Check that the given type is a literal type. Issue a diagnostic if not,
1693/// if Kind is Diagnose.
1694/// \return \c true if a problem has been found (and optionally diagnosed).
1695template <typename... Ts>
1697 SourceLocation Loc, QualType T, unsigned DiagID,
1698 Ts &&...DiagArgs) {
1699 if (T->isDependentType())
1700 return false;
1701
1702 switch (Kind) {
1704 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1705 std::forward<Ts>(DiagArgs)...);
1706
1708 return !T->isLiteralType(SemaRef.Context);
1709 }
1710
1711 llvm_unreachable("unknown CheckConstexprKind");
1712}
1713
1714/// Determine whether a destructor cannot be constexpr due to
1716 const CXXDestructorDecl *DD,
1718 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1719 "this check is obsolete for C++23");
1720 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1721 const CXXRecordDecl *RD =
1723 if (!RD || RD->hasConstexprDestructor())
1724 return true;
1725
1727 SemaRef.Diag(DD->getLocation(), diag::err_constexpr_dtor_subobject)
1728 << static_cast<int>(DD->getConstexprKind()) << !FD
1729 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1730 SemaRef.Diag(Loc, diag::note_constexpr_dtor_subobject)
1731 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1732 }
1733 return false;
1734 };
1735
1736 const CXXRecordDecl *RD = DD->getParent();
1737 for (const CXXBaseSpecifier &B : RD->bases())
1738 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1739 return false;
1740 for (const FieldDecl *FD : RD->fields())
1741 if (!Check(FD->getLocation(), FD->getType(), FD))
1742 return false;
1743 return true;
1744}
1745
1746/// Check whether a function's parameter types are all literal types. If so,
1747/// return true. If not, produce a suitable diagnostic and return false.
1749 const FunctionDecl *FD,
1751 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1752 "this check is obsolete for C++23");
1753 unsigned ArgIndex = 0;
1754 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1755 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1756 e = FT->param_type_end();
1757 i != e; ++i, ++ArgIndex) {
1758 const ParmVarDecl *PD = FD->getParamDecl(ArgIndex);
1759 assert(PD && "null in a parameter list");
1760 SourceLocation ParamLoc = PD->getLocation();
1761 if (CheckLiteralType(SemaRef, Kind, ParamLoc, *i,
1762 diag::err_constexpr_non_literal_param, ArgIndex + 1,
1763 PD->getSourceRange(), isa<CXXConstructorDecl>(FD),
1764 FD->isConsteval()))
1765 return false;
1766 }
1767 return true;
1768}
1769
1770/// Check whether a function's return type is a literal type. If so, return
1771/// true. If not, produce a suitable diagnostic and return false.
1774 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1775 "this check is obsolete for C++23");
1776 if (CheckLiteralType(SemaRef, Kind, FD->getLocation(), FD->getReturnType(),
1777 diag::err_constexpr_non_literal_return,
1778 FD->isConsteval()))
1779 return false;
1780 return true;
1781}
1782
1783/// Get diagnostic %select index for tag kind for
1784/// record diagnostic message.
1785/// WARNING: Indexes apply to particular diagnostics only!
1786///
1787/// \returns diagnostic %select index.
1789 switch (Tag) {
1791 return 0;
1793 return 1;
1794 case TagTypeKind::Class:
1795 return 2;
1796 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1797 }
1798}
1799
1800static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1801 Stmt *Body,
1803
1804// Check whether a function declaration satisfies the requirements of a
1805// constexpr function definition or a constexpr constructor definition. If so,
1806// return true. If not, produce appropriate diagnostics (unless asked not to by
1807// Kind) and return false.
1808//
1809// This implements C++11 [dcl.constexpr]p3,4, as amended by DR1360.
1811 CheckConstexprKind Kind) {
1812 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(NewFD);
1813 if (MD && MD->isInstance()) {
1814 // C++11 [dcl.constexpr]p4:
1815 // The definition of a constexpr constructor shall satisfy the following
1816 // constraints:
1817 // - the class shall not have any virtual base classes;
1818 //
1819 // FIXME: This only applies to constructors and destructors, not arbitrary
1820 // member functions.
1821 const CXXRecordDecl *RD = MD->getParent();
1822 if (RD->getNumVBases()) {
1824 return false;
1825
1826 Diag(NewFD->getLocation(), diag::err_constexpr_virtual_base)
1827 << isa<CXXConstructorDecl>(NewFD)
1829 for (const auto &I : RD->vbases())
1830 Diag(I.getBeginLoc(), diag::note_constexpr_virtual_base_here)
1831 << I.getSourceRange();
1832 return false;
1833 }
1834 }
1835
1836 if (!isa<CXXConstructorDecl>(NewFD)) {
1837 // C++11 [dcl.constexpr]p3:
1838 // The definition of a constexpr function shall satisfy the following
1839 // constraints:
1840 // - it shall not be virtual; (removed in C++20)
1841 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(NewFD);
1842 if (Method && Method->isVirtual()) {
1843 if (getLangOpts().CPlusPlus20) {
1844 if (Kind == CheckConstexprKind::Diagnose)
1845 Diag(Method->getLocation(), diag::warn_cxx17_compat_constexpr_virtual);
1846 } else {
1848 return false;
1849
1850 Method = Method->getCanonicalDecl();
1851 Diag(Method->getLocation(), diag::err_constexpr_virtual);
1852
1853 // If it's not obvious why this function is virtual, find an overridden
1854 // function which uses the 'virtual' keyword.
1855 const CXXMethodDecl *WrittenVirtual = Method;
1856 while (!WrittenVirtual->isVirtualAsWritten())
1857 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1858 if (WrittenVirtual != Method)
1859 Diag(WrittenVirtual->getLocation(),
1860 diag::note_overridden_virtual_function);
1861 return false;
1862 }
1863 }
1864
1865 // - its return type shall be a literal type; (removed in C++23)
1866 if (!getLangOpts().CPlusPlus23 &&
1867 !CheckConstexprReturnType(*this, NewFD, Kind))
1868 return false;
1869 }
1870
1871 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(NewFD)) {
1872 // A destructor can be constexpr only if the defaulted destructor could be;
1873 // we don't need to check the members and bases if we already know they all
1874 // have constexpr destructors. (removed in C++23)
1875 if (!getLangOpts().CPlusPlus23 &&
1876 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1878 return false;
1879 if (!CheckConstexprDestructorSubobjects(*this, Dtor, Kind))
1880 return false;
1881 }
1882 }
1883
1884 // - each of its parameter types shall be a literal type; (removed in C++23)
1885 if (!getLangOpts().CPlusPlus23 &&
1886 !CheckConstexprParameterTypes(*this, NewFD, Kind))
1887 return false;
1888
1889 Stmt *Body = NewFD->getBody();
1890 assert(Body &&
1891 "CheckConstexprFunctionDefinition called on function with no body");
1892 return CheckConstexprFunctionBody(*this, NewFD, Body, Kind);
1893}
1894
1895/// Check the given declaration statement is legal within a constexpr function
1896/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
1897///
1898/// \return true if the body is OK (maybe only as an extension), false if we
1899/// have diagnosed a problem.
1901 DeclStmt *DS, SourceLocation &Cxx1yLoc,
1903 // C++11 [dcl.constexpr]p3 and p4:
1904 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
1905 // contain only
1906 for (const auto *DclIt : DS->decls()) {
1907 switch (DclIt->getKind()) {
1908 case Decl::StaticAssert:
1909 case Decl::Using:
1910 case Decl::UsingShadow:
1911 case Decl::UsingDirective:
1912 case Decl::UnresolvedUsingTypename:
1913 case Decl::UnresolvedUsingValue:
1914 case Decl::UsingEnum:
1915 // - static_assert-declarations
1916 // - using-declarations,
1917 // - using-directives,
1918 // - using-enum-declaration
1919 continue;
1920
1921 case Decl::Typedef:
1922 case Decl::TypeAlias: {
1923 // - typedef declarations and alias-declarations that do not define
1924 // classes or enumerations,
1925 const auto *TN = cast<TypedefNameDecl>(DclIt);
1926 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
1927 // Don't allow variably-modified types in constexpr functions.
1929 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
1930 SemaRef.Diag(TL.getBeginLoc(), diag::err_constexpr_vla)
1931 << TL.getSourceRange() << TL.getType()
1932 << isa<CXXConstructorDecl>(Dcl);
1933 }
1934 return false;
1935 }
1936 continue;
1937 }
1938
1939 case Decl::Enum:
1940 case Decl::CXXRecord:
1941 // C++1y allows types to be defined, not just declared.
1942 if (cast<TagDecl>(DclIt)->isThisDeclarationADefinition()) {
1944 SemaRef.Diag(DS->getBeginLoc(),
1945 SemaRef.getLangOpts().CPlusPlus14
1946 ? diag::warn_cxx11_compat_constexpr_type_definition
1947 : diag::ext_constexpr_type_definition)
1948 << isa<CXXConstructorDecl>(Dcl);
1949 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
1950 return false;
1951 }
1952 }
1953 continue;
1954
1955 case Decl::EnumConstant:
1956 case Decl::IndirectField:
1957 case Decl::ParmVar:
1958 // These can only appear with other declarations which are banned in
1959 // C++11 and permitted in C++1y, so ignore them.
1960 continue;
1961
1962 case Decl::Var:
1963 case Decl::Decomposition: {
1964 // C++1y [dcl.constexpr]p3 allows anything except:
1965 // a definition of a variable of non-literal type or of static or
1966 // thread storage duration or [before C++2a] for which no
1967 // initialization is performed.
1968 const auto *VD = cast<VarDecl>(DclIt);
1969 if (VD->isThisDeclarationADefinition()) {
1970 if (VD->isStaticLocal()) {
1972 SemaRef.Diag(VD->getLocation(),
1973 SemaRef.getLangOpts().CPlusPlus23
1974 ? diag::warn_cxx20_compat_constexpr_var
1975 : diag::ext_constexpr_static_var)
1976 << isa<CXXConstructorDecl>(Dcl)
1977 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
1978 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
1979 return false;
1980 }
1981 }
1982 if (SemaRef.LangOpts.CPlusPlus23) {
1983 CheckLiteralType(SemaRef, Kind, VD->getLocation(), VD->getType(),
1984 diag::warn_cxx20_compat_constexpr_var,
1985 isa<CXXConstructorDecl>(Dcl),
1986 /*variable of non-literal type*/ 2);
1987 } else if (CheckLiteralType(
1988 SemaRef, Kind, VD->getLocation(), VD->getType(),
1989 diag::err_constexpr_local_var_non_literal_type,
1990 isa<CXXConstructorDecl>(Dcl))) {
1991 return false;
1992 }
1993 if (!VD->getType()->isDependentType() &&
1994 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
1996 SemaRef.Diag(
1997 VD->getLocation(),
1998 SemaRef.getLangOpts().CPlusPlus20
1999 ? diag::warn_cxx17_compat_constexpr_local_var_no_init
2000 : diag::ext_constexpr_local_var_no_init)
2001 << isa<CXXConstructorDecl>(Dcl);
2002 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2003 return false;
2004 }
2005 continue;
2006 }
2007 }
2009 SemaRef.Diag(VD->getLocation(),
2010 SemaRef.getLangOpts().CPlusPlus14
2011 ? diag::warn_cxx11_compat_constexpr_local_var
2012 : diag::ext_constexpr_local_var)
2013 << isa<CXXConstructorDecl>(Dcl);
2014 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2015 return false;
2016 }
2017 continue;
2018 }
2019
2020 case Decl::NamespaceAlias:
2021 case Decl::Function:
2022 // These are disallowed in C++11 and permitted in C++1y. Allow them
2023 // everywhere as an extension.
2024 if (!Cxx1yLoc.isValid())
2025 Cxx1yLoc = DS->getBeginLoc();
2026 continue;
2027
2028 default:
2030 SemaRef.Diag(DS->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2031 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2032 }
2033 return false;
2034 }
2035 }
2036
2037 return true;
2038}
2039
2040/// Check that the given field is initialized within a constexpr constructor.
2041///
2042/// \param Dcl The constexpr constructor being checked.
2043/// \param Field The field being checked. This may be a member of an anonymous
2044/// struct or union nested within the class being checked.
2045/// \param Inits All declarations, including anonymous struct/union members and
2046/// indirect members, for which any initialization was provided.
2047/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2048/// multiple notes for different members to the same error.
2049/// \param Kind Whether we're diagnosing a constructor as written or determining
2050/// whether the formal requirements are satisfied.
2051/// \return \c false if we're checking for validity and the constructor does
2052/// not satisfy the requirements on a constexpr constructor.
2054 const FunctionDecl *Dcl,
2055 FieldDecl *Field,
2056 llvm::SmallSet<Decl*, 16> &Inits,
2057 bool &Diagnosed,
2059 // In C++20 onwards, there's nothing to check for validity.
2061 SemaRef.getLangOpts().CPlusPlus20)
2062 return true;
2063
2064 if (Field->isInvalidDecl())
2065 return true;
2066
2067 if (Field->isUnnamedBitfield())
2068 return true;
2069
2070 // Anonymous unions with no variant members and empty anonymous structs do not
2071 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2072 // indirect fields don't need initializing.
2073 if (Field->isAnonymousStructOrUnion() &&
2074 (Field->getType()->isUnionType()
2075 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2076 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2077 return true;
2078
2079 if (!Inits.count(Field)) {
2081 if (!Diagnosed) {
2082 SemaRef.Diag(Dcl->getLocation(),
2083 SemaRef.getLangOpts().CPlusPlus20
2084 ? diag::warn_cxx17_compat_constexpr_ctor_missing_init
2085 : diag::ext_constexpr_ctor_missing_init);
2086 Diagnosed = true;
2087 }
2088 SemaRef.Diag(Field->getLocation(),
2089 diag::note_constexpr_ctor_missing_init);
2090 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2091 return false;
2092 }
2093 } else if (Field->isAnonymousStructOrUnion()) {
2094 const RecordDecl *RD = Field->getType()->castAs<RecordType>()->getDecl();
2095 for (auto *I : RD->fields())
2096 // If an anonymous union contains an anonymous struct of which any member
2097 // is initialized, all members must be initialized.
2098 if (!RD->isUnion() || Inits.count(I))
2099 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2100 Kind))
2101 return false;
2102 }
2103 return true;
2104}
2105
2106/// Check the provided statement is allowed in a constexpr function
2107/// definition.
2108static bool
2111 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2112 SourceLocation &Cxx2bLoc,
2114 // - its function-body shall be [...] a compound-statement that contains only
2115 switch (S->getStmtClass()) {
2116 case Stmt::NullStmtClass:
2117 // - null statements,
2118 return true;
2119
2120 case Stmt::DeclStmtClass:
2121 // - static_assert-declarations
2122 // - using-declarations,
2123 // - using-directives,
2124 // - typedef declarations and alias-declarations that do not define
2125 // classes or enumerations,
2126 if (!CheckConstexprDeclStmt(SemaRef, Dcl, cast<DeclStmt>(S), Cxx1yLoc, Kind))
2127 return false;
2128 return true;
2129
2130 case Stmt::ReturnStmtClass:
2131 // - and exactly one return statement;
2132 if (isa<CXXConstructorDecl>(Dcl)) {
2133 // C++1y allows return statements in constexpr constructors.
2134 if (!Cxx1yLoc.isValid())
2135 Cxx1yLoc = S->getBeginLoc();
2136 return true;
2137 }
2138
2139 ReturnStmts.push_back(S->getBeginLoc());
2140 return true;
2141
2142 case Stmt::AttributedStmtClass:
2143 // Attributes on a statement don't affect its formal kind and hence don't
2144 // affect its validity in a constexpr function.
2146 SemaRef, Dcl, cast<AttributedStmt>(S)->getSubStmt(), ReturnStmts,
2147 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2148
2149 case Stmt::CompoundStmtClass: {
2150 // C++1y allows compound-statements.
2151 if (!Cxx1yLoc.isValid())
2152 Cxx1yLoc = S->getBeginLoc();
2153
2154 CompoundStmt *CompStmt = cast<CompoundStmt>(S);
2155 for (auto *BodyIt : CompStmt->body()) {
2156 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, BodyIt, ReturnStmts,
2157 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2158 return false;
2159 }
2160 return true;
2161 }
2162
2163 case Stmt::IfStmtClass: {
2164 // C++1y allows if-statements.
2165 if (!Cxx1yLoc.isValid())
2166 Cxx1yLoc = S->getBeginLoc();
2167
2168 IfStmt *If = cast<IfStmt>(S);
2169 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, If->getThen(), ReturnStmts,
2170 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2171 return false;
2172 if (If->getElse() &&
2173 !CheckConstexprFunctionStmt(SemaRef, Dcl, If->getElse(), ReturnStmts,
2174 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2175 return false;
2176 return true;
2177 }
2178
2179 case Stmt::WhileStmtClass:
2180 case Stmt::DoStmtClass:
2181 case Stmt::ForStmtClass:
2182 case Stmt::CXXForRangeStmtClass:
2183 case Stmt::ContinueStmtClass:
2184 // C++1y allows all of these. We don't allow them as extensions in C++11,
2185 // because they don't make sense without variable mutation.
2186 if (!SemaRef.getLangOpts().CPlusPlus14)
2187 break;
2188 if (!Cxx1yLoc.isValid())
2189 Cxx1yLoc = S->getBeginLoc();
2190 for (Stmt *SubStmt : S->children()) {
2191 if (SubStmt &&
2192 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2193 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2194 return false;
2195 }
2196 return true;
2197
2198 case Stmt::SwitchStmtClass:
2199 case Stmt::CaseStmtClass:
2200 case Stmt::DefaultStmtClass:
2201 case Stmt::BreakStmtClass:
2202 // C++1y allows switch-statements, and since they don't need variable
2203 // mutation, we can reasonably allow them in C++11 as an extension.
2204 if (!Cxx1yLoc.isValid())
2205 Cxx1yLoc = S->getBeginLoc();
2206 for (Stmt *SubStmt : S->children()) {
2207 if (SubStmt &&
2208 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2209 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2210 return false;
2211 }
2212 return true;
2213
2214 case Stmt::LabelStmtClass:
2215 case Stmt::GotoStmtClass:
2216 if (Cxx2bLoc.isInvalid())
2217 Cxx2bLoc = S->getBeginLoc();
2218 for (Stmt *SubStmt : S->children()) {
2219 if (SubStmt &&
2220 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2221 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2222 return false;
2223 }
2224 return true;
2225
2226 case Stmt::GCCAsmStmtClass:
2227 case Stmt::MSAsmStmtClass:
2228 // C++2a allows inline assembly statements.
2229 case Stmt::CXXTryStmtClass:
2230 if (Cxx2aLoc.isInvalid())
2231 Cxx2aLoc = S->getBeginLoc();
2232 for (Stmt *SubStmt : S->children()) {
2233 if (SubStmt &&
2234 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2235 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2236 return false;
2237 }
2238 return true;
2239
2240 case Stmt::CXXCatchStmtClass:
2241 // Do not bother checking the language mode (already covered by the
2242 // try block check).
2244 SemaRef, Dcl, cast<CXXCatchStmt>(S)->getHandlerBlock(), ReturnStmts,
2245 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2246 return false;
2247 return true;
2248
2249 default:
2250 if (!isa<Expr>(S))
2251 break;
2252
2253 // C++1y allows expression-statements.
2254 if (!Cxx1yLoc.isValid())
2255 Cxx1yLoc = S->getBeginLoc();
2256 return true;
2257 }
2258
2260 SemaRef.Diag(S->getBeginLoc(), diag::err_constexpr_body_invalid_stmt)
2261 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval();
2262 }
2263 return false;
2264}
2265
2266/// Check the body for the given constexpr function declaration only contains
2267/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2268///
2269/// \return true if the body is OK, false if we have found or diagnosed a
2270/// problem.
2272 Stmt *Body,
2275
2276 if (isa<CXXTryStmt>(Body)) {
2277 // C++11 [dcl.constexpr]p3:
2278 // The definition of a constexpr function shall satisfy the following
2279 // constraints: [...]
2280 // - its function-body shall be = delete, = default, or a
2281 // compound-statement
2282 //
2283 // C++11 [dcl.constexpr]p4:
2284 // In the definition of a constexpr constructor, [...]
2285 // - its function-body shall not be a function-try-block;
2286 //
2287 // This restriction is lifted in C++2a, as long as inner statements also
2288 // apply the general constexpr rules.
2289 switch (Kind) {
2291 if (!SemaRef.getLangOpts().CPlusPlus20)
2292 return false;
2293 break;
2294
2296 SemaRef.Diag(Body->getBeginLoc(),
2297 !SemaRef.getLangOpts().CPlusPlus20
2298 ? diag::ext_constexpr_function_try_block_cxx20
2299 : diag::warn_cxx17_compat_constexpr_function_try_block)
2300 << isa<CXXConstructorDecl>(Dcl);
2301 break;
2302 }
2303 }
2304
2305 // - its function-body shall be [...] a compound-statement that contains only
2306 // [... list of cases ...]
2307 //
2308 // Note that walking the children here is enough to properly check for
2309 // CompoundStmt and CXXTryStmt body.
2310 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2311 for (Stmt *SubStmt : Body->children()) {
2312 if (SubStmt &&
2313 !CheckConstexprFunctionStmt(SemaRef, Dcl, SubStmt, ReturnStmts,
2314 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2315 return false;
2316 }
2317
2319 // If this is only valid as an extension, report that we don't satisfy the
2320 // constraints of the current language.
2321 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2322 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2323 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2324 return false;
2325 } else if (Cxx2bLoc.isValid()) {
2326 SemaRef.Diag(Cxx2bLoc,
2327 SemaRef.getLangOpts().CPlusPlus23
2328 ? diag::warn_cxx20_compat_constexpr_body_invalid_stmt
2329 : diag::ext_constexpr_body_invalid_stmt_cxx23)
2330 << isa<CXXConstructorDecl>(Dcl);
2331 } else if (Cxx2aLoc.isValid()) {
2332 SemaRef.Diag(Cxx2aLoc,
2333 SemaRef.getLangOpts().CPlusPlus20
2334 ? diag::warn_cxx17_compat_constexpr_body_invalid_stmt
2335 : diag::ext_constexpr_body_invalid_stmt_cxx20)
2336 << isa<CXXConstructorDecl>(Dcl);
2337 } else if (Cxx1yLoc.isValid()) {
2338 SemaRef.Diag(Cxx1yLoc,
2339 SemaRef.getLangOpts().CPlusPlus14
2340 ? diag::warn_cxx11_compat_constexpr_body_invalid_stmt
2341 : diag::ext_constexpr_body_invalid_stmt)
2342 << isa<CXXConstructorDecl>(Dcl);
2343 }
2344
2345 if (const CXXConstructorDecl *Constructor
2346 = dyn_cast<CXXConstructorDecl>(Dcl)) {
2347 const CXXRecordDecl *RD = Constructor->getParent();
2348 // DR1359:
2349 // - every non-variant non-static data member and base class sub-object
2350 // shall be initialized;
2351 // DR1460:
2352 // - if the class is a union having variant members, exactly one of them
2353 // shall be initialized;
2354 if (RD->isUnion()) {
2355 if (Constructor->getNumCtorInitializers() == 0 &&
2356 RD->hasVariantMembers()) {
2358 SemaRef.Diag(
2359 Dcl->getLocation(),
2360 SemaRef.getLangOpts().CPlusPlus20
2361 ? diag::warn_cxx17_compat_constexpr_union_ctor_no_init
2362 : diag::ext_constexpr_union_ctor_no_init);
2363 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2364 return false;
2365 }
2366 }
2367 } else if (!Constructor->isDependentContext() &&
2368 !Constructor->isDelegatingConstructor()) {
2369 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2370
2371 // Skip detailed checking if we have enough initializers, and we would
2372 // allow at most one initializer per member.
2373 bool AnyAnonStructUnionMembers = false;
2374 unsigned Fields = 0;
2376 E = RD->field_end(); I != E; ++I, ++Fields) {
2377 if (I->isAnonymousStructOrUnion()) {
2378 AnyAnonStructUnionMembers = true;
2379 break;
2380 }
2381 }
2382 // DR1460:
2383 // - if the class is a union-like class, but is not a union, for each of
2384 // its anonymous union members having variant members, exactly one of
2385 // them shall be initialized;
2386 if (AnyAnonStructUnionMembers ||
2387 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2388 // Check initialization of non-static data members. Base classes are
2389 // always initialized so do not need to be checked. Dependent bases
2390 // might not have initializers in the member initializer list.
2391 llvm::SmallSet<Decl*, 16> Inits;
2392 for (const auto *I: Constructor->inits()) {
2393 if (FieldDecl *FD = I->getMember())
2394 Inits.insert(FD);
2395 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2396 Inits.insert(ID->chain_begin(), ID->chain_end());
2397 }
2398
2399 bool Diagnosed = false;
2400 for (auto *I : RD->fields())
2401 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, I, Inits, Diagnosed,
2402 Kind))
2403 return false;
2404 }
2405 }
2406 } else {
2407 if (ReturnStmts.empty()) {
2408 // C++1y doesn't require constexpr functions to contain a 'return'
2409 // statement. We still do, unless the return type might be void, because
2410 // otherwise if there's no return statement, the function cannot
2411 // be used in a core constant expression.
2412 bool OK = SemaRef.getLangOpts().CPlusPlus14 &&
2413 (Dcl->getReturnType()->isVoidType() ||
2414 Dcl->getReturnType()->isDependentType());
2415 switch (Kind) {
2417 SemaRef.Diag(Dcl->getLocation(),
2418 OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2419 : diag::err_constexpr_body_no_return)
2420 << Dcl->isConsteval();
2421 if (!OK)
2422 return false;
2423 break;
2424
2426 // The formal requirements don't include this rule in C++14, even
2427 // though the "must be able to produce a constant expression" rules
2428 // still imply it in some cases.
2429 if (!SemaRef.getLangOpts().CPlusPlus14)
2430 return false;
2431 break;
2432 }
2433 } else if (ReturnStmts.size() > 1) {
2434 switch (Kind) {
2436 SemaRef.Diag(
2437 ReturnStmts.back(),
2438 SemaRef.getLangOpts().CPlusPlus14
2439 ? diag::warn_cxx11_compat_constexpr_body_multiple_return
2440 : diag::ext_constexpr_body_multiple_return);
2441 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2442 SemaRef.Diag(ReturnStmts[I],
2443 diag::note_constexpr_body_previous_return);
2444 break;
2445
2447 if (!SemaRef.getLangOpts().CPlusPlus14)
2448 return false;
2449 break;
2450 }
2451 }
2452 }
2453
2454 // C++11 [dcl.constexpr]p5:
2455 // if no function argument values exist such that the function invocation
2456 // substitution would produce a constant expression, the program is
2457 // ill-formed; no diagnostic required.
2458 // C++11 [dcl.constexpr]p3:
2459 // - every constructor call and implicit conversion used in initializing the
2460 // return value shall be one of those allowed in a constant expression.
2461 // C++11 [dcl.constexpr]p4:
2462 // - every constructor involved in initializing non-static data members and
2463 // base class sub-objects shall be a constexpr constructor.
2464 //
2465 // Note that this rule is distinct from the "requirements for a constexpr
2466 // function", so is not checked in CheckValid mode.
2470 !SemaRef.getLangOpts().CPlusPlus23) {
2471 SemaRef.Diag(Dcl->getLocation(),
2472 diag::ext_constexpr_function_never_constant_expr)
2473 << isa<CXXConstructorDecl>(Dcl) << Dcl->isConsteval()
2474 << Dcl->getNameInfo().getSourceRange();
2475 for (size_t I = 0, N = Diags.size(); I != N; ++I)
2476 SemaRef.Diag(Diags[I].first, Diags[I].second);
2477 // Don't return false here: we allow this for compatibility in
2478 // system headers.
2479 }
2480
2481 return true;
2482}
2483
2485 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2487 return true;
2491 auto it = UndefinedButUsed.find(FD->getCanonicalDecl());
2492 if (it != UndefinedButUsed.end()) {
2493 Diag(it->second, diag::err_immediate_function_used_before_definition)
2494 << it->first;
2495 Diag(FD->getLocation(), diag::note_defined_here) << FD;
2496 if (FD->isImmediateFunction() && !FD->isConsteval())
2498 return false;
2499 }
2500 }
2501 return true;
2502}
2503
2505 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2506 "expected an immediate function");
2507 assert(FD->hasBody() && "expected the function to have a body");
2508 struct ImmediateEscalatingExpressionsVisitor
2509 : public RecursiveASTVisitor<ImmediateEscalatingExpressionsVisitor> {
2510
2512 Sema &SemaRef;
2513
2514 const FunctionDecl *ImmediateFn;
2515 bool ImmediateFnIsConstructor;
2516 CXXConstructorDecl *CurrentConstructor = nullptr;
2517 CXXCtorInitializer *CurrentInit = nullptr;
2518
2519 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2520 : SemaRef(SemaRef), ImmediateFn(FD),
2521 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(FD)) {}
2522
2523 bool shouldVisitImplicitCode() const { return true; }
2524 bool shouldVisitLambdaBody() const { return false; }
2525
2526 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2527 SourceLocation Loc = E->getBeginLoc();
2528 SourceRange Range = E->getSourceRange();
2529 if (CurrentConstructor && CurrentInit) {
2530 Loc = CurrentConstructor->getLocation();
2531 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2532 : SourceRange();
2533 }
2534
2535 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2536
2537 SemaRef.Diag(Loc, diag::note_immediate_function_reason)
2538 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2539 << isa<CXXConstructorDecl>(Fn) << ImmediateFnIsConstructor
2540 << (InitializedField != nullptr)
2541 << (CurrentInit && !CurrentInit->isWritten())
2542 << InitializedField << Range;
2543 }
2544 bool TraverseCallExpr(CallExpr *E) {
2545 if (const auto *DR =
2546 dyn_cast<DeclRefExpr>(E->getCallee()->IgnoreImplicit());
2547 DR && DR->isImmediateEscalating()) {
2548 Diag(E, E->getDirectCallee(), /*IsCall=*/true);
2549 return false;
2550 }
2551
2552 for (Expr *A : E->arguments())
2553 if (!getDerived().TraverseStmt(A))
2554 return false;
2555
2556 return true;
2557 }
2558
2559 bool VisitDeclRefExpr(DeclRefExpr *E) {
2560 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(E->getDecl());
2561 ReferencedFn && E->isImmediateEscalating()) {
2562 Diag(E, ReferencedFn, /*IsCall=*/false);
2563 return false;
2564 }
2565
2566 return true;
2567 }
2568
2569 bool VisitCXXConstructExpr(CXXConstructExpr *E) {
2571 if (E->isImmediateEscalating()) {
2572 Diag(E, D, /*IsCall=*/true);
2573 return false;
2574 }
2575 return true;
2576 }
2577
2578 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) {
2579 llvm::SaveAndRestore RAII(CurrentInit, Init);
2580 return Base::TraverseConstructorInitializer(Init);
2581 }
2582
2583 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) {
2584 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2585 return Base::TraverseCXXConstructorDecl(Ctr);
2586 }
2587
2588 bool TraverseType(QualType T) { return true; }
2589 bool VisitBlockExpr(BlockExpr *T) { return true; }
2590
2591 } Visitor(*this, FD);
2592 Visitor.TraverseDecl(FD);
2593}
2594
2595/// Get the class that is directly named by the current context. This is the
2596/// class for which an unqualified-id in this scope could name a constructor
2597/// or destructor.
2598///
2599/// If the scope specifier denotes a class, this will be that class.
2600/// If the scope specifier is empty, this will be the class whose
2601/// member-specification we are currently within. Otherwise, there
2602/// is no such class.
2604 assert(getLangOpts().CPlusPlus && "No class names in C!");
2605
2606 if (SS && SS->isInvalid())
2607 return nullptr;
2608
2609 if (SS && SS->isNotEmpty()) {
2610 DeclContext *DC = computeDeclContext(*SS, true);
2611 return dyn_cast_or_null<CXXRecordDecl>(DC);
2612 }
2613
2614 return dyn_cast_or_null<CXXRecordDecl>(CurContext);
2615}
2616
2617/// isCurrentClassName - Determine whether the identifier II is the
2618/// name of the class type currently being defined. In the case of
2619/// nested classes, this will only return true if II is the name of
2620/// the innermost class.
2622 const CXXScopeSpec *SS) {
2623 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2624 return CurDecl && &II == CurDecl->getIdentifier();
2625}
2626
2627/// Determine whether the identifier II is a typo for the name of
2628/// the class type currently being defined. If so, update it to the identifier
2629/// that should have been used.
2631 assert(getLangOpts().CPlusPlus && "No class names in C!");
2632
2633 if (!getLangOpts().SpellChecking)
2634 return false;
2635
2636 CXXRecordDecl *CurDecl;
2637 if (SS && SS->isSet() && !SS->isInvalid()) {
2638 DeclContext *DC = computeDeclContext(*SS, true);
2639 CurDecl = dyn_cast_or_null<CXXRecordDecl>(DC);
2640 } else
2641 CurDecl = dyn_cast_or_null<CXXRecordDecl>(CurContext);
2642
2643 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2644 3 * II->getName().edit_distance(CurDecl->getIdentifier()->getName())
2645 < II->getLength()) {
2646 II = CurDecl->getIdentifier();
2647 return true;
2648 }
2649
2650 return false;
2651}
2652
2653/// Determine whether the given class is a base class of the given
2654/// class, including looking at dependent bases.
2656 const CXXRecordDecl *Current) {
2658
2659 Class = Class->getCanonicalDecl();
2660 while (true) {
2661 for (const auto &I : Current->bases()) {
2662 CXXRecordDecl *Base = I.getType()->getAsCXXRecordDecl();
2663 if (!Base)
2664 continue;
2665
2666 Base = Base->getDefinition();
2667 if (!Base)
2668 continue;
2669
2670 if (Base->getCanonicalDecl() == Class)
2671 return true;
2672
2673 Queue.push_back(Base);
2674 }
2675
2676 if (Queue.empty())
2677 return false;
2678
2679 Current = Queue.pop_back_val();
2680 }
2681
2682 return false;
2683}
2684
2685/// Check the validity of a C++ base class specifier.
2686///
2687/// \returns a new CXXBaseSpecifier if well-formed, emits diagnostics
2688/// and returns NULL otherwise.
2691 SourceRange SpecifierRange,
2692 bool Virtual, AccessSpecifier Access,
2693 TypeSourceInfo *TInfo,
2694 SourceLocation EllipsisLoc) {
2695 // In HLSL, unspecified class access is public rather than private.
2696 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2697 Access == AS_none)
2698 Access = AS_public;
2699
2700 QualType BaseType = TInfo->getType();
2701 if (BaseType->containsErrors()) {
2702 // Already emitted a diagnostic when parsing the error type.
2703 return nullptr;
2704 }
2705 // C++ [class.union]p1:
2706 // A union shall not have base classes.
2707 if (Class->isUnion()) {
2708 Diag(Class->getLocation(), diag::err_base_clause_on_union)
2709 << SpecifierRange;
2710 return nullptr;
2711 }
2712
2713 if (EllipsisLoc.isValid() &&
2715 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
2716 << TInfo->getTypeLoc().getSourceRange();
2717 EllipsisLoc = SourceLocation();
2718 }
2719
2720 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2721
2722 if (BaseType->isDependentType()) {
2723 // Make sure that we don't have circular inheritance among our dependent
2724 // bases. For non-dependent bases, the check for completeness below handles
2725 // this.
2726 if (CXXRecordDecl *BaseDecl = BaseType->getAsCXXRecordDecl()) {
2727 if (BaseDecl->getCanonicalDecl() == Class->getCanonicalDecl() ||
2728 ((BaseDecl = BaseDecl->getDefinition()) &&
2729 findCircularInheritance(Class, BaseDecl))) {
2730 Diag(BaseLoc, diag::err_circular_inheritance)
2731 << BaseType << Context.getTypeDeclType(Class);
2732
2733 if (BaseDecl->getCanonicalDecl() != Class->getCanonicalDecl())
2734 Diag(BaseDecl->getLocation(), diag::note_previous_decl)
2735 << BaseType;
2736
2737 return nullptr;
2738 }
2739 }
2740
2741 // Make sure that we don't make an ill-formed AST where the type of the
2742 // Class is non-dependent and its attached base class specifier is an
2743 // dependent type, which violates invariants in many clang code paths (e.g.
2744 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2745 // explicitly mark the Class decl invalid. The diagnostic was already
2746 // emitted.
2747 if (!Class->getTypeForDecl()->isDependentType())
2748 Class->setInvalidDecl();
2749 return new (Context) CXXBaseSpecifier(
2750 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2751 Access, TInfo, EllipsisLoc);
2752 }
2753
2754 // Base specifiers must be record types.
2755 if (!BaseType->isRecordType()) {
2756 Diag(BaseLoc, diag::err_base_must_be_class) << SpecifierRange;
2757 return nullptr;
2758 }
2759
2760 // C++ [class.union]p1:
2761 // A union shall not be used as a base class.
2762 if (BaseType->isUnionType()) {
2763 Diag(BaseLoc, diag::err_union_as_base_class) << SpecifierRange;
2764 return nullptr;
2765 }
2766
2767 // For the MS ABI, propagate DLL attributes to base class templates.
2769 Context.getTargetInfo().getTriple().isPS()) {
2770 if (Attr *ClassAttr = getDLLAttr(Class)) {
2771 if (auto *BaseTemplate = dyn_cast_or_null<ClassTemplateSpecializationDecl>(
2772 BaseType->getAsCXXRecordDecl())) {
2773 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplate,
2774 BaseLoc);
2775 }
2776 }
2777 }
2778
2779 // C++ [class.derived]p2:
2780 // The class-name in a base-specifier shall not be an incompletely
2781 // defined class.
2782 if (RequireCompleteType(BaseLoc, BaseType,
2783 diag::err_incomplete_base_class, SpecifierRange)) {
2784 Class->setInvalidDecl();
2785 return nullptr;
2786 }
2787
2788 // If the base class is polymorphic or isn't empty, the new one is/isn't, too.
2789 RecordDecl *BaseDecl = BaseType->castAs<RecordType>()->getDecl();
2790 assert(BaseDecl && "Record type has no declaration");
2791 BaseDecl = BaseDecl->getDefinition();
2792 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2793 CXXRecordDecl *CXXBaseDecl = cast<CXXRecordDecl>(BaseDecl);
2794 assert(CXXBaseDecl && "Base type is not a C++ type");
2795
2796 // Microsoft docs say:
2797 // "If a base-class has a code_seg attribute, derived classes must have the
2798 // same attribute."
2799 const auto *BaseCSA = CXXBaseDecl->getAttr<CodeSegAttr>();
2800 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2801 if ((DerivedCSA || BaseCSA) &&
2802 (!BaseCSA || !DerivedCSA || BaseCSA->getName() != DerivedCSA->getName())) {
2803 Diag(Class->getLocation(), diag::err_mismatched_code_seg_base);
2804 Diag(CXXBaseDecl->getLocation(), diag::note_base_class_specified_here)
2805 << CXXBaseDecl;
2806 return nullptr;
2807 }
2808
2809 // A class which contains a flexible array member is not suitable for use as a
2810 // base class:
2811 // - If the layout determines that a base comes before another base,
2812 // the flexible array member would index into the subsequent base.
2813 // - If the layout determines that base comes before the derived class,
2814 // the flexible array member would index into the derived class.
2815 if (CXXBaseDecl->hasFlexibleArrayMember()) {
2816 Diag(BaseLoc, diag::err_base_class_has_flexible_array_member)
2817 << CXXBaseDecl->getDeclName();
2818 return nullptr;
2819 }
2820
2821 // C++ [class]p3:
2822 // If a class is marked final and it appears as a base-type-specifier in
2823 // base-clause, the program is ill-formed.
2824 if (FinalAttr *FA = CXXBaseDecl->getAttr<FinalAttr>()) {
2825 Diag(BaseLoc, diag::err_class_marked_final_used_as_base)
2826 << CXXBaseDecl->getDeclName()
2827 << FA->isSpelledAsSealed();
2828 Diag(CXXBaseDecl->getLocation(), diag::note_entity_declared_at)
2829 << CXXBaseDecl->getDeclName() << FA->getRange();
2830 return nullptr;
2831 }
2832
2833 if (BaseDecl->isInvalidDecl())
2834 Class->setInvalidDecl();
2835
2836 // Create the base specifier.
2837 return new (Context) CXXBaseSpecifier(
2838 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2839 Access, TInfo, EllipsisLoc);
2840}
2841
2842/// ActOnBaseSpecifier - Parsed a base specifier. A base specifier is
2843/// one entry in the base class list of a class specifier, for
2844/// example:
2845/// class foo : public bar, virtual private baz {
2846/// 'public bar' and 'virtual private baz' are each base-specifiers.
2848 const ParsedAttributesView &Attributes,
2849 bool Virtual, AccessSpecifier Access,
2850 ParsedType basetype, SourceLocation BaseLoc,
2851 SourceLocation EllipsisLoc) {
2852 if (!classdecl)
2853 return true;
2854
2855 AdjustDeclIfTemplate(classdecl);
2856 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(classdecl);
2857 if (!Class)
2858 return true;
2859
2860 // We haven't yet attached the base specifiers.
2861 Class->setIsParsingBaseSpecifiers();
2862
2863 // We do not support any C++11 attributes on base-specifiers yet.
2864 // Diagnose any attributes we see.
2865 for (const ParsedAttr &AL : Attributes) {
2866 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2867 continue;
2868 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2869 Diag(AL.getLoc(), diag::warn_unknown_attribute_ignored)
2870 << AL << AL.getRange();
2871 else
2872 Diag(AL.getLoc(), diag::err_base_specifier_attribute)
2873 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2874 }
2875
2876 TypeSourceInfo *TInfo = nullptr;
2877 GetTypeFromParser(basetype, &TInfo);
2878
2879 if (EllipsisLoc.isInvalid() &&
2880 DiagnoseUnexpandedParameterPack(SpecifierRange.getBegin(), TInfo,
2882 return true;
2883
2884 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2885 Virtual, Access, TInfo,
2886 EllipsisLoc))
2887 return BaseSpec;
2888 else
2889 Class->setInvalidDecl();
2890
2891 return true;
2892}
2893
2894/// Use small set to collect indirect bases. As this is only used
2895/// locally, there's no need to abstract the small size parameter.
2897
2898/// Recursively add the bases of Type. Don't add Type itself.
2899static void
2901 const QualType &Type)
2902{
2903 // Even though the incoming type is a base, it might not be
2904 // a class -- it could be a template parm, for instance.
2905 if (auto Rec = Type->getAs<RecordType>()) {
2906 auto Decl = Rec->getAsCXXRecordDecl();
2907
2908 // Iterate over its bases.
2909 for (const auto &BaseSpec : Decl->bases()) {
2910 QualType Base = Context.getCanonicalType(BaseSpec.getType())
2912 if (Set.insert(Base).second)
2913 // If we've not already seen it, recurse.
2915 }
2916 }
2917}
2918
2919/// Performs the actual work of attaching the given base class
2920/// specifiers to a C++ class.
2923 if (Bases.empty())
2924 return false;
2925
2926 // Used to keep track of which base types we have already seen, so
2927 // that we can properly diagnose redundant direct base types. Note
2928 // that the key is always the unqualified canonical type of the base
2929 // class.
2930 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2931
2932 // Used to track indirect bases so we can see if a direct base is
2933 // ambiguous.
2934 IndirectBaseSet IndirectBaseTypes;
2935
2936 // Copy non-redundant base specifiers into permanent storage.
2937 unsigned NumGoodBases = 0;
2938 bool Invalid = false;
2939 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2940 QualType NewBaseType
2941 = Context.getCanonicalType(Bases[idx]->getType());
2942 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2943
2944 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2945 if (KnownBase) {
2946 // C++ [class.mi]p3:
2947 // A class shall not be specified as a direct base class of a
2948 // derived class more than once.
2949 Diag(Bases[idx]->getBeginLoc(), diag::err_duplicate_base_class)
2950 << KnownBase->getType() << Bases[idx]->getSourceRange();
2951
2952 // Delete the duplicate base class specifier; we're going to
2953 // overwrite its pointer later.
2954 Context.Deallocate(Bases[idx]);
2955
2956 Invalid = true;
2957 } else {
2958 // Okay, add this new base class.
2959 KnownBase = Bases[idx];
2960 Bases[NumGoodBases++] = Bases[idx];
2961
2962 if (NewBaseType->isDependentType())
2963 continue;
2964 // Note this base's direct & indirect bases, if there could be ambiguity.
2965 if (Bases.size() > 1)
2966 NoteIndirectBases(Context, IndirectBaseTypes, NewBaseType);
2967
2968 if (const RecordType *Record = NewBaseType->getAs<RecordType>()) {
2969 const CXXRecordDecl *RD = cast<CXXRecordDecl>(Record->getDecl());
2970 if (Class->isInterface() &&
2971 (!RD->isInterfaceLike() ||
2972 KnownBase->getAccessSpecifier() != AS_public)) {
2973 // The Microsoft extension __interface does not permit bases that
2974 // are not themselves public interfaces.
2975 Diag(KnownBase->getBeginLoc(), diag::err_invalid_base_in_interface)
2976 << getRecordDiagFromTagKind(RD->getTagKind()) << RD
2977 << RD->getSourceRange();
2978 Invalid = true;
2979 }
2980 if (RD->hasAttr<WeakAttr>())
2981 Class->addAttr(WeakAttr::CreateImplicit(Context));
2982 }
2983 }
2984 }
2985
2986 // Attach the remaining base class specifiers to the derived class.
2987 Class->setBases(Bases.data(), NumGoodBases);
2988
2989 // Check that the only base classes that are duplicate are virtual.
2990 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
2991 // Check whether this direct base is inaccessible due to ambiguity.
2992 QualType BaseType = Bases[idx]->getType();
2993
2994 // Skip all dependent types in templates being used as base specifiers.
2995 // Checks below assume that the base specifier is a CXXRecord.
2996 if (BaseType->isDependentType())
2997 continue;
2998
2999 CanQualType CanonicalBase = Context.getCanonicalType(BaseType)
3001
3002 if (IndirectBaseTypes.count(CanonicalBase)) {
3003 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3004 /*DetectVirtual=*/true);
3005 bool found
3006 = Class->isDerivedFrom(CanonicalBase->getAsCXXRecordDecl(), Paths);
3007 assert(found);
3008 (void)found;
3009
3010 if (Paths.isAmbiguous(CanonicalBase))
3011 Diag(Bases[idx]->getBeginLoc(), diag::warn_inaccessible_base_class)
3012 << BaseType << getAmbiguousPathsDisplayString(Paths)
3013 << Bases[idx]->getSourceRange();
3014 else
3015 assert(Bases[idx]->isVirtual());
3016 }
3017
3018 // Delete the base class specifier, since its data has been copied
3019 // into the CXXRecordDecl.
3020 Context.Deallocate(Bases[idx]);
3021 }
3022
3023 return Invalid;
3024}
3025
3026/// ActOnBaseSpecifiers - Attach the given base specifiers to the
3027/// class, after checking whether there are any duplicate base
3028/// classes.
3031 if (!ClassDecl || Bases.empty())
3032 return;
3033
3034 AdjustDeclIfTemplate(ClassDecl);
3035 AttachBaseSpecifiers(cast<CXXRecordDecl>(ClassDecl), Bases);
3036}
3037
3038/// Determine whether the type \p Derived is a C++ class that is
3039/// derived from the type \p Base.
3041 if (!getLangOpts().CPlusPlus)
3042 return false;
3043
3044 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3045 if (!DerivedRD)
3046 return false;
3047
3048 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3049 if (!BaseRD)
3050 return false;
3051
3052 // If either the base or the derived type is invalid, don't try to
3053 // check whether one is derived from the other.
3054 if (BaseRD->isInvalidDecl() || DerivedRD->isInvalidDecl())
3055 return false;
3056
3057 // FIXME: In a modules build, do we need the entire path to be visible for us
3058 // to be able to use the inheritance relationship?
3059 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3060 return false;
3061
3062 return DerivedRD->isDerivedFrom(BaseRD);
3063}
3064
3065/// Determine whether the type \p Derived is a C++ class that is
3066/// derived from the type \p Base.
3068 CXXBasePaths &Paths) {
3069 if (!getLangOpts().CPlusPlus)
3070 return false;
3071
3072 CXXRecordDecl *DerivedRD = Derived->getAsCXXRecordDecl();
3073 if (!DerivedRD)
3074 return false;
3075
3076 CXXRecordDecl *BaseRD = Base->getAsCXXRecordDecl();
3077 if (!BaseRD)
3078 return false;
3079
3080 if (!isCompleteType(Loc, Derived) && !DerivedRD->isBeingDefined())
3081 return false;
3082
3083 return DerivedRD->isDerivedFrom(BaseRD, Paths);
3084}
3085
3086static void BuildBasePathArray(const CXXBasePath &Path,
3087 CXXCastPath &BasePathArray) {
3088 // We first go backward and check if we have a virtual base.
3089 // FIXME: It would be better if CXXBasePath had the base specifier for
3090 // the nearest virtual base.
3091 unsigned Start = 0;
3092 for (unsigned I = Path.size(); I != 0; --I) {
3093 if (Path[I - 1].Base->isVirtual()) {
3094 Start = I - 1;
3095 break;
3096 }
3097 }
3098
3099 // Now add all bases.
3100 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3101 BasePathArray.push_back(const_cast<CXXBaseSpecifier*>(Path[I].Base));
3102}
3103
3104
3106 CXXCastPath &BasePathArray) {
3107 assert(BasePathArray.empty() && "Base path array must be empty!");
3108 assert(Paths.isRecordingPaths() && "Must record paths!");
3109 return ::BuildBasePathArray(Paths.front(), BasePathArray);
3110}
3111/// CheckDerivedToBaseConversion - Check whether the Derived-to-Base
3112/// conversion (where Derived and Base are class types) is
3113/// well-formed, meaning that the conversion is unambiguous (and
3114/// that all of the base classes are accessible). Returns true
3115/// and emits a diagnostic if the code is ill-formed, returns false
3116/// otherwise. Loc is the location where this routine should point to
3117/// if there is an error, and Range is the source range to highlight
3118/// if there is an error.
3119///
3120/// If either InaccessibleBaseID or AmbiguousBaseConvID are 0, then the
3121/// diagnostic for the respective type of error will be suppressed, but the
3122/// check for ill-formed code will still be performed.
3123bool
3125 unsigned InaccessibleBaseID,
3126 unsigned AmbiguousBaseConvID,
3127 SourceLocation Loc, SourceRange Range,
3128 DeclarationName Name,
3129 CXXCastPath *BasePath,
3130 bool IgnoreAccess) {
3131 // First, determine whether the path from Derived to Base is
3132 // ambiguous. This is slightly more expensive than checking whether
3133 // the Derived to Base conversion exists, because here we need to
3134 // explore multiple paths to determine if there is an ambiguity.
3135 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3136 /*DetectVirtual=*/false);
3137 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3138 if (!DerivationOkay)
3139 return true;
3140
3141 const CXXBasePath *Path = nullptr;
3142 if (!Paths.isAmbiguous(Context.getCanonicalType(Base).getUnqualifiedType()))
3143 Path = &Paths.front();
3144
3145 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3146 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3147 // user to access such bases.
3148 if (!Path && getLangOpts().MSVCCompat) {
3149 for (const CXXBasePath &PossiblePath : Paths) {
3150 if (PossiblePath.size() == 1) {
3151 Path = &PossiblePath;
3152 if (AmbiguousBaseConvID)
3153 Diag(Loc, diag::ext_ms_ambiguous_direct_base)
3154 << Base << Derived << Range;
3155 break;
3156 }
3157 }
3158 }
3159
3160 if (Path) {
3161 if (!IgnoreAccess) {
3162 // Check that the base class can be accessed.
3163 switch (
3164 CheckBaseClassAccess(Loc, Base, Derived, *Path, InaccessibleBaseID)) {
3165 case AR_inaccessible:
3166 return true;
3167 case AR_accessible:
3168 case AR_dependent:
3169 case AR_delayed:
3170 break;
3171 }
3172 }
3173
3174 // Build a base path if necessary.
3175 if (BasePath)
3176 ::BuildBasePathArray(*Path, *BasePath);
3177 return false;
3178 }
3179
3180 if (AmbiguousBaseConvID) {
3181 // We know that the derived-to-base conversion is ambiguous, and
3182 // we're going to produce a diagnostic. Perform the derived-to-base
3183 // search just one more time to compute all of the possible paths so
3184 // that we can print them out. This is more expensive than any of
3185 // the previous derived-to-base checks we've done, but at this point
3186 // performance isn't as much of an issue.
3187 Paths.clear();
3188 Paths.setRecordingPaths(true);
3189 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3190 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3191 (void)StillOkay;
3192
3193 // Build up a textual representation of the ambiguous paths, e.g.,
3194 // D -> B -> A, that will be used to illustrate the ambiguous
3195 // conversions in the diagnostic. We only print one of the paths
3196 // to each base class subobject.
3197 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3198
3199 Diag(Loc, AmbiguousBaseConvID)
3200 << Derived << Base << PathDisplayStr << Range << Name;
3201 }
3202 return true;
3203}
3204
3205bool
3207 SourceLocation Loc, SourceRange Range,
3208 CXXCastPath *BasePath,
3209 bool IgnoreAccess) {
3211 Derived, Base, diag::err_upcast_to_inaccessible_base,
3212 diag::err_ambiguous_derived_to_base_conv, Loc, Range, DeclarationName(),
3213 BasePath, IgnoreAccess);
3214}
3215
3216
3217/// Builds a string representing ambiguous paths from a
3218/// specific derived class to different subobjects of the same base
3219/// class.
3220///
3221/// This function builds a string that can be used in error messages
3222/// to show the different paths that one can take through the
3223/// inheritance hierarchy to go from the derived class to different
3224/// subobjects of a base class. The result looks something like this:
3225/// @code
3226/// struct D -> struct B -> struct A
3227/// struct D -> struct C -> struct A
3228/// @endcode
3230 std::string PathDisplayStr;
3231 std::set<unsigned> DisplayedPaths;
3232 for (CXXBasePaths::paths_iterator Path = Paths.begin();
3233 Path != Paths.end(); ++Path) {
3234 if (DisplayedPaths.insert(Path->back().SubobjectNumber).second) {
3235 // We haven't displayed a path to this particular base
3236 // class subobject yet.
3237 PathDisplayStr += "\n ";
3238 PathDisplayStr += Context.getTypeDeclType(Paths.getOrigin()).getAsString();
3239 for (CXXBasePath::const_iterator Element = Path->begin();
3240 Element != Path->end(); ++Element)
3241 PathDisplayStr += " -> " + Element->Base->getType().getAsString();
3242 }
3243 }
3244
3245 return PathDisplayStr;
3246}
3247
3248//===----------------------------------------------------------------------===//
3249// C++ class member Handling
3250//===----------------------------------------------------------------------===//
3251
3252/// ActOnAccessSpecifier - Parsed an access specifier followed by a colon.
3254 SourceLocation ColonLoc,
3255 const ParsedAttributesView &Attrs) {
3256 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3258 ASLoc, ColonLoc);
3259 CurContext->addHiddenDecl(ASDecl);
3260 return ProcessAccessDeclAttributeList(ASDecl, Attrs);
3261}
3262
3263/// CheckOverrideControl - Check C++11 override control semantics.
3265 if (D->isInvalidDecl())
3266 return;
3267
3268 // We only care about "override" and "final" declarations.
3269 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3270 return;
3271
3272 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3273
3274 // We can't check dependent instance methods.
3275 if (MD && MD->isInstance() &&
3276 (MD->getParent()->hasAnyDependentBases() ||
3277 MD->getType()->isDependentType()))
3278 return;
3279
3280 if (MD && !MD->isVirtual()) {
3281 // If we have a non-virtual method, check if it hides a virtual method.
3282 // (In that case, it's most likely the method has the wrong type.)
3283 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3284 FindHiddenVirtualMethods(MD, OverloadedMethods);
3285
3286 if (!OverloadedMethods.empty()) {
3287 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3288 Diag(OA->getLocation(),
3289 diag::override_keyword_hides_virtual_member_function)
3290 << "override" << (OverloadedMethods.size() > 1);
3291 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3292 Diag(FA->getLocation(),
3293 diag::override_keyword_hides_virtual_member_function)
3294 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3295 << (OverloadedMethods.size() > 1);
3296 }
3297 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3298 MD->setInvalidDecl();
3299 return;
3300 }
3301 // Fall through into the general case diagnostic.
3302 // FIXME: We might want to attempt typo correction here.
3303 }
3304
3305 if (!MD || !MD->isVirtual()) {
3306 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3307 Diag(OA->getLocation(),
3308 diag::override_keyword_only_allowed_on_virtual_member_functions)
3309 << "override" << FixItHint::CreateRemoval(OA->getLocation());
3310 D->dropAttr<OverrideAttr>();
3311 }
3312 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3313 Diag(FA->getLocation(),
3314 diag::override_keyword_only_allowed_on_virtual_member_functions)
3315 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3316 << FixItHint::CreateRemoval(FA->getLocation());
3317 D->dropAttr<FinalAttr>();
3318 }
3319 return;
3320 }
3321
3322 // C++11 [class.virtual]p5:
3323 // If a function is marked with the virt-specifier override and
3324 // does not override a member function of a base class, the program is
3325 // ill-formed.
3326 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3327 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3328 Diag(MD->getLocation(), diag::err_function_marked_override_not_overriding)
3329 << MD->getDeclName();
3330}
3331
3333 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3334 return;
3335 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D);
3336 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3337 return;
3338
3339 SourceLocation Loc = MD->getLocation();
3340 SourceLocation SpellingLoc = Loc;
3341 if (getSourceManager().isMacroArgExpansion(Loc))
3343 SpellingLoc = getSourceManager().getSpellingLoc(SpellingLoc);
3344 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(SpellingLoc))
3345 return;
3346
3347 if (MD->size_overridden_methods() > 0) {
3348 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3349 unsigned DiagID =
3350 Inconsistent && !Diags.isIgnored(DiagInconsistent, MD->getLocation())
3351 ? DiagInconsistent
3352 : DiagSuggest;
3353 Diag(MD->getLocation(), DiagID) << MD->getDeclName();
3354 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3355 Diag(OMD->getLocation(), diag::note_overridden_virtual_function);
3356 };
3357 if (isa<CXXDestructorDecl>(MD))
3358 EmitDiag(
3359 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3360 diag::warn_suggest_destructor_marked_not_override_overriding);
3361 else
3362 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3363 diag::warn_suggest_function_marked_not_override_overriding);
3364 }
3365}
3366
3367/// CheckIfOverriddenFunctionIsMarkedFinal - Checks whether a virtual member
3368/// function overrides a virtual member function marked 'final', according to
3369/// C++11 [class.virtual]p4.
3371 const CXXMethodDecl *Old) {
3372 FinalAttr *FA = Old->getAttr<FinalAttr>();
3373 if (!FA)
3374 return false;
3375
3376 Diag(New->getLocation(), diag::err_final_function_overridden)
3377 << New->getDeclName()
3378 << FA->isSpelledAsSealed();
3379 Diag(Old->getLocation(), diag::note_overridden_virtual_function);
3380 return true;
3381}
3382
3384 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3385 // FIXME: Destruction of ObjC lifetime types has side-effects.
3386 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3387 return !RD->isCompleteDefinition() ||
3388 !RD->hasTrivialDefaultConstructor() ||
3389 !RD->hasTrivialDestructor();
3390 return false;
3391}
3392
3393// Check if there is a field shadowing.
3394void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3395 DeclarationName FieldName,
3396 const CXXRecordDecl *RD,
3397 bool DeclIsField) {
3398 if (Diags.isIgnored(diag::warn_shadow_field, Loc))
3399 return;
3400
3401 // To record a shadowed field in a base
3402 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3403 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3404 CXXBasePath &Path) {
3405 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3406 // Record an ambiguous path directly
3407 if (Bases.find(Base) != Bases.end())
3408 return true;
3409 for (const auto Field : Base->lookup(FieldName)) {
3410 if ((isa<FieldDecl>(Field) || isa<IndirectFieldDecl>(Field)) &&
3411 Field->getAccess() != AS_private) {
3412 assert(Field->getAccess() != AS_none);
3413 assert(Bases.find(Base) == Bases.end());
3414 Bases[Base] = Field;
3415 return true;
3416 }
3417 }
3418 return false;
3419 };
3420
3421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3422 /*DetectVirtual=*/true);
3423 if (!RD->lookupInBases(FieldShadowed, Paths))
3424 return;
3425
3426 for (const auto &P : Paths) {
3427 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3428 auto It = Bases.find(Base);
3429 // Skip duplicated bases
3430 if (It == Bases.end())
3431 continue;
3432 auto BaseField = It->second;
3433 assert(BaseField->getAccess() != AS_private);
3434 if (AS_none !=
3435 CXXRecordDecl::MergeAccess(P.Access, BaseField->getAccess())) {
3436 Diag(Loc, diag::warn_shadow_field)
3437 << FieldName << RD << Base << DeclIsField;
3438 Diag(BaseField->getLocation(), diag::note_shadow_field);
3439 Bases.erase(It);
3440 }
3441 }
3442}
3443
3444/// ActOnCXXMemberDeclarator - This is invoked when a C++ class member
3445/// declarator is parsed. 'AS' is the access specifier, 'BW' specifies the
3446/// bitfield width if there is one, 'InitExpr' specifies the initializer if
3447/// one has been parsed, and 'InitStyle' is set if an in-class initializer is
3448/// present (but parsing it has been deferred).
3449NamedDecl *
3451 MultiTemplateParamsArg TemplateParameterLists,
3452 Expr *BW, const VirtSpecifiers &VS,
3453 InClassInitStyle InitStyle) {
3454 const DeclSpec &DS = D.getDeclSpec();
3456 DeclarationName Name = NameInfo.getName();
3457 SourceLocation Loc = NameInfo.getLoc();
3458
3459 // For anonymous bitfields, the location should point to the type.
3460 if (Loc.isInvalid())
3461 Loc = D.getBeginLoc();
3462
3463 Expr *BitWidth = static_cast<Expr*>(BW);
3464
3465 assert(isa<CXXRecordDecl>(CurContext));
3466 assert(!DS.isFriendSpecified());
3467
3468 bool isFunc = D.isDeclarationOfFunction();
3469 const ParsedAttr *MSPropertyAttr =
3471
3472 if (cast<CXXRecordDecl>(CurContext)->isInterface()) {
3473 // The Microsoft extension __interface only permits public member functions
3474 // and prohibits constructors, destructors, operators, non-public member
3475 // functions, static methods and data members.
3476 unsigned InvalidDecl;
3477 bool ShowDeclName = true;
3478 if (!isFunc &&
3479 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3480 InvalidDecl = 0;
3481 else if (!isFunc)
3482 InvalidDecl = 1;
3483 else if (AS != AS_public)
3484 InvalidDecl = 2;
3486 InvalidDecl = 3;
3487 else switch (Name.getNameKind()) {
3489 InvalidDecl = 4;
3490 ShowDeclName = false;
3491 break;
3492
3494 InvalidDecl = 5;
3495 ShowDeclName = false;
3496 break;
3497
3500 InvalidDecl = 6;
3501 break;
3502
3503 default:
3504 InvalidDecl = 0;
3505 break;
3506 }
3507
3508 if (InvalidDecl) {
3509 if (ShowDeclName)
3510 Diag(Loc, diag::err_invalid_member_in_interface)
3511 << (InvalidDecl-1) << Name;
3512 else
3513 Diag(Loc, diag::err_invalid_member_in_interface)
3514 << (InvalidDecl-1) << "";
3515 return nullptr;
3516 }
3517 }
3518
3519 // C++ 9.2p6: A member shall not be declared to have automatic storage
3520 // duration (auto, register) or with the extern storage-class-specifier.
3521 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3522 // data members and cannot be applied to names declared const or static,
3523 // and cannot be applied to reference members.
3524 switch (DS.getStorageClassSpec()) {
3528 break;
3530 if (isFunc) {
3531 Diag(DS.getStorageClassSpecLoc(), diag::err_mutable_function);
3532
3533 // FIXME: It would be nicer if the keyword was ignored only for this
3534 // declarator. Otherwise we could get follow-up errors.
3536 }
3537 break;
3538 default:
3540 diag::err_storageclass_invalid_for_member);
3542 break;
3543 }
3544
3545 bool isInstField = ((DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3547 !isFunc);
3548
3549 if (DS.hasConstexprSpecifier() && isInstField) {
3551 Diag(DS.getConstexprSpecLoc(), diag::err_invalid_constexpr_member);
3552 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3553 if (InitStyle == ICIS_NoInit) {
3554 B << 0 << 0;
3556 B << FixItHint::CreateRemoval(ConstexprLoc);
3557 else {
3558 B << FixItHint::CreateReplacement(ConstexprLoc, "const");
3560 const char *PrevSpec;
3561 unsigned DiagID;
3562 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3563 DeclSpec::TQ_const, ConstexprLoc, PrevSpec, DiagID, getLangOpts());
3564 (void)Failed;
3565 assert(!Failed && "Making a constexpr member const shouldn't fail");
3566 }
3567 } else {
3568 B << 1;
3569 const char *PrevSpec;
3570 unsigned DiagID;
3572 *this, DeclSpec::SCS_static, ConstexprLoc, PrevSpec, DiagID,
3575 "This is the only DeclSpec that should fail to be applied");
3576 B << 1;
3577 } else {
3578 B << 0 << FixItHint::CreateInsertion(ConstexprLoc, "static ");
3579 isInstField = false;
3580 }
3581 }
3582 }
3583
3585 if (isInstField) {
3586 CXXScopeSpec &SS = D.getCXXScopeSpec();
3587
3588 // Data members must have identifiers for names.
3589 if (!Name.isIdentifier()) {
3590 Diag(Loc, diag::err_bad_variable_name)
3591 << Name;
3592 return nullptr;
3593 }
3594
3595 IdentifierInfo *II = Name.getAsIdentifierInfo();
3596
3597 // Member field could not be with "template" keyword.
3598 // So TemplateParameterLists should be empty in this case.
3599 if (TemplateParameterLists.size()) {
3600 TemplateParameterList* TemplateParams = TemplateParameterLists[0];
3601 if (TemplateParams->size()) {
3602 // There is no such thing as a member field template.
3603 Diag(D.getIdentifierLoc(), diag::err_template_member)
3604 << II
3605 << SourceRange(TemplateParams->getTemplateLoc(),
3606 TemplateParams->getRAngleLoc());
3607 } else {
3608 // There is an extraneous 'template<>' for this member.
3609 Diag(TemplateParams->getTemplateLoc(),
3610 diag::err_template_member_noparams)
3611 << II
3612 << SourceRange(TemplateParams->getTemplateLoc(),
3613 TemplateParams->getRAngleLoc());
3614 }
3615 return nullptr;
3616 }
3617
3619 Diag(D.getIdentifierLoc(), diag::err_member_with_template_arguments)
3620 << II
3624 D.SetIdentifier(II, Loc);
3625 }
3626
3627 if (SS.isSet() && !SS.isInvalid()) {
3628 // The user provided a superfluous scope specifier inside a class
3629 // definition:
3630 //
3631 // class X {
3632 // int X::member;
3633 // };
3634 if (DeclContext *DC = computeDeclContext(SS, false)) {
3635 TemplateIdAnnotation *TemplateId =
3637 ? D.getName().TemplateId
3638 : nullptr;
3640 TemplateId,
3641 /*IsMemberSpecialization=*/false);
3642 } else {
3643 Diag(D.getIdentifierLoc(), diag::err_member_qualification)
3644 << Name << SS.getRange();
3645 }
3646 SS.clear();
3647 }
3648
3649 if (MSPropertyAttr) {
3650 Member = HandleMSProperty(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3651 BitWidth, InitStyle, AS, *MSPropertyAttr);
3652 if (!Member)
3653 return nullptr;
3654 isInstField = false;
3655 } else {
3656 Member = HandleField(S, cast<CXXRecordDecl>(CurContext), Loc, D,
3657 BitWidth, InitStyle, AS);
3658 if (!Member)
3659 return nullptr;
3660 }
3661
3662 CheckShadowInheritedFields(Loc, Name, cast<CXXRecordDecl>(CurContext));
3663 } else {
3664 Member = HandleDeclarator(S, D, TemplateParameterLists);
3665 if (!Member)
3666 return nullptr;
3667
3668 // Non-instance-fields can't have a bitfield.
3669 if (BitWidth) {
3670 if (Member->isInvalidDecl()) {
3671 // don't emit another diagnostic.
3672 } else if (isa<VarDecl>(Member) || isa<VarTemplateDecl>(Member)) {
3673 // C++ 9.6p3: A bit-field shall not be a static member.
3674 // "static member 'A' cannot be a bit-field"
3675 Diag(Loc, diag::err_static_not_bitfield)
3676 << Name << BitWidth->getSourceRange();
3677 } else if (isa<TypedefDecl>(Member)) {
3678 // "typedef member 'x' cannot be a bit-field"
3679 Diag(Loc, diag::err_typedef_not_bitfield)
3680 << Name << BitWidth->getSourceRange();
3681 } else {
3682 // A function typedef ("typedef int f(); f a;").
3683 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3684 Diag(Loc, diag::err_not_integral_type_bitfield)
3685 << Name << cast<ValueDecl>(Member)->getType()
3686 << BitWidth->getSourceRange();
3687 }
3688
3689 BitWidth = nullptr;
3690 Member->setInvalidDecl();
3691 }
3692
3693 NamedDecl *NonTemplateMember = Member;
3694 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Member))
3695 NonTemplateMember = FunTmpl->getTemplatedDecl();
3696 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Member))
3697 NonTemplateMember = VarTmpl->getTemplatedDecl();
3698
3699 Member->setAccess(AS);
3700
3701 // If we have declared a member function template or static data member
3702 // template, set the access of the templated declaration as well.
3703 if (NonTemplateMember != Member)
3704 NonTemplateMember->setAccess(AS);
3705
3706 // C++ [temp.deduct.guide]p3:
3707 // A deduction guide [...] for a member class template [shall be
3708 // declared] with the same access [as the template].
3709 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(NonTemplateMember)) {
3710 auto *TD = DG->getDeducedTemplate();
3711 // Access specifiers are only meaningful if both the template and the
3712 // deduction guide are from the same scope.
3713 if (AS != TD->getAccess() &&
3714 TD->getDeclContext()->getRedeclContext()->Equals(
3715 DG->getDeclContext()->getRedeclContext())) {
3716 Diag(DG->getBeginLoc(), diag::err_deduction_guide_wrong_access);
3717 Diag(TD->getBeginLoc(), diag::note_deduction_guide_template_access)
3718 << TD->getAccess();
3719 const AccessSpecDecl *LastAccessSpec = nullptr;
3720 for (const auto *D : cast<CXXRecordDecl>(CurContext)->decls()) {
3721 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(D))
3722 LastAccessSpec = AccessSpec;
3723 }
3724 assert(LastAccessSpec && "differing access with no access specifier");
3725 Diag(LastAccessSpec->getBeginLoc(), diag::note_deduction_guide_access)
3726 << AS;
3727 }
3728 }
3729 }
3730
3731 if (VS.isOverrideSpecified())
3732 Member->addAttr(OverrideAttr::Create(Context, VS.getOverrideLoc()));
3733 if (VS.isFinalSpecified())
3734 Member->addAttr(FinalAttr::Create(Context, VS.getFinalLoc(),
3736 ? FinalAttr::Keyword_sealed
3737 : FinalAttr::Keyword_final));
3738
3739 if (VS.getLastLocation().isValid()) {
3740 // Update the end location of a method that has a virt-specifiers.
3741 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Member))
3742 MD->setRangeEnd(VS.getLastLocation());
3743 }
3744
3746
3747 assert((Name || isInstField) && "No identifier for non-field ?");
3748
3749 if (isInstField) {
3750 FieldDecl *FD = cast<FieldDecl>(Member);
3751 FieldCollector->Add(FD);
3752
3753 if (!Diags.isIgnored(diag::warn_unused_private_field, FD->getLocation())) {
3754 // Remember all explicit private FieldDecls that have a name, no side
3755 // effects and are not part of a dependent type declaration.
3756
3757 auto DeclHasUnusedAttr = [](const QualType &T) {
3758 if (const TagDecl *TD = T->getAsTagDecl())
3759 return TD->hasAttr<UnusedAttr>();
3760 if (const TypedefType *TDT = T->getAs<TypedefType>())
3761 return TDT->getDecl()->hasAttr<UnusedAttr>();
3762 return false;
3763 };
3764
3765 if (!FD->isImplicit() && FD->getDeclName() &&
3766 FD->getAccess() == AS_private &&
3767 !FD->hasAttr<UnusedAttr>() &&
3768 !FD->getParent()->isDependentContext() &&
3769 !DeclHasUnusedAttr(FD->getType()) &&
3771 UnusedPrivateFields.insert(FD);
3772 }
3773 }
3774
3775 return Member;
3776}
3777
3778namespace {
3779 class UninitializedFieldVisitor
3780 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3781 Sema &S;
3782 // List of Decls to generate a warning on. Also remove Decls that become
3783 // initialized.
3784 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3785 // List of base classes of the record. Classes are removed after their
3786 // initializers.
3787 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3788 // Vector of decls to be removed from the Decl set prior to visiting the
3789 // nodes. These Decls may have been initialized in the prior initializer.
3791 // If non-null, add a note to the warning pointing back to the constructor.
3792 const CXXConstructorDecl *Constructor;
3793 // Variables to hold state when processing an initializer list. When
3794 // InitList is true, special case initialization of FieldDecls matching
3795 // InitListFieldDecl.
3796 bool InitList;
3797 FieldDecl *InitListFieldDecl;
3798 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3799
3800 public:
3802 UninitializedFieldVisitor(Sema &S,
3803 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3804 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3805 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3806 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3807
3808 // Returns true if the use of ME is not an uninitialized use.
3809 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3810 bool CheckReferenceOnly) {
3812 bool ReferenceField = false;
3813 while (ME) {
3814 FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
3815 if (!FD)
3816 return false;
3817 Fields.push_back(FD);
3818 if (FD->getType()->isReferenceType())
3819 ReferenceField = true;
3820 ME = dyn_cast<MemberExpr>(ME->getBase()->IgnoreParenImpCasts());
3821 }
3822
3823 // Binding a reference to an uninitialized field is not an
3824 // uninitialized use.
3825 if (CheckReferenceOnly && !ReferenceField)
3826 return true;
3827
3828 llvm::SmallVector<unsigned, 4> UsedFieldIndex;
3829 // Discard the first field since it is the field decl that is being
3830 // initialized.
3831 for (const FieldDecl *FD : llvm::drop_begin(llvm::reverse(Fields)))
3832 UsedFieldIndex.push_back(FD->getFieldIndex());
3833
3834 for (auto UsedIter = UsedFieldIndex.begin(),
3835 UsedEnd = UsedFieldIndex.end(),
3836 OrigIter = InitFieldIndex.begin(),
3837 OrigEnd = InitFieldIndex.end();
3838 UsedIter != UsedEnd && OrigIter != OrigEnd; ++UsedIter, ++OrigIter) {
3839 if (*UsedIter < *OrigIter)
3840 return true;
3841 if (*UsedIter > *OrigIter)
3842 break;
3843 }
3844
3845 return false;
3846 }
3847
3848 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3849 bool AddressOf) {
3850 if (isa<EnumConstantDecl>(ME->getMemberDecl()))
3851 return;
3852
3853 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3854 // or union.
3855 MemberExpr *FieldME = ME;
3856
3857 bool AllPODFields = FieldME->getType().isPODType(S.Context);
3858
3859 Expr *Base = ME;
3860 while (MemberExpr *SubME =
3861 dyn_cast<MemberExpr>(Base->IgnoreParenImpCasts())) {
3862
3863 if (isa<VarDecl>(SubME->getMemberDecl()))
3864 return;
3865
3866 if (FieldDecl *FD = dyn_cast<FieldDecl>(SubME->getMemberDecl()))
3867 if (!FD->isAnonymousStructOrUnion())
3868 FieldME = SubME;
3869
3870 if (!FieldME->getType().isPODType(S.Context))
3871 AllPODFields = false;
3872
3873 Base = SubME->getBase();
3874 }
3875
3876 if (!isa<CXXThisExpr>(Base->IgnoreParenImpCasts())) {
3877 Visit(Base);
3878 return;
3879 }
3880
3881 if (AddressOf && AllPODFields)
3882 return;
3883
3884 ValueDecl* FoundVD = FieldME->getMemberDecl();
3885
3886 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Base)) {
3887 while (isa<ImplicitCastExpr>(BaseCast->getSubExpr())) {
3888 BaseCast = cast<ImplicitCastExpr>(BaseCast->getSubExpr());
3889 }
3890
3891 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3892 QualType T = BaseCast->getType();
3893 if (T->isPointerType() &&
3894 BaseClasses.count(T->getPointeeType())) {
3895 S.Diag(FieldME->getExprLoc(), diag::warn_base_class_is_uninit)
3896 << T->getPointeeType() << FoundVD;
3897 }
3898 }
3899 }
3900
3901 if (!Decls.count(FoundVD))
3902 return;
3903
3904 const bool IsReference = FoundVD->getType()->isReferenceType();
3905
3906 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3907 // Special checking for initializer lists.
3908 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3909 return;
3910 }
3911 } else {
3912 // Prevent double warnings on use of unbounded references.
3913 if (CheckReferenceOnly && !IsReference)
3914 return;
3915 }
3916
3917 unsigned diag = IsReference
3918 ? diag::warn_reference_field_is_uninit
3919 : diag::warn_field_is_uninit;
3920 S.Diag(FieldME->getExprLoc(), diag) << FoundVD;
3921 if (Constructor)
3922 S.Diag(Constructor->getLocation(),
3923 diag::note_uninit_in_this_constructor)
3924 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3925
3926 }
3927
3928 void HandleValue(Expr *E, bool AddressOf) {
3929 E = E->IgnoreParens();
3930
3931 if (MemberExpr *ME = dyn_cast<MemberExpr>(E)) {
3932 HandleMemberExpr(ME, false /*CheckReferenceOnly*/,
3933 AddressOf /*AddressOf*/);
3934 return;
3935 }
3936
3937 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(E)) {
3938 Visit(CO->getCond());
3939 HandleValue(CO->getTrueExpr(), AddressOf);
3940 HandleValue(CO->getFalseExpr(), AddressOf);
3941 return;
3942 }
3943
3944 if (BinaryConditionalOperator *BCO =
3945 dyn_cast<BinaryConditionalOperator>(E)) {
3946 Visit(BCO->getCond());
3947 HandleValue(BCO->getFalseExpr(), AddressOf);
3948 return;
3949 }
3950
3951 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(E)) {
3952 HandleValue(OVE->getSourceExpr(), AddressOf);
3953 return;
3954 }
3955
3956 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(E)) {
3957 switch (BO->getOpcode()) {
3958 default:
3959 break;
3960 case(BO_PtrMemD):
3961 case(BO_PtrMemI):
3962 HandleValue(BO->getLHS(), AddressOf);
3963 Visit(BO->getRHS());
3964 return;
3965 case(BO_Comma):
3966 Visit(BO->getLHS());
3967 HandleValue(BO->getRHS(), AddressOf);
3968 return;
3969 }
3970 }
3971
3972 Visit(E);
3973 }
3974
3975 void CheckInitListExpr(InitListExpr *ILE) {
3976 InitFieldIndex.push_back(0);
3977 for (auto *Child : ILE->children()) {
3978 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Child)) {
3979 CheckInitListExpr(SubList);
3980 } else {
3981 Visit(Child);
3982 }
3983 ++InitFieldIndex.back();
3984 }
3985 InitFieldIndex.pop_back();
3986 }
3987
3988 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3989 FieldDecl *Field, const Type *BaseClass) {
3990 // Remove Decls that may have been initialized in the previous
3991 // initializer.
3992 for (ValueDecl* VD : DeclsToRemove)
3993 Decls.erase(VD);
3994 DeclsToRemove.clear();
3995
3996 Constructor = FieldConstructor;
3997 InitListExpr *ILE = dyn_cast<InitListExpr>(E);
3998
3999 if (ILE && Field) {
4000 InitList = true;
4001 InitListFieldDecl = Field;
4002 InitFieldIndex.clear();
4003 CheckInitListExpr(ILE);
4004 } else {
4005 InitList = false;
4006 Visit(E);
4007 }
4008
4009 if (Field)
4010 Decls.erase(Field);
4011 if (BaseClass)
4012 BaseClasses.erase(BaseClass->getCanonicalTypeInternal());
4013 }
4014
4015 void VisitMemberExpr(MemberExpr *ME) {
4016 // All uses of unbounded reference fields will warn.
4017 HandleMemberExpr(ME, true /*CheckReferenceOnly*/, false /*AddressOf*/);
4018 }
4019
4020 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4021 if (E->getCastKind() == CK_LValueToRValue) {
4022 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4023 return;
4024 }
4025
4026 Inherited::VisitImplicitCastExpr(E);
4027 }
4028
4029 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4030 if (E->getConstructor()->isCopyConstructor()) {
4031 Expr *ArgExpr = E->getArg(0);
4032 if (InitListExpr *ILE = dyn_cast<InitListExpr>(ArgExpr))
4033 if (ILE->getNumInits() == 1)
4034 ArgExpr = ILE->getInit(0);
4035 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(ArgExpr))
4036 if (ICE->getCastKind() == CK_NoOp)
4037 ArgExpr = ICE->getSubExpr();
4038 HandleValue(ArgExpr, false /*AddressOf*/);
4039 return;
4040 }
4041 Inherited::VisitCXXConstructExpr(E);
4042 }
4043
4044 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4045 Expr *Callee = E->getCallee();
4046 if (isa<MemberExpr>(Callee)) {
4047 HandleValue(Callee, false /*AddressOf*/);
4048 for (auto *Arg : E->arguments())
4049 Visit(Arg);
4050 return;
4051 }
4052
4053 Inherited::VisitCXXMemberCallExpr(E);
4054 }
4055
4056 void VisitCallExpr(CallExpr *E) {
4057 // Treat std::move as a use.
4058 if (E->isCallToStdMove()) {
4059 HandleValue(E->getArg(0), /*AddressOf=*/false);
4060 return;
4061 }
4062
4063 Inherited::VisitCallExpr(E);
4064 }
4065
4066 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4067 Expr *Callee = E->getCallee();
4068
4069 if (isa<UnresolvedLookupExpr>(Callee))
4070 return Inherited::VisitCXXOperatorCallExpr(E);
4071
4072 Visit(Callee);
4073 for (auto *Arg : E->arguments())
4074 HandleValue(Arg->IgnoreParenImpCasts(), false /*AddressOf*/);
4075 }
4076
4077 void VisitBinaryOperator(BinaryOperator *E) {
4078 // If a field assignment is detected, remove the field from the
4079 // uninitiailized field set.
4080 if (E->getOpcode() == BO_Assign)
4081 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getLHS()))
4082 if (FieldDecl *FD = dyn_cast<FieldDecl>(ME->getMemberDecl()))
4083 if (!FD->getType()->isReferenceType())
4084 DeclsToRemove.push_back(FD);
4085
4086 if (E->isCompoundAssignmentOp()) {
4087 HandleValue(E->getLHS(), false /*AddressOf*/);
4088 Visit(E->getRHS());
4089 return;
4090 }
4091
4092 Inherited::VisitBinaryOperator(E);
4093 }
4094
4095 void VisitUnaryOperator(UnaryOperator *E) {
4096 if (E->isIncrementDecrementOp()) {
4097 HandleValue(E->getSubExpr(), false /*AddressOf*/);
4098 return;
4099 }
4100 if (E->getOpcode() == UO_AddrOf) {
4101 if (MemberExpr *ME = dyn_cast<MemberExpr>(E->getSubExpr())) {
4102 HandleValue(ME->getBase(), true /*AddressOf*/);
4103 return;
4104 }
4105 }
4106
4107 Inherited::VisitUnaryOperator(E);
4108 }
4109 };
4110
4111 // Diagnose value-uses of fields to initialize themselves, e.g.
4112 // foo(foo)
4113 // where foo is not also a parameter to the constructor.
4114 // Also diagnose across field uninitialized use such as
4115 // x(y), y(x)
4116 // TODO: implement -Wuninitialized and fold this into that framework.
4117 static void DiagnoseUninitializedFields(
4118 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4119
4120 if (SemaRef.getDiagnostics().isIgnored(diag::warn_field_is_uninit,
4121 Constructor->getLocation())) {
4122 return;
4123 }
4124
4125 if (Constructor->isInvalidDecl())
4126 return;
4127
4128 const CXXRecordDecl *RD = Constructor->getParent();
4129
4130 if (RD->isDependentContext())
4131 return;
4132
4133 // Holds fields that are uninitialized.
4134 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4135
4136 // At the beginning, all fields are uninitialized.
4137 for (auto *I : RD->decls()) {
4138 if (auto *FD = dyn_cast<FieldDecl>(I)) {
4139 UninitializedFields.insert(FD);
4140 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(I)) {
4141 UninitializedFields.insert(IFD->getAnonField());
4142 }
4143 }
4144
4145 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4146 for (const auto &I : RD->bases())
4147 UninitializedBaseClasses.insert(I.getType().getCanonicalType());
4148
4149 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4150 return;
4151
4152 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4153 UninitializedFields,
4154 UninitializedBaseClasses);
4155
4156 for (const auto *FieldInit : Constructor->inits()) {
4157 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4158 break;
4159
4160 Expr *InitExpr = FieldInit->getInit();
4161 if (!InitExpr)
4162 continue;
4163
4165 dyn_cast<CXXDefaultInitExpr>(InitExpr)) {
4166 InitExpr = Default->getExpr();
4167 if (!InitExpr)
4168 continue;
4169 // In class initializers will point to the constructor.
4170 UninitializedChecker.CheckInitializer(InitExpr, Constructor,
4171 FieldInit->getAnyMember(),
4172 FieldInit->getBaseClass());
4173 } else {
4174 UninitializedChecker.CheckInitializer(InitExpr, nullptr,
4175 FieldInit->getAnyMember(),
4176 FieldInit->getBaseClass());
4177 }
4178 }
4179 }
4180} // namespace
4181
4182/// Enter a new C++ default initializer scope. After calling this, the
4183/// caller must call \ref ActOnFinishCXXInClassMemberInitializer, even if
4184/// parsing or instantiating the initializer failed.
4186 // Create a synthetic function scope to represent the call to the constructor
4187 // that notionally surrounds a use of this initializer.
4189}
4190
4192 if (!D.isFunctionDeclarator())
4193 return;
4194 auto &FTI = D.getFunctionTypeInfo();
4195 if (!FTI.Params)
4196 return;
4197 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4198 FTI.NumParams)) {
4199 auto *ParamDecl = cast<NamedDecl>(Param.Param);
4200 if (ParamDecl->getDeclName())
4201 PushOnScopeChains(ParamDecl, S, /*AddToContext=*/false);
4202 }
4203}
4204
4206 return ActOnRequiresClause(ConstraintExpr);
4207}
4208
4210 if (ConstraintExpr.isInvalid())
4211 return ExprError();
4212
4213 ConstraintExpr = CorrectDelayedTyposInExpr(ConstraintExpr);
4214 if (ConstraintExpr.isInvalid())
4215 return ExprError();
4216
4217 if (DiagnoseUnexpandedParameterPack(ConstraintExpr.get(),
4219 return ExprError();
4220
4221 return ConstraintExpr;
4222}
4223
4225 Expr *InitExpr,
4226 SourceLocation InitLoc) {
4227 InitializedEntity Entity =
4229 InitializationKind Kind =
4232 InitExpr->getBeginLoc(),
4233 InitExpr->getEndLoc())
4234 : InitializationKind::CreateCopy(InitExpr->getBeginLoc(), InitLoc);
4235 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4236 return Seq.Perform(*this, Entity, Kind, InitExpr);
4237}
4238
4239/// This is invoked after parsing an in-class initializer for a
4240/// non-static C++ class member, and after instantiating an in-class initializer
4241/// in a class template. Such actions are deferred until the class is complete.
4243 SourceLocation InitLoc,
4244 Expr *InitExpr) {
4245 // Pop the notional constructor scope we created earlier.
4246 PopFunctionScopeInfo(nullptr, D);
4247
4248 FieldDecl *FD = dyn_cast<FieldDecl>(D);
4249 assert((isa<MSPropertyDecl>(D) || FD->getInClassInitStyle() != ICIS_NoInit) &&
4250 "must set init style when field is created");
4251
4252 if (!InitExpr) {
4253 D->setInvalidDecl();
4254 if (FD)
4256 return;
4257 }
4258
4260 FD->setInvalidDecl();
4262 return;
4263 }
4264
4265 ExprResult Init = CorrectDelayedTyposInExpr(InitExpr, /*InitDecl=*/nullptr,
4266 /*RecoverUncorrectedTypos=*/true);
4267 assert(Init.isUsable() && "Init should at least have a RecoveryExpr");
4268 if (!FD->getType()->isDependentType() && !Init.get()->isTypeDependent()) {
4269 Init = ConvertMemberDefaultInitExpression(FD, Init.get(), InitLoc);
4270 // C++11 [class.base.init]p7:
4271 // The initialization of each base and member constitutes a
4272 // full-expression.
4273 if (!Init.isInvalid())
4274 Init = ActOnFinishFullExpr(Init.get(), /*DiscarededValue=*/false);
4275 if (Init.isInvalid()) {
4276 FD->setInvalidDecl();
4277 return;
4278 }
4279 }
4280
4281 FD->setInClassInitializer(Init.get());
4282}
4283
4284/// Find the direct and/or virtual base specifiers that
4285/// correspond to the given base type, for use in base initialization
4286/// within a constructor.
4288 CXXRecordDecl *ClassDecl,
4289 QualType BaseType,
4290 const CXXBaseSpecifier *&DirectBaseSpec,
4291 const CXXBaseSpecifier *&VirtualBaseSpec) {
4292 // First, check for a direct base class.
4293 DirectBaseSpec = nullptr;
4294 for (const auto &Base : ClassDecl->bases()) {
4295 if (SemaRef.Context.hasSameUnqualifiedType(BaseType, Base.getType())) {
4296 // We found a direct base of this type. That's what we're
4297 // initializing.
4298 DirectBaseSpec = &Base;
4299 break;
4300 }
4301 }
4302
4303 // Check for a virtual base class.
4304 // FIXME: We might be able to short-circuit this if we know in advance that
4305 // there are no virtual bases.
4306 VirtualBaseSpec = nullptr;
4307 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4308 // We haven't found a base yet; search the class hierarchy for a
4309 // virtual base class.
4310 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4311 /*DetectVirtual=*/false);
4312 if (SemaRef.IsDerivedFrom(ClassDecl->getLocation(),
4313 SemaRef.Context.getTypeDeclType(ClassDecl),
4314 BaseType, Paths)) {
4315 for (CXXBasePaths::paths_iterator Path = Paths.begin();
4316 Path != Paths.end(); ++Path) {
4317 if (Path->back().Base->isVirtual()) {
4318 VirtualBaseSpec = Path->back().Base;
4319 break;
4320 }
4321 }
4322 }
4323 }
4324
4325 return DirectBaseSpec || VirtualBaseSpec;
4326}
4327
4328/// Handle a C++ member initializer using braced-init-list syntax.
4331 Scope *S,
4332 CXXScopeSpec &SS,
4333 IdentifierInfo *MemberOrBase,
4334 ParsedType TemplateTypeTy,
4335 const DeclSpec &DS,
4336 SourceLocation IdLoc,
4337 Expr *InitList,
4338 SourceLocation EllipsisLoc) {
4339 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4340 DS, IdLoc, InitList,
4341 EllipsisLoc);
4342}
4343
4344/// Handle a C++ member initializer using parentheses syntax.
4347 Scope *S,
4348 CXXScopeSpec &SS,
4349 IdentifierInfo *MemberOrBase,
4350 ParsedType TemplateTypeTy,
4351 const DeclSpec &DS,
4352 SourceLocation IdLoc,
4353 SourceLocation LParenLoc,
4354 ArrayRef<Expr *> Args,
4355 SourceLocation RParenLoc,
4356 SourceLocation EllipsisLoc) {
4357 Expr *List = ParenListExpr::Create(Context, LParenLoc, Args, RParenLoc);
4358 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4359 DS, IdLoc, List, EllipsisLoc);
4360}
4361
4362namespace {
4363
4364// Callback to only accept typo corrections that can be a valid C++ member
4365// initializer: either a non-static field member or a base class.
4366class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4367public:
4368 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4369 : ClassDecl(ClassDecl) {}
4370
4371 bool ValidateCandidate(const TypoCorrection &candidate) override {
4372 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4373 if (FieldDecl *Member = dyn_cast<FieldDecl>(ND))
4374 return Member->getDeclContext()->getRedeclContext()->Equals(ClassDecl);
4375 return isa<TypeDecl>(ND);
4376 }
4377 return false;
4378 }
4379
4380 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4381 return std::make_unique<MemInitializerValidatorCCC>(*this);
4382 }
4383
4384private:
4385 CXXRecordDecl *ClassDecl;
4386};
4387
4388}
4389
4391 RecordDecl *ClassDecl,
4392 const IdentifierInfo *Name) {
4393 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4395 llvm::find_if(Result, [this](const NamedDecl *Elem) {
4396 return isa<FieldDecl, IndirectFieldDecl>(Elem) &&
4398 });
4399 // We did not find a placeholder variable
4400 if (Found == Result.end())
4401 return false;
4402 Diag(Loc, diag::err_using_placeholder_variable) << Name;
4403 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4404 const NamedDecl *ND = *It;
4405 if (ND->getDeclContext() != ND->getDeclContext())
4406 break;
4407 if (isa<FieldDecl, IndirectFieldDecl>(ND) &&
4409 Diag(ND->getLocation(), diag::note_reference_placeholder) << ND;
4410 }
4411 return true;
4412}
4413
4414ValueDecl *
4416 const IdentifierInfo *MemberOrBase) {
4417 ValueDecl *ND = nullptr;
4418 for (auto *D : ClassDecl->lookup(MemberOrBase)) {
4419 if (isa<FieldDecl, IndirectFieldDecl>(D)) {
4420 bool IsPlaceholder = D->isPlaceholderVar(getLangOpts());
4421 if (ND) {
4422 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4423 return nullptr;
4424 break;
4425 }
4426 if (!IsPlaceholder)
4427 return cast<ValueDecl>(D);
4428 ND = cast<ValueDecl>(D);
4429 }
4430 }
4431 return ND;
4432}
4433
4434ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4435 CXXScopeSpec &SS,
4436 ParsedType TemplateTypeTy,
4437 IdentifierInfo *MemberOrBase) {
4438 if (SS.getScopeRep() || TemplateTypeTy)
4439 return nullptr;
4440 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4441}
4442
4443/// Handle a C++ member initializer.
4446 Scope *S,
4447 CXXScopeSpec &SS,
4448 IdentifierInfo *MemberOrBase,
4449 ParsedType TemplateTypeTy,
4450 const DeclSpec &DS,
4451 SourceLocation IdLoc,
4452 Expr *Init,
4453 SourceLocation EllipsisLoc) {
4454 ExprResult Res = CorrectDelayedTyposInExpr(Init, /*InitDecl=*/nullptr,
4455 /*RecoverUncorrectedTypos=*/true);
4456 if (!Res.isUsable())
4457 return true;
4458 Init = Res.get();
4459
4460 if (!ConstructorD)
4461 return true;
4462
4463 AdjustDeclIfTemplate(ConstructorD);
4464
4465 CXXConstructorDecl *Constructor
4466 = dyn_cast<CXXConstructorDecl>(ConstructorD);
4467 if (!Constructor) {
4468 // The user wrote a constructor initializer on a function that is
4469 // not a C++ constructor. Ignore the error for now, because we may
4470 // have more member initializers coming; we'll diagnose it just
4471 // once in ActOnMemInitializers.
4472 return true;
4473 }
4474
4475 CXXRecordDecl *ClassDecl = Constructor->getParent();
4476
4477 // C++ [class.base.init]p2:
4478 // Names in a mem-initializer-id are looked up in the scope of the
4479 // constructor's class and, if not found in that scope, are looked
4480 // up in the scope containing the constructor's definition.
4481 // [Note: if the constructor's class contains a member with the
4482 // same name as a direct or virtual base class of the class, a
4483 // mem-initializer-id naming the member or base class and composed
4484 // of a single identifier refers to the class member. A
4485 // mem-initializer-id for the hidden base class may be specified
4486 // using a qualified name. ]
4487
4488 // Look for a member, first.
4489 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4490 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4491 if (EllipsisLoc.isValid())
4492 Diag(EllipsisLoc, diag::err_pack_expansion_member_init)
4493 << MemberOrBase
4494 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4495
4496 return BuildMemberInitializer(Member, Init, IdLoc);
4497 }
4498 // It didn't name a member, so see if it names a class.
4499 QualType BaseType;
4500 TypeSourceInfo *TInfo = nullptr;
4501
4502 if (TemplateTypeTy) {
4503 BaseType = GetTypeFromParser(TemplateTypeTy, &TInfo);
4504 if (BaseType.isNull())
4505 return true;
4506 } else if (DS.getTypeSpecType() == TST_decltype) {
4507 BaseType = BuildDecltypeType(DS.getRepAsExpr());
4508 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4509 Diag(DS.getTypeSpecTypeLoc(), diag::err_decltype_auto_invalid);
4510 return true;
4511 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4512 BaseType =
4514 DS.getBeginLoc(), DS.getEllipsisLoc());
4515 } else {
4516 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4517 LookupParsedName(R, S, &SS);
4518
4519 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4520 if (!TyD) {
4521 if (R.isAmbiguous()) return true;
4522
4523 // We don't want access-control diagnostics here.
4525
4526 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4527 bool NotUnknownSpecialization = false;
4528 DeclContext *DC = computeDeclContext(SS, false);
4529 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(DC))
4530 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4531
4532 if (!NotUnknownSpecialization) {
4533 // When the scope specifier can refer to a member of an unknown
4534 // specialization, we take it as a type name.
4535 BaseType = CheckTypenameType(
4537 SS.getWithLocInContext(Context), *MemberOrBase, IdLoc);
4538 if (BaseType.isNull())
4539 return true;
4540
4541 TInfo = Context.CreateTypeSourceInfo(BaseType);
4544 if (!TL.isNull()) {
4545 TL.setNameLoc(IdLoc);
4548 }
4549
4550 R.clear();
4551 R.setLookupName(MemberOrBase);
4552 }
4553 }
4554
4555 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4556 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4557 auto *TempSpec = cast<TemplateSpecializationType>(
4558 UnqualifiedBase->getInjectedClassNameSpecialization());
4559 TemplateName TN = TempSpec->getTemplateName();
4560 for (auto const &Base : ClassDecl->bases()) {
4561 auto BaseTemplate =
4562 Base.getType()->getAs<TemplateSpecializationType>();
4563 if (BaseTemplate && Context.hasSameTemplateName(
4564 BaseTemplate->getTemplateName(), TN)) {
4565 Diag(IdLoc, diag::ext_unqualified_base_class)
4566 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4567 BaseType = Base.getType();
4568 break;
4569 }
4570 }
4571 }
4572 }
4573
4574 // If no results were found, try to correct typos.
4575 TypoCorrection Corr;
4576 MemInitializerValidatorCCC CCC(ClassDecl);
4577 if (R.empty() && BaseType.isNull() &&
4578 (Corr = CorrectTypo(R.getLookupNameInfo(), R.getLookupKind(), S, &SS,
4579 CCC, CTK_ErrorRecovery, ClassDecl))) {
4581 // We have found a non-static data member with a similar
4582 // name to what was typed; complain and initialize that
4583 // member.
4584 diagnoseTypo(Corr,
4585 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4586 << MemberOrBase << true);
4587 return BuildMemberInitializer(Member, Init, IdLoc);
4588 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4589 const CXXBaseSpecifier *DirectBaseSpec;
4590 const CXXBaseSpecifier *VirtualBaseSpec;
4591 if (FindBaseInitializer(*this, ClassDecl,
4593 DirectBaseSpec, VirtualBaseSpec)) {
4594 // We have found a direct or virtual base class with a
4595 // similar name to what was typed; complain and initialize
4596 // that base class.
4597 diagnoseTypo(Corr,
4598 PDiag(diag::err_mem_init_not_member_or_class_suggest)
4599 << MemberOrBase << false,
4600 PDiag() /*Suppress note, we provide our own.*/);
4601
4602 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4603 : VirtualBaseSpec;
4604 Diag(BaseSpec->getBeginLoc(), diag::note_base_class_specified_here)
4605 << BaseSpec->getType() << BaseSpec->getSourceRange();
4606
4607 TyD = Type;
4608 }
4609 }
4610 }
4611
4612 if (!TyD && BaseType.isNull()) {
4613 Diag(IdLoc, diag::err_mem_init_not_member_or_class)
4614 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4615 return true;
4616 }
4617 }
4618
4619 if (BaseType.isNull()) {
4622 MarkAnyDeclReferenced(TyD->getLocation(), TyD, /*OdrUse=*/false);
4623 TInfo = Context.CreateTypeSourceInfo(BaseType);
4625 TL.getNamedTypeLoc().castAs<TypeSpecTypeLoc>().setNameLoc(IdLoc);
4628 }
4629 }
4630
4631 if (!TInfo)
4632 TInfo = Context.getTrivialTypeSourceInfo(BaseType, IdLoc);
4633
4634 return BuildBaseInitializer(BaseType, TInfo, Init, ClassDecl, EllipsisLoc);
4635}
4636
4639 SourceLocation IdLoc) {
4640 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Member);
4641 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Member);
4642 assert((DirectMember || IndirectMember) &&
4643 "Member must be a FieldDecl or IndirectFieldDecl");
4644
4646 return true;
4647
4648 if (Member->isInvalidDecl())
4649 return true;
4650
4651 MultiExprArg Args;
4652 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4653 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4654 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Init)) {
4655 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4656 } else {
4657 // Template instantiation doesn't reconstruct ParenListExprs for us.
4658 Args = Init;
4659 }
4660
4661 SourceRange InitRange = Init->getSourceRange();
4662
4663 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4664 // Can't check initialization for a member of dependent type or when
4665 // any of the arguments are type-dependent expressions.
4667 } else {
4668 bool InitList = false;
4669 if (isa<InitListExpr>(Init)) {
4670 InitList = true;
4671 Args = Init;
4672 }
4673
4674 // Initialize the member.
4675 InitializedEntity MemberEntity =
4676 DirectMember ? InitializedEntity::InitializeMember(DirectMember, nullptr)
4677 : InitializedEntity::InitializeMember(IndirectMember,
4678 nullptr);
4679 InitializationKind Kind =
4681 IdLoc, Init->getBeginLoc(), Init->getEndLoc())
4682 : InitializationKind::CreateDirect(IdLoc, InitRange.getBegin(),
4683 InitRange.getEnd());
4684
4685 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4686 ExprResult MemberInit = InitSeq.Perform(*this, MemberEntity, Kind, Args,
4687 nullptr);
4688 if (!MemberInit.isInvalid()) {
4689 // C++11 [class.base.init]p7:
4690 // The initialization of each base and member constitutes a
4691 // full-expression.
4692 MemberInit = ActOnFinishFullExpr(MemberInit.get(), InitRange.getBegin(),
4693 /*DiscardedValue*/ false);
4694 }
4695
4696 if (MemberInit.isInvalid()) {
4697 // Args were sensible expressions but we couldn't initialize the member
4698 // from them. Preserve them in a RecoveryExpr instead.
4699 Init = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4700 Member->getType())
4701 .get();
4702 if (!Init)
4703 return true;
4704 } else {
4705 Init = MemberInit.get();
4706 }
4707 }
4708
4709 if (DirectMember) {
4710 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4711 InitRange.getBegin(), Init,
4712 InitRange.getEnd());
4713 } else {
4714 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4715 InitRange.getBegin(), Init,
4716 InitRange.getEnd());
4717 }
4718}
4719
4722 CXXRecordDecl *ClassDecl) {
4723 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4724 if (!LangOpts.CPlusPlus11)
4725 return Diag(NameLoc, diag::err_delegating_ctor)
4726 << TInfo->getTypeLoc().getSourceRange();
4727 Diag(NameLoc, diag::warn_cxx98_compat_delegating_ctor);
4728
4729 bool InitList = true;
4730 MultiExprArg Args = Init;
4731 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4732 InitList = false;
4733 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4734 }
4735
4736 SourceRange InitRange = Init->getSourceRange();
4737 // Initialize the object.
4739 QualType(ClassDecl->getTypeForDecl(), 0));
4740 InitializationKind Kind =
4742 NameLoc, Init->getBeginLoc(), Init->getEndLoc())
4743 : InitializationKind::CreateDirect(NameLoc, InitRange.getBegin(),
4744 InitRange.getEnd());
4745 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4746 ExprResult DelegationInit = InitSeq.Perform(*this, DelegationEntity, Kind,
4747 Args, nullptr);
4748 if (!DelegationInit.isInvalid()) {
4749 assert((DelegationInit.get()->containsErrors() ||
4750 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4751 "Delegating constructor with no target?");
4752
4753 // C++11 [class.base.init]p7:
4754 // The initialization of each base and member constitutes a
4755 // full-expression.
4756 DelegationInit = ActOnFinishFullExpr(
4757 DelegationInit.get(), InitRange.getBegin(), /*DiscardedValue*/ false);
4758 }
4759
4760 if (DelegationInit.isInvalid()) {
4761 DelegationInit =
4762 CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(), Args,
4763 QualType(ClassDecl->getTypeForDecl(), 0));
4764 if (DelegationInit.isInvalid())
4765 return true;
4766 } else {
4767 // If we are in a dependent context, template instantiation will
4768 // perform this type-checking again. Just save the arguments that we
4769 // received in a ParenListExpr.
4770 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4771 // of the information that we have about the base
4772 // initializer. However, deconstructing the ASTs is a dicey process,
4773 // and this approach is far more likely to get the corner cases right.
4775 DelegationInit = Init;
4776 }
4777
4778 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4779 DelegationInit.getAs<Expr>(),
4780 InitRange.getEnd());
4781}
4782
4785 Expr *Init, CXXRecordDecl *ClassDecl,
4786 SourceLocation EllipsisLoc) {
4787 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4788
4789 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4790 return Diag(BaseLoc, diag::err_base_init_does_not_name_class)
4791 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4792
4793 // C++ [class.base.init]p2:
4794 // [...] Unless the mem-initializer-id names a nonstatic data
4795 // member of the constructor's class or a direct or virtual base
4796 // of that class, the mem-initializer is ill-formed. A
4797 // mem-initializer-list can initialize a base class using any
4798 // name that denotes that base class type.
4799
4800 // We can store the initializers in "as-written" form and delay analysis until
4801 // instantiation if the constructor is dependent. But not for dependent
4802 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4803 bool Dependent = CurContext->isDependentContext() &&
4804 (BaseType->isDependentType() || Init->isTypeDependent());
4805
4806 SourceRange InitRange = Init->getSourceRange();
4807 if (EllipsisLoc.isValid()) {
4808 // This is a pack expansion.
4809 if (!BaseType->containsUnexpandedParameterPack()) {
4810 Diag(EllipsisLoc, diag::err_pack_expansion_without_parameter_packs)
4811 << SourceRange(BaseLoc, InitRange.getEnd());
4812
4813 EllipsisLoc = SourceLocation();
4814 }
4815 } else {
4816 // Check for any unexpanded parameter packs.
4817 if (DiagnoseUnexpandedParameterPack(BaseLoc, BaseTInfo, UPPC_Initializer))
4818 return true;
4819
4821 return true;
4822 }
4823
4824 // Check for direct and virtual base classes.
4825 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4826 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4827 if (!Dependent) {
4829 BaseType))
4830 return BuildDelegatingInitializer(BaseTInfo, Init, ClassDecl);
4831
4832 FindBaseInitializer(*this, ClassDecl, BaseType, DirectBaseSpec,
4833 VirtualBaseSpec);
4834
4835 // C++ [base.class.init]p2:
4836 // Unless the mem-initializer-id names a nonstatic data member of the
4837 // constructor's class or a direct or virtual base of that class, the
4838 // mem-initializer is ill-formed.
4839 if (!DirectBaseSpec && !VirtualBaseSpec) {
4840 // If the class has any dependent bases, then it's possible that
4841 // one of those types will resolve to the same type as
4842 // BaseType. Therefore, just treat this as a dependent base
4843 // class initialization. FIXME: Should we try to check the
4844 // initialization anyway? It seems odd.
4845 if (ClassDecl->hasAnyDependentBases())
4846 Dependent = true;
4847 else
4848 return Diag(BaseLoc, diag::err_not_direct_base_or_virtual)
4849 << BaseType << Context.getTypeDeclType(ClassDecl)
4850 << BaseTInfo->getTypeLoc().getSourceRange();
4851 }
4852 }
4853
4854 if (Dependent) {
4856
4857 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4858 /*IsVirtual=*/false,
4859 InitRange.getBegin(), Init,
4860 InitRange.getEnd(), EllipsisLoc);
4861 }
4862
4863 // C++ [base.class.init]p2:
4864 // If a mem-initializer-id is ambiguous because it designates both
4865 // a direct non-virtual base class and an inherited virtual base
4866 // class, the mem-initializer is ill-formed.
4867 if (DirectBaseSpec && VirtualBaseSpec)
4868 return Diag(BaseLoc, diag::err_base_init_direct_and_virtual)
4869 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4870
4871 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4872 if (!BaseSpec)
4873 BaseSpec = VirtualBaseSpec;
4874
4875 // Initialize the base.
4876 bool InitList = true;
4877 MultiExprArg Args = Init;
4878 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Init)) {
4879 InitList = false;
4880 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4881 }
4882
4883 InitializedEntity BaseEntity =
4884 InitializedEntity::InitializeBase(Context, BaseSpec, VirtualBaseSpec);
4885 InitializationKind Kind =
4886 InitList ? InitializationKind::CreateDirectList(BaseLoc)
4887 : InitializationKind::CreateDirect(BaseLoc, InitRange.getBegin(),
4888 InitRange.getEnd());
4889 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4890 ExprResult BaseInit = InitSeq.Perform(*this, BaseEntity, Kind, Args, nullptr);
4891 if (!BaseInit.isInvalid()) {
4892 // C++11 [class.base.init]p7:
4893 // The initialization of each base and member constitutes a
4894 // full-expression.
4895 BaseInit = ActOnFinishFullExpr(BaseInit.get(), InitRange.getBegin(),
4896 /*DiscardedValue*/ false);
4897 }
4898
4899 if (BaseInit.isInvalid()) {
4900 BaseInit = CreateRecoveryExpr(InitRange.getBegin(), InitRange.getEnd(),
4901 Args, BaseType);
4902 if (BaseInit.isInvalid())
4903 return true;
4904 } else {
4905 // If we are in a dependent context, template instantiation will
4906 // perform this type-checking again. Just save the arguments that we
4907 // received in a ParenListExpr.
4908 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4909 // of the information that we have about the base
4910 // initializer. However, deconstructing the ASTs is a dicey process,
4911 // and this approach is far more likely to get the corner cases right.
4913 BaseInit = Init;
4914 }
4915
4916 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4917 BaseSpec->isVirtual(),
4918 InitRange.getBegin(),
4919 BaseInit.getAs<Expr>(),
4920 InitRange.getEnd(), EllipsisLoc);
4921}
4922
4923// Create a static_cast<T&&>(expr).
4925 QualType TargetType =
4926 SemaRef.BuildReferenceType(E->getType(), /*SpelledAsLValue*/ false,
4928 SourceLocation ExprLoc = E->getBeginLoc();
4930 TargetType, ExprLoc);
4931
4932 return SemaRef.BuildCXXNamedCast(ExprLoc, tok::kw_static_cast, TargetLoc, E,
4933 SourceRange(ExprLoc, ExprLoc),
4934 E->getSourceRange()).get();
4935}
4936
4937/// ImplicitInitializerKind - How an implicit base or member initializer should
4938/// initialize its base or member.
4945
4946static bool
4948 ImplicitInitializerKind ImplicitInitKind,
4949 CXXBaseSpecifier *BaseSpec,
4950 bool IsInheritedVirtualBase,
4951 CXXCtorInitializer *&CXXBaseInit) {
4952 InitializedEntity InitEntity
4954 IsInheritedVirtualBase);
4955
4956 ExprResult BaseInit;
4957
4958 switch (ImplicitInitKind) {
4959 case IIK_Inherit:
4960 case IIK_Default: {
4961 InitializationKind InitKind
4962 = InitializationKind::CreateDefault(Constructor->getLocation());
4963 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, std::nullopt);
4964 BaseInit = InitSeq.Perform(SemaRef, InitEntity, InitKind, std::nullopt);
4965 break;
4966 }
4967
4968 case IIK_Move:
4969 case IIK_Copy: {
4970 bool Moving = ImplicitInitKind == IIK_Move;
4971 ParmVarDecl *Param = Constructor->getParamDecl(0);
4972 QualType ParamType = Param->getType().getNonReferenceType();
4973
4974 Expr *CopyCtorArg =
4976 SourceLocation(), Param, false,
4977 Constructor->getLocation(), ParamType,
4978 VK_LValue, nullptr);
4979
4980 SemaRef.MarkDeclRefReferenced(cast<DeclRefExpr>(CopyCtorArg));
4981
4982