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