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
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DynamicRecursiveASTVisitor.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Basic/AttributeCommonInfo.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/Specifiers.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/EnterExpressionEvaluationContext.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Ownership.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaCUDA.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/SemaObjC.h"
48#include "clang/Sema/SemaOpenMP.h"
49#include "clang/Sema/Template.h"
50#include "clang/Sema/TemplateDeduction.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86 bool VisitCoawaitExpr(const CoawaitExpr *E);
87 bool VisitCoyieldExpr(const CoyieldExpr *E);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(S: SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = DRE->getDecl();
104
105 if (!isa<VarDecl, BindingDecl>(Val: Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(Loc: DRE->getBeginLoc(),
119 DiagID: diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(Loc: DRE->getBeginLoc(),
136 DiagID: diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(Loc: ThisE->getBeginLoc(),
148 DiagID: diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(S: E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(Capture: &LC))
176 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
179 Invalid |= Visit(S: D->getInit());
180 }
181 return Invalid;
182}
183
184bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
185 // [expr.await] An await-expression shall not appear in a default argument.
186 // Note that this is generally diagnosed by isValidCoroutineContext,
187 // however isValidCoroutineContext misses default argument in nested
188 // function declarations.
189 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
190 << "co_await" << E->getSourceRange();
191 return true;
192}
193
194bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
195 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
196 << "co_yield" << E->getSourceRange();
197 return true;
198}
199
200} // namespace
201
202void
203Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
204 const CXXMethodDecl *Method) {
205 // If we have an MSAny spec already, don't bother.
206 if (!Method || ComputedEST == EST_MSAny)
207 return;
208
209 const FunctionProtoType *Proto
210 = Method->getType()->getAs<FunctionProtoType>();
211 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
212 if (!Proto)
213 return;
214
215 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
216
217 // If we have a throw-all spec at this point, ignore the function.
218 if (ComputedEST == EST_None)
219 return;
220
221 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
222 EST = EST_BasicNoexcept;
223
224 switch (EST) {
225 case EST_Unparsed:
226 case EST_Uninstantiated:
227 case EST_Unevaluated:
228 llvm_unreachable("should not see unresolved exception specs here");
229
230 // If this function can throw any exceptions, make a note of that.
231 case EST_MSAny:
232 case EST_None:
233 // FIXME: Whichever we see last of MSAny and None determines our result.
234 // We should make a consistent, order-independent choice here.
235 ClearExceptions();
236 ComputedEST = EST;
237 return;
238 case EST_NoexceptFalse:
239 ClearExceptions();
240 ComputedEST = EST_None;
241 return;
242 // FIXME: If the call to this decl is using any of its default arguments, we
243 // need to search them for potentially-throwing calls.
244 // If this function has a basic noexcept, it doesn't affect the outcome.
245 case EST_BasicNoexcept:
246 case EST_NoexceptTrue:
247 case EST_NoThrow:
248 return;
249 // If we're still at noexcept(true) and there's a throw() callee,
250 // change to that specification.
251 case EST_DynamicNone:
252 if (ComputedEST == EST_BasicNoexcept)
253 ComputedEST = EST_DynamicNone;
254 return;
255 case EST_DependentNoexcept:
256 llvm_unreachable(
257 "should not generate implicit declarations for dependent cases");
258 case EST_Dynamic:
259 break;
260 }
261 assert(EST == EST_Dynamic && "EST case not considered earlier.");
262 assert(ComputedEST != EST_None &&
263 "Shouldn't collect exceptions when throw-all is guaranteed.");
264 ComputedEST = EST_Dynamic;
265 // Record the exceptions in this function's exception specification.
266 for (const auto &E : Proto->exceptions())
267 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
268 Exceptions.push_back(Elt: E);
269}
270
271void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
272 if (!S || ComputedEST == EST_MSAny)
273 return;
274
275 // FIXME:
276 //
277 // C++0x [except.spec]p14:
278 // [An] implicit exception-specification specifies the type-id T if and
279 // only if T is allowed by the exception-specification of a function directly
280 // invoked by f's implicit definition; f shall allow all exceptions if any
281 // function it directly invokes allows all exceptions, and f shall allow no
282 // exceptions if every function it directly invokes allows no exceptions.
283 //
284 // Note in particular that if an implicit exception-specification is generated
285 // for a function containing a throw-expression, that specification can still
286 // be noexcept(true).
287 //
288 // Note also that 'directly invoked' is not defined in the standard, and there
289 // is no indication that we should only consider potentially-evaluated calls.
290 //
291 // Ultimately we should implement the intent of the standard: the exception
292 // specification should be the set of exceptions which can be thrown by the
293 // implicit definition. For now, we assume that any non-nothrow expression can
294 // throw any exception.
295
296 if (Self->canThrow(E: S))
297 ComputedEST = EST_None;
298}
299
300ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
301 SourceLocation EqualLoc) {
302 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
303 DiagID: diag::err_typecheck_decl_incomplete_type))
304 return true;
305
306 // C++ [dcl.fct.default]p5
307 // A default argument expression is implicitly converted (clause
308 // 4) to the parameter type. The default argument expression has
309 // the same semantic constraints as the initializer expression in
310 // a declaration of a variable of the parameter type, using the
311 // copy-initialization semantics (8.5).
312 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
313 Parm: Param);
314 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
315 EqualLoc);
316 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
317 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
318 if (Result.isInvalid())
319 return true;
320 Arg = Result.getAs<Expr>();
321
322 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
323 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
324
325 return Arg;
326}
327
328void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
329 SourceLocation EqualLoc) {
330 // Add the default argument to the parameter
331 Param->setDefaultArg(Arg);
332
333 // We have already instantiated this parameter; provide each of the
334 // instantiations with the uninstantiated default argument.
335 UnparsedDefaultArgInstantiationsMap::iterator InstPos
336 = UnparsedDefaultArgInstantiations.find(Val: Param);
337 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
338 for (auto &Instantiation : InstPos->second)
339 Instantiation->setUninstantiatedDefaultArg(Arg);
340
341 // We're done tracking this parameter's instantiations.
342 UnparsedDefaultArgInstantiations.erase(I: InstPos);
343 }
344}
345
346void
347Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
348 Expr *DefaultArg) {
349 if (!param || !DefaultArg)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
353 UnparsedDefaultArgLocs.erase(Val: Param);
354
355 // Default arguments are only permitted in C++
356 if (!getLangOpts().CPlusPlus) {
357 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
358 << DefaultArg->getSourceRange();
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 }
361
362 // Check for unexpanded parameter packs.
363 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
364 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
365
366 // C++11 [dcl.fct.default]p3
367 // A default argument expression [...] shall not be specified for a
368 // parameter pack.
369 if (Param->isParameterPack()) {
370 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
371 << DefaultArg->getSourceRange();
372 // Recover by discarding the default argument.
373 Param->setDefaultArg(nullptr);
374 return;
375 }
376
377 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
378 if (Result.isInvalid())
379 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
380
381 DefaultArg = Result.getAs<Expr>();
382
383 // Check that the default argument is well-formed
384 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
385 if (DefaultArgChecker.Visit(S: DefaultArg))
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
389}
390
391void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
392 SourceLocation EqualLoc,
393 SourceLocation ArgLoc) {
394 if (!param)
395 return;
396
397 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
398 Param->setUnparsedDefaultArg();
399 UnparsedDefaultArgLocs[Param] = ArgLoc;
400}
401
402void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
403 Expr *DefaultArg) {
404 if (!param)
405 return;
406
407 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
408 Param->setInvalidDecl();
409 UnparsedDefaultArgLocs.erase(Val: Param);
410 ExprResult RE;
411 if (DefaultArg) {
412 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
413 T: Param->getType().getNonReferenceType());
414 } else {
415 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
416 T: Param->getType().getNonReferenceType());
417 }
418 Param->setDefaultArg(RE.get());
419}
420
421void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
422 // C++ [dcl.fct.default]p3
423 // A default argument expression shall be specified only in the
424 // parameter-declaration-clause of a function declaration or in a
425 // template-parameter (14.1). It shall not be specified for a
426 // parameter pack. If it is specified in a
427 // parameter-declaration-clause, it shall not occur within a
428 // declarator or abstract-declarator of a parameter-declaration.
429 bool MightBeFunction = D.isFunctionDeclarationContext();
430 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
431 DeclaratorChunk &chunk = D.getTypeObject(i);
432 if (chunk.Kind == DeclaratorChunk::Function) {
433 if (MightBeFunction) {
434 // This is a function declaration. It can have default arguments, but
435 // keep looking in case its return type is a function type with default
436 // arguments.
437 MightBeFunction = false;
438 continue;
439 }
440 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
441 ++argIdx) {
442 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
443 if (Param->hasUnparsedDefaultArg()) {
444 std::unique_ptr<CachedTokens> Toks =
445 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
446 SourceRange SR;
447 if (Toks->size() > 1)
448 SR = SourceRange((*Toks)[1].getLocation(),
449 Toks->back().getLocation());
450 else
451 SR = UnparsedDefaultArgLocs[Param];
452 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
453 << SR;
454 } else if (Param->getDefaultArg()) {
455 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
456 << Param->getDefaultArg()->getSourceRange();
457 Param->setDefaultArg(nullptr);
458 }
459 }
460 } else if (chunk.Kind != DeclaratorChunk::Paren) {
461 MightBeFunction = false;
462 }
463 }
464}
465
466static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
467 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
468 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
469 });
470}
471
472bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
473 Scope *S) {
474 bool Invalid = false;
475
476 // The declaration context corresponding to the scope is the semantic
477 // parent, unless this is a local function declaration, in which case
478 // it is that surrounding function.
479 DeclContext *ScopeDC = New->isLocalExternDecl()
480 ? New->getLexicalDeclContext()
481 : New->getDeclContext();
482
483 // Find the previous declaration for the purpose of default arguments.
484 FunctionDecl *PrevForDefaultArgs = Old;
485 for (/**/; PrevForDefaultArgs;
486 // Don't bother looking back past the latest decl if this is a local
487 // extern declaration; nothing else could work.
488 PrevForDefaultArgs = New->isLocalExternDecl()
489 ? nullptr
490 : PrevForDefaultArgs->getPreviousDecl()) {
491 // Ignore hidden declarations.
492 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
493 continue;
494
495 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
496 !New->isCXXClassMember()) {
497 // Ignore default arguments of old decl if they are not in
498 // the same scope and this is not an out-of-line definition of
499 // a member function.
500 continue;
501 }
502
503 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
504 // If only one of these is a local function declaration, then they are
505 // declared in different scopes, even though isDeclInScope may think
506 // they're in the same scope. (If both are local, the scope check is
507 // sufficient, and if neither is local, then they are in the same scope.)
508 continue;
509 }
510
511 // We found the right previous declaration.
512 break;
513 }
514
515 // C++ [dcl.fct.default]p4:
516 // For non-template functions, default arguments can be added in
517 // later declarations of a function in the same
518 // scope. Declarations in different scopes have completely
519 // distinct sets of default arguments. That is, declarations in
520 // inner scopes do not acquire default arguments from
521 // declarations in outer scopes, and vice versa. In a given
522 // function declaration, all parameters subsequent to a
523 // parameter with a default argument shall have default
524 // arguments supplied in this or previous declarations. A
525 // default argument shall not be redefined by a later
526 // declaration (not even to the same value).
527 //
528 // C++ [dcl.fct.default]p6:
529 // Except for member functions of class templates, the default arguments
530 // in a member function definition that appears outside of the class
531 // definition are added to the set of default arguments provided by the
532 // member function declaration in the class definition.
533 for (unsigned p = 0, NumParams = PrevForDefaultArgs
534 ? PrevForDefaultArgs->getNumParams()
535 : 0;
536 p < NumParams; ++p) {
537 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
538 ParmVarDecl *NewParam = New->getParamDecl(i: p);
539
540 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
541 bool NewParamHasDfl = NewParam->hasDefaultArg();
542
543 if (OldParamHasDfl && NewParamHasDfl) {
544 unsigned DiagDefaultParamID =
545 diag::err_param_default_argument_redefinition;
546
547 // MSVC accepts that default parameters be redefined for member functions
548 // of template class. The new default parameter's value is ignored.
549 Invalid = true;
550 if (getLangOpts().MicrosoftExt) {
551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
552 if (MD && MD->getParent()->getDescribedClassTemplate()) {
553 // Merge the old default argument into the new parameter.
554 NewParam->setHasInheritedDefaultArg();
555 if (OldParam->hasUninstantiatedDefaultArg())
556 NewParam->setUninstantiatedDefaultArg(
557 OldParam->getUninstantiatedDefaultArg());
558 else
559 NewParam->setDefaultArg(OldParam->getInit());
560 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
561 Invalid = false;
562 }
563 }
564
565 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
566 // hint here. Alternatively, we could walk the type-source information
567 // for NewParam to find the last source location in the type... but it
568 // isn't worth the effort right now. This is the kind of test case that
569 // is hard to get right:
570 // int f(int);
571 // void g(int (*fp)(int) = f);
572 // void g(int (*fp)(int) = &f);
573 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
574 << NewParam->getDefaultArgRange();
575
576 // Look for the function declaration where the default argument was
577 // actually written, which may be a declaration prior to Old.
578 for (auto Older = PrevForDefaultArgs;
579 OldParam->hasInheritedDefaultArg(); /**/) {
580 Older = Older->getPreviousDecl();
581 OldParam = Older->getParamDecl(i: p);
582 }
583
584 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
585 << OldParam->getDefaultArgRange();
586 } else if (OldParamHasDfl) {
587 // Merge the old default argument into the new parameter unless the new
588 // function is a friend declaration in a template class. In the latter
589 // case the default arguments will be inherited when the friend
590 // declaration will be instantiated.
591 if (New->getFriendObjectKind() == Decl::FOK_None ||
592 !New->getLexicalDeclContext()->isDependentContext()) {
593 // It's important to use getInit() here; getDefaultArg()
594 // strips off any top-level ExprWithCleanups.
595 NewParam->setHasInheritedDefaultArg();
596 if (OldParam->hasUnparsedDefaultArg())
597 NewParam->setUnparsedDefaultArg();
598 else if (OldParam->hasUninstantiatedDefaultArg())
599 NewParam->setUninstantiatedDefaultArg(
600 OldParam->getUninstantiatedDefaultArg());
601 else
602 NewParam->setDefaultArg(OldParam->getInit());
603 }
604 } else if (NewParamHasDfl) {
605 if (New->getDescribedFunctionTemplate()) {
606 // Paragraph 4, quoted above, only applies to non-template functions.
607 Diag(Loc: NewParam->getLocation(),
608 DiagID: diag::err_param_default_argument_template_redecl)
609 << NewParam->getDefaultArgRange();
610 Diag(Loc: PrevForDefaultArgs->getLocation(),
611 DiagID: diag::note_template_prev_declaration)
612 << false;
613 } else if (New->getTemplateSpecializationKind()
614 != TSK_ImplicitInstantiation &&
615 New->getTemplateSpecializationKind() != TSK_Undeclared) {
616 // C++ [temp.expr.spec]p21:
617 // Default function arguments shall not be specified in a declaration
618 // or a definition for one of the following explicit specializations:
619 // - the explicit specialization of a function template;
620 // - the explicit specialization of a member function template;
621 // - the explicit specialization of a member function of a class
622 // template where the class template specialization to which the
623 // member function specialization belongs is implicitly
624 // instantiated.
625 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
626 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
627 << New->getDeclName()
628 << NewParam->getDefaultArgRange();
629 } else if (New->getDeclContext()->isDependentContext()) {
630 // C++ [dcl.fct.default]p6 (DR217):
631 // Default arguments for a member function of a class template shall
632 // be specified on the initial declaration of the member function
633 // within the class template.
634 //
635 // Reading the tea leaves a bit in DR217 and its reference to DR205
636 // leads me to the conclusion that one cannot add default function
637 // arguments for an out-of-line definition of a member function of a
638 // dependent type.
639 int WhichKind = 2;
640 if (CXXRecordDecl *Record
641 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
642 if (Record->getDescribedClassTemplate())
643 WhichKind = 0;
644 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
645 WhichKind = 1;
646 else
647 WhichKind = 2;
648 }
649
650 Diag(Loc: NewParam->getLocation(),
651 DiagID: diag::err_param_default_argument_member_template_redecl)
652 << WhichKind
653 << NewParam->getDefaultArgRange();
654 }
655 }
656 }
657
658 // DR1344: If a default argument is added outside a class definition and that
659 // default argument makes the function a special member function, the program
660 // is ill-formed. This can only happen for constructors.
661 if (isa<CXXConstructorDecl>(Val: New) &&
662 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
663 CXXSpecialMemberKind NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)),
664 OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old));
665 if (NewSM != OldSM) {
666 ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments());
667 assert(NewParam->hasDefaultArg());
668 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
669 << NewParam->getDefaultArgRange() << NewSM;
670 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
671 }
672 }
673
674 const FunctionDecl *Def;
675 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
676 // template has a constexpr specifier then all its declarations shall
677 // contain the constexpr specifier.
678 if (New->getConstexprKind() != Old->getConstexprKind()) {
679 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
680 << New << static_cast<int>(New->getConstexprKind())
681 << static_cast<int>(Old->getConstexprKind());
682 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
683 Invalid = true;
684 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
685 Old->isDefined(Definition&: Def) &&
686 // If a friend function is inlined but does not have 'inline'
687 // specifier, it is a definition. Do not report attribute conflict
688 // in this case, redefinition will be diagnosed later.
689 (New->isInlineSpecified() ||
690 New->getFriendObjectKind() == Decl::FOK_None)) {
691 // C++11 [dcl.fcn.spec]p4:
692 // If the definition of a function appears in a translation unit before its
693 // first declaration as inline, the program is ill-formed.
694 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
695 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
696 Invalid = true;
697 }
698
699 // C++17 [temp.deduct.guide]p3:
700 // Two deduction guide declarations in the same translation unit
701 // for the same class template shall not have equivalent
702 // parameter-declaration-clauses.
703 if (isa<CXXDeductionGuideDecl>(Val: New) &&
704 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
705 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
706 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
707 }
708
709 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
710 // argument expression, that declaration shall be a definition and shall be
711 // the only declaration of the function or function template in the
712 // translation unit.
713 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
714 functionDeclHasDefaultArgument(FD: Old)) {
715 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
716 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
717 Invalid = true;
718 }
719
720 // C++11 [temp.friend]p4 (DR329):
721 // When a function is defined in a friend function declaration in a class
722 // template, the function is instantiated when the function is odr-used.
723 // The same restrictions on multiple declarations and definitions that
724 // apply to non-template function declarations and definitions also apply
725 // to these implicit definitions.
726 const FunctionDecl *OldDefinition = nullptr;
727 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
728 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
729 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
730
731 return Invalid;
732}
733
734void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
735 Diag(Loc, DiagID: getLangOpts().CPlusPlus26
736 ? diag::warn_cxx23_placeholder_var_definition
737 : diag::ext_placeholder_var_definition);
738}
739
740NamedDecl *
741Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
742 MultiTemplateParamsArg TemplateParamLists) {
743 assert(D.isDecompositionDeclarator());
744 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
745
746 // The syntax only allows a decomposition declarator as a simple-declaration,
747 // a for-range-declaration, or a condition in Clang, but we parse it in more
748 // cases than that.
749 if (!D.mayHaveDecompositionDeclarator()) {
750 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
751 << Decomp.getSourceRange();
752 return nullptr;
753 }
754
755 if (!TemplateParamLists.empty()) {
756 // C++17 [temp]/1:
757 // A template defines a family of class, functions, or variables, or an
758 // alias for a family of types.
759 //
760 // Structured bindings are not included.
761 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
762 DiagID: diag::err_decomp_decl_template);
763 return nullptr;
764 }
765
766 unsigned DiagID;
767 if (!getLangOpts().CPlusPlus17)
768 DiagID = diag::compat_pre_cxx17_decomp_decl;
769 else if (D.getContext() == DeclaratorContext::Condition)
770 DiagID = getLangOpts().CPlusPlus26
771 ? diag::compat_cxx26_decomp_decl_cond
772 : diag::compat_pre_cxx26_decomp_decl_cond;
773 else
774 DiagID = diag::compat_cxx17_decomp_decl;
775
776 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
777
778 // The semantic context is always just the current context.
779 DeclContext *const DC = CurContext;
780
781 // C++17 [dcl.dcl]/8:
782 // The decl-specifier-seq shall contain only the type-specifier auto
783 // and cv-qualifiers.
784 // C++20 [dcl.dcl]/8:
785 // If decl-specifier-seq contains any decl-specifier other than static,
786 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
787 // C++23 [dcl.pre]/6:
788 // Each decl-specifier in the decl-specifier-seq shall be static,
789 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
790 // C++23 [dcl.pre]/7:
791 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
792 // constinit, static, thread_local, auto, or a cv-qualifier
793 auto &DS = D.getDeclSpec();
794 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
795 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
796 };
797
798 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
799 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
800 };
801
802 if (auto SCS = DS.getStorageClassSpec()) {
803 if (SCS == DeclSpec::SCS_static)
804 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
805 DS.getStorageClassSpecLoc());
806 else
807 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
808 DS.getStorageClassSpecLoc());
809 }
810 if (auto TSCS = DS.getThreadStorageClassSpec())
811 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
812 DS.getThreadStorageClassSpecLoc());
813
814 if (DS.isInlineSpecified())
815 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
816
817 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
818 ConstexprSpec != ConstexprSpecKind::Unspecified) {
819 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
820 !getLangOpts().CPlusPlus26)
821 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
822 DS.getConstexprSpecLoc());
823 }
824
825 // We can't recover from it being declared as a typedef.
826 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
827 return nullptr;
828
829 // C++2a [dcl.struct.bind]p1:
830 // A cv that includes volatile is deprecated
831 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
832 getLangOpts().CPlusPlus20)
833 Diag(Loc: DS.getVolatileSpecLoc(),
834 DiagID: diag::warn_deprecated_volatile_structured_binding);
835
836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
837 QualType R = TInfo->getType();
838
839 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
840 UPPC: UPPC_DeclarationType))
841 D.setInvalidType();
842
843 // The syntax only allows a single ref-qualifier prior to the decomposition
844 // declarator. No other declarator chunks are permitted. Also check the type
845 // specifier here.
846 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
847 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
848 (D.getNumTypeObjects() == 1 &&
849 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
850 Diag(Loc: Decomp.getLSquareLoc(),
851 DiagID: (D.hasGroupingParens() ||
852 (D.getNumTypeObjects() &&
853 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
854 ? diag::err_decomp_decl_parens
855 : diag::err_decomp_decl_type)
856 << R;
857
858 // In most cases, there's no actual problem with an explicitly-specified
859 // type, but a function type won't work here, and ActOnVariableDeclarator
860 // shouldn't be called for such a type.
861 if (R->isFunctionType())
862 D.setInvalidType();
863 }
864
865 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
866 if (DS.isConstrainedAuto()) {
867 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
868 assert(TemplRep->Kind == TNK_Concept_template &&
869 "No other template kind should be possible for a constrained auto");
870
871 SourceRange TemplRange{TemplRep->TemplateNameLoc,
872 TemplRep->RAngleLoc.isValid()
873 ? TemplRep->RAngleLoc
874 : TemplRep->TemplateNameLoc};
875 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
876 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
877 }
878
879 // Build the BindingDecls.
880 SmallVector<BindingDecl*, 8> Bindings;
881
882 // Build the BindingDecls.
883 for (auto &B : D.getDecompositionDeclarator().bindings()) {
884 // Check for name conflicts.
885 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
886 IdentifierInfo *VarName = B.Name;
887 assert(VarName && "Cannot have an unnamed binding declaration");
888
889 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
890 RedeclarationKind::ForVisibleRedeclaration);
891 LookupName(R&: Previous, S,
892 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
893
894 // It's not permitted to shadow a template parameter name.
895 if (Previous.isSingleResult() &&
896 Previous.getFoundDecl()->isTemplateParameter()) {
897 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
898 Previous.clear();
899 }
900
901 QualType QT;
902 if (B.EllipsisLoc.isValid()) {
903 if (!cast<Decl>(Val: DC)->isTemplated())
904 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
905 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
906 /*ExpectsPackInType=*/ExpectPackInType: false);
907 }
908
909 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
910
911 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
912
913 // Find the shadowed declaration before filtering for scope.
914 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
915 ? getShadowedDeclaration(D: BD, R: Previous)
916 : nullptr;
917
918 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
919 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
920 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
921 /*AllowInlineNamespace*/false);
922
923 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
924 DC->isFunctionOrMethod() && VarName->isPlaceholder();
925 if (!Previous.empty()) {
926 if (IsPlaceholder) {
927 bool sameDC = (Previous.end() - 1)
928 ->getDeclContext()
929 ->getRedeclContext()
930 ->Equals(DC: DC->getRedeclContext());
931 if (sameDC &&
932 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
933 Previous.clear();
934 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
935 }
936 } else {
937 auto *Old = Previous.getRepresentativeDecl();
938 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
939 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
940 }
941 } else if (ShadowedDecl && !D.isRedeclaration()) {
942 CheckShadow(D: BD, ShadowedDecl, R: Previous);
943 }
944 PushOnScopeChains(D: BD, S, AddToContext: true);
945 Bindings.push_back(Elt: BD);
946 ParsingInitForAutoVars.insert(Ptr: BD);
947 }
948
949 // There are no prior lookup results for the variable itself, because it
950 // is unnamed.
951 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
952 Decomp.getLSquareLoc());
953 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
954 RedeclarationKind::ForVisibleRedeclaration);
955
956 // Build the variable that holds the non-decomposed object.
957 bool AddToScope = true;
958 NamedDecl *New =
959 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
960 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
961 if (AddToScope) {
962 S->AddDecl(D: New);
963 CurContext->addHiddenDecl(D: New);
964 }
965
966 if (OpenMP().isInOpenMPDeclareTargetContext())
967 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
968
969 return New;
970}
971
972// Check the arity of the structured bindings.
973// Create the resolved pack expr if needed.
974static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
975 QualType DecompType,
976 ArrayRef<BindingDecl *> Bindings,
977 unsigned MemberCount) {
978 auto BindingWithPackItr = llvm::find_if(
979 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
980 bool HasPack = BindingWithPackItr != Bindings.end();
981 bool IsValid;
982 if (!HasPack) {
983 IsValid = Bindings.size() == MemberCount;
984 } else {
985 // There may not be more members than non-pack bindings.
986 IsValid = MemberCount >= Bindings.size() - 1;
987 }
988
989 if (IsValid && HasPack) {
990 // Create the pack expr and assign it to the binding.
991 unsigned PackSize = MemberCount - Bindings.size() + 1;
992
993 BindingDecl *BPack = *BindingWithPackItr;
994 BPack->setDecomposedDecl(DD);
995 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
996 // Create the nested BindingDecls.
997 for (unsigned I = 0; I < PackSize; ++I) {
998 BindingDecl *NestedBD = BindingDecl::Create(
999 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
1000 Id: BPack->getIdentifier(), T: QualType());
1001 NestedBD->setDecomposedDecl(DD);
1002 NestedBDs[I] = NestedBD;
1003 }
1004
1005 QualType PackType = S.Context.getPackExpansionType(
1006 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
1007 auto *PackExpr = FunctionParmPackExpr::Create(
1008 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
1009 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
1010 }
1011
1012 if (IsValid)
1013 return false;
1014
1015 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
1016 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1017 << (MemberCount < Bindings.size());
1018 return true;
1019}
1020
1021static bool checkSimpleDecomposition(
1022 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1023 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1024 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1025 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1026 auto *DD = cast<DecompositionDecl>(Val: Src);
1027
1028 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1029 return true;
1030
1031 unsigned I = 0;
1032 for (auto *B : DD->flat_bindings()) {
1033 SourceLocation Loc = B->getLocation();
1034 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1035 if (E.isInvalid())
1036 return true;
1037 E = GetInit(Loc, E.get(), I++);
1038 if (E.isInvalid())
1039 return true;
1040 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1041 }
1042
1043 return false;
1044}
1045
1046static bool checkArrayLikeDecomposition(Sema &S,
1047 ArrayRef<BindingDecl *> Bindings,
1048 ValueDecl *Src, QualType DecompType,
1049 const llvm::APSInt &NumElems,
1050 QualType ElemType) {
1051 return checkSimpleDecomposition(
1052 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1053 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1054 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1055 if (E.isInvalid())
1056 return ExprError();
1057 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1058 });
1059}
1060
1061static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1062 ValueDecl *Src, QualType DecompType,
1063 const ConstantArrayType *CAT) {
1064 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1065 NumElems: llvm::APSInt(CAT->getSize()),
1066 ElemType: CAT->getElementType());
1067}
1068
1069static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1070 ValueDecl *Src, QualType DecompType,
1071 const VectorType *VT) {
1072 return checkArrayLikeDecomposition(
1073 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1074 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1075 Qs: DecompType.getQualifiers()));
1076}
1077
1078static bool checkComplexDecomposition(Sema &S,
1079 ArrayRef<BindingDecl *> Bindings,
1080 ValueDecl *Src, QualType DecompType,
1081 const ComplexType *CT) {
1082 return checkSimpleDecomposition(
1083 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1084 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1085 Qs: DecompType.getQualifiers()),
1086 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1087 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1088 });
1089}
1090
1091static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1092 TemplateArgumentListInfo &Args,
1093 const TemplateParameterList *Params) {
1094 SmallString<128> SS;
1095 llvm::raw_svector_ostream OS(SS);
1096 bool First = true;
1097 unsigned I = 0;
1098 for (auto &Arg : Args.arguments()) {
1099 if (!First)
1100 OS << ", ";
1101 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1102 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1103 Policy: PrintingPolicy, TPL: Params, Idx: I));
1104 First = false;
1105 I++;
1106 }
1107 return std::string(OS.str());
1108}
1109
1110static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1111 TemplateArgumentListInfo &Args, unsigned DiagID) {
1112 auto DiagnoseMissing = [&] {
1113 if (DiagID)
1114 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1115 Args, /*Params*/ nullptr);
1116 return QualType();
1117 };
1118
1119 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1120 NamespaceDecl *Std = S.getStdNamespace();
1121 if (!Std)
1122 return DiagnoseMissing();
1123
1124 // Look up the trait itself, within namespace std. We can diagnose various
1125 // problems with this lookup even if we've been asked to not diagnose a
1126 // missing specialization, because this can only fail if the user has been
1127 // declaring their own names in namespace std or we don't support the
1128 // standard library implementation in use.
1129 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1130 Sema::LookupOrdinaryName);
1131 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1132 return DiagnoseMissing();
1133 if (Result.isAmbiguous())
1134 return QualType();
1135
1136 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1137 if (!TraitTD) {
1138 Result.suppressDiagnostics();
1139 NamedDecl *Found = *Result.begin();
1140 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1141 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1142 return QualType();
1143 }
1144
1145 // Build the template-id.
1146 QualType TraitTy = S.CheckTemplateIdType(
1147 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1148 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1149 if (TraitTy.isNull())
1150 return QualType();
1151
1152 if (!S.isCompleteType(Loc, T: TraitTy)) {
1153 if (DiagID)
1154 S.RequireCompleteType(
1155 Loc, T: TraitTy, DiagID,
1156 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1157 Params: TraitTD->getTemplateParameters()));
1158 return QualType();
1159 }
1160 return TraitTy;
1161}
1162
1163static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1164 LookupResult &MemberLookup) {
1165 assert(RD && "specialization of class template is not a class?");
1166 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1167 return MemberLookup.isAmbiguous();
1168}
1169
1170static TemplateArgumentLoc
1171getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1172 uint64_t I) {
1173 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1174 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1175}
1176
1177static TemplateArgumentLoc
1178getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1179 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1180}
1181
1182namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1183
1184static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1185 unsigned &OutSize) {
1186 EnterExpressionEvaluationContext ContextRAII(
1187 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1188
1189 // Form template argument list for tuple_size<T>.
1190 TemplateArgumentListInfo Args(Loc, Loc);
1191 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1192
1193 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1194 if (TraitTy.isNull())
1195 return IsTupleLike::NotTupleLike;
1196
1197 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1198 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1199
1200 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1201 // it's not tuple-like.
1202 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1203 return IsTupleLike::NotTupleLike;
1204
1205 // If we get this far, we've committed to the tuple interpretation, but
1206 // we can still fail if there actually isn't a usable ::value.
1207
1208 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1209 LookupResult &R;
1210 TemplateArgumentListInfo &Args;
1211 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1212 : R(R), Args(Args) {}
1213 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1214 SourceLocation Loc) override {
1215 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1216 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1217 /*Params*/ nullptr);
1218 }
1219 } Diagnoser(R, Args);
1220
1221 ExprResult E =
1222 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1223 if (E.isInvalid())
1224 return IsTupleLike::Error;
1225
1226 llvm::APSInt Size;
1227 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1228 if (E.isInvalid())
1229 return IsTupleLike::Error;
1230
1231 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1232 // an UnsignedOrNone.
1233 if (Size < 0 || Size >= UINT_MAX) {
1234 llvm::SmallVector<char, 16> Str;
1235 Size.toString(Str);
1236 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1237 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1238 /*Params=*/nullptr)
1239 << StringRef(Str.data(), Str.size());
1240 return IsTupleLike::Error;
1241 }
1242
1243 OutSize = Size.getExtValue();
1244 return IsTupleLike::TupleLike;
1245}
1246
1247/// \return std::tuple_element<I, T>::type.
1248static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1249 unsigned I, QualType T) {
1250 // Form template argument list for tuple_element<I, T>.
1251 TemplateArgumentListInfo Args(Loc, Loc);
1252 Args.addArgument(
1253 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1254 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1255
1256 QualType TraitTy =
1257 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1258 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1259 if (TraitTy.isNull())
1260 return QualType();
1261
1262 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1263 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1264 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1265 return QualType();
1266
1267 auto *TD = R.getAsSingle<TypeDecl>();
1268 if (!TD) {
1269 R.suppressDiagnostics();
1270 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1271 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1272 /*Params*/ nullptr);
1273 if (!R.empty())
1274 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1275 return QualType();
1276 }
1277
1278 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1279 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1280}
1281
1282namespace {
1283struct InitializingBinding {
1284 Sema &S;
1285 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1286 Sema::CodeSynthesisContext Ctx;
1287 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1288 Ctx.PointOfInstantiation = BD->getLocation();
1289 Ctx.Entity = BD;
1290 S.pushCodeSynthesisContext(Ctx);
1291 }
1292 ~InitializingBinding() {
1293 S.popCodeSynthesisContext();
1294 }
1295};
1296}
1297
1298static bool checkTupleLikeDecomposition(Sema &S,
1299 ArrayRef<BindingDecl *> Bindings,
1300 VarDecl *Src, QualType DecompType,
1301 unsigned NumElems) {
1302 auto *DD = cast<DecompositionDecl>(Val: Src);
1303 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1304 return true;
1305
1306 if (Bindings.empty())
1307 return false;
1308
1309 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1310
1311 // [dcl.decomp]p3:
1312 // The unqualified-id get is looked up in the scope of E by class member
1313 // access lookup ...
1314 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1315 bool UseMemberGet = false;
1316 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1317 if (auto *RD = DecompType->getAsCXXRecordDecl())
1318 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1319 if (MemberGet.isAmbiguous())
1320 return true;
1321 // ... and if that finds at least one declaration that is a function
1322 // template whose first template parameter is a non-type parameter ...
1323 for (NamedDecl *D : MemberGet) {
1324 if (FunctionTemplateDecl *FTD =
1325 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1326 TemplateParameterList *TPL = FTD->getTemplateParameters();
1327 if (TPL->size() != 0 &&
1328 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1329 // ... the initializer is e.get<i>().
1330 UseMemberGet = true;
1331 break;
1332 }
1333 }
1334 }
1335 }
1336
1337 unsigned I = 0;
1338 for (auto *B : DD->flat_bindings()) {
1339 InitializingBinding InitContext(S, B);
1340 SourceLocation Loc = B->getLocation();
1341
1342 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1343 if (E.isInvalid())
1344 return true;
1345
1346 // e is an lvalue if the type of the entity is an lvalue reference and
1347 // an xvalue otherwise
1348 if (!Src->getType()->isLValueReferenceType())
1349 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1350 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1351 FPO: FPOptionsOverride());
1352
1353 TemplateArgumentListInfo Args(Loc, Loc);
1354 Args.addArgument(
1355 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1356
1357 if (UseMemberGet) {
1358 // if [lookup of member get] finds at least one declaration, the
1359 // initializer is e.get<i-1>().
1360 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1361 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1362 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1363 if (E.isInvalid())
1364 return true;
1365
1366 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1367 } else {
1368 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1369 // in the associated namespaces.
1370 Expr *Get = UnresolvedLookupExpr::Create(
1371 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1372 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1373 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1374 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1375
1376 Expr *Arg = E.get();
1377 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1378 }
1379 if (E.isInvalid())
1380 return true;
1381 Expr *Init = E.get();
1382
1383 // Given the type T designated by std::tuple_element<i - 1, E>::type
1384 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1385 if (T.isNull())
1386 return true;
1387
1388 // C++26 [dcl.struct.bind]p7:
1389 // and the type Ui, defined as Ti if the initializer is a prvalue,
1390 // as "lvalue reference to Ti" if the initializer is an lvalue,
1391 // or as "rvalue reference to Ti" otherwise
1392 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1393 QualType U = E.get()->isPRValue()
1394 ? T
1395 : S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc,
1396 Entity: B->getDeclName());
1397 if (U.isNull())
1398 return true;
1399
1400 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1401 // entity and this type was never written in source code.
1402 auto *BindingVD =
1403 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1404 Id: B->getDeclName().getAsIdentifierInfo(), T: U,
1405 /*TInfo=*/nullptr, S: Src->getStorageClass());
1406 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1407 BindingVD->setTSCSpec(Src->getTSCSpec());
1408 BindingVD->setConstexpr(Src->isConstexpr());
1409 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1410 BindingVD->addAttr(A: CIAttr->clone(C&: S.Context));
1411 BindingVD->setImplicit();
1412 if (Src->isInlineSpecified())
1413 BindingVD->setInlineSpecified();
1414 BindingVD->getLexicalDeclContext()->addHiddenDecl(D: BindingVD);
1415
1416 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: BindingVD);
1417 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1418 InitializationSequence Seq(S, Entity, Kind, Init);
1419 E = Seq.Perform(S, Entity, Kind, Args: Init);
1420 if (E.isInvalid())
1421 return true;
1422 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1423 if (E.isInvalid())
1424 return true;
1425 BindingVD->setInit(E.get());
1426 S.CheckCompleteVariableDeclaration(VD: BindingVD);
1427
1428 E = S.BuildDeclarationNameExpr(
1429 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(B->getDeclName(), Loc), D: BindingVD);
1430 if (E.isInvalid())
1431 return true;
1432
1433 B->setBinding(DeclaredType: T, Binding: E.get());
1434 I++;
1435 }
1436
1437 return false;
1438}
1439
1440/// Find the base class to decompose in a built-in decomposition of a class type.
1441/// This base class search is, unfortunately, not quite like any other that we
1442/// perform anywhere else in C++.
1443static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1444 const CXXRecordDecl *RD,
1445 CXXCastPath &BasePath) {
1446 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1447 CXXBasePath &Path) {
1448 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1449 };
1450
1451 const CXXRecordDecl *ClassWithFields = nullptr;
1452 AccessSpecifier AS = AS_public;
1453 if (RD->hasDirectFields())
1454 // [dcl.decomp]p4:
1455 // Otherwise, all of E's non-static data members shall be public direct
1456 // members of E ...
1457 ClassWithFields = RD;
1458 else {
1459 // ... or of ...
1460 CXXBasePaths Paths;
1461 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1462 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1463 // If no classes have fields, just decompose RD itself. (This will work
1464 // if and only if zero bindings were provided.)
1465 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1466 }
1467
1468 CXXBasePath *BestPath = nullptr;
1469 for (auto &P : Paths) {
1470 if (!BestPath)
1471 BestPath = &P;
1472 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1473 T2: BestPath->back().Base->getType())) {
1474 // ... the same ...
1475 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1476 << false << RD << BestPath->back().Base->getType()
1477 << P.back().Base->getType();
1478 return DeclAccessPair();
1479 } else if (P.Access < BestPath->Access) {
1480 BestPath = &P;
1481 }
1482 }
1483
1484 // ... unambiguous ...
1485 QualType BaseType = BestPath->back().Base->getType();
1486 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1487 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1488 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1489 return DeclAccessPair();
1490 }
1491
1492 // ... [accessible, implied by other rules] base class of E.
1493 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1494 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1495 AS = BestPath->Access;
1496
1497 ClassWithFields = BaseType->getAsCXXRecordDecl();
1498 S.BuildBasePathArray(Paths, BasePath);
1499 }
1500
1501 // The above search did not check whether the selected class itself has base
1502 // classes with fields, so check that now.
1503 CXXBasePaths Paths;
1504 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1505 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1506 << (ClassWithFields == RD) << RD << ClassWithFields
1507 << Paths.front().back().Base->getType();
1508 return DeclAccessPair();
1509 }
1510
1511 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1512}
1513
1514static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1515 const CXXRecordDecl *OrigRD,
1516 QualType DecompType,
1517 DeclAccessPair BasePair) {
1518 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1519 if (!RD)
1520 return true;
1521
1522 for (auto *FD : RD->fields()) {
1523 if (FD->isUnnamedBitField())
1524 continue;
1525
1526 // All the non-static data members are required to be nameable, so they
1527 // must all have names.
1528 if (!FD->getDeclName()) {
1529 if (RD->isLambda()) {
1530 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1531 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1532 return true;
1533 }
1534
1535 if (FD->isAnonymousStructOrUnion()) {
1536 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1537 << DecompType << FD->getType()->isUnionType();
1538 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1539 return true;
1540 }
1541
1542 // FIXME: Are there any other ways we could have an anonymous member?
1543 }
1544 // The field must be accessible in the context of the structured binding.
1545 // We already checked that the base class is accessible.
1546 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1547 // const_cast here.
1548 S.CheckStructuredBindingMemberAccess(
1549 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1550 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1551 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1552 }
1553 return false;
1554}
1555
1556static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1557 ValueDecl *Src, QualType DecompType,
1558 const CXXRecordDecl *OrigRD) {
1559 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1560 DiagID: diag::err_incomplete_type))
1561 return true;
1562
1563 CXXCastPath BasePath;
1564 DeclAccessPair BasePair =
1565 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1566 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1567 if (!RD)
1568 return true;
1569 QualType BaseType = S.Context.getQualifiedType(
1570 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1571
1572 auto *DD = cast<DecompositionDecl>(Val: Src);
1573 unsigned NumFields = llvm::count_if(
1574 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1575 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1576 return true;
1577
1578 // all of E's non-static data members shall be [...] well-formed
1579 // when named as e.name in the context of the structured binding,
1580 // E shall not have an anonymous union member, ...
1581 auto FlatBindings = DD->flat_bindings();
1582 assert(llvm::range_size(FlatBindings) == NumFields);
1583 auto FlatBindingsItr = FlatBindings.begin();
1584
1585 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1586 BasePair))
1587 return true;
1588
1589 for (auto *FD : RD->fields()) {
1590 if (FD->isUnnamedBitField())
1591 continue;
1592
1593 // We have a real field to bind.
1594 assert(FlatBindingsItr != FlatBindings.end());
1595 BindingDecl *B = *(FlatBindingsItr++);
1596 SourceLocation Loc = B->getLocation();
1597
1598 // Initialize the binding to Src.FD.
1599 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1600 if (E.isInvalid())
1601 return true;
1602 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1603 VK: VK_LValue, BasePath: &BasePath);
1604 if (E.isInvalid())
1605 return true;
1606 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1607 SS: CXXScopeSpec(), Field: FD,
1608 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1609 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1610 if (E.isInvalid())
1611 return true;
1612
1613 // If the type of the member is T, the referenced type is cv T, where cv is
1614 // the cv-qualification of the decomposition expression.
1615 //
1616 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1617 // 'const' to the type of the field.
1618 Qualifiers Q = DecompType.getQualifiers();
1619 if (FD->isMutable())
1620 Q.removeConst();
1621 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1622 }
1623
1624 return false;
1625}
1626
1627void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1628 QualType DecompType = DD->getType();
1629
1630 // If the type of the decomposition is dependent, then so is the type of
1631 // each binding.
1632 if (DecompType->isDependentType()) {
1633 // Note that all of the types are still Null or PackExpansionType.
1634 for (auto *B : DD->bindings()) {
1635 // Do not overwrite any pack type.
1636 if (B->getType().isNull())
1637 B->setType(Context.DependentTy);
1638 }
1639 return;
1640 }
1641
1642 DecompType = DecompType.getNonReferenceType();
1643 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1644
1645 // C++1z [dcl.decomp]/2:
1646 // If E is an array type [...]
1647 // As an extension, we also support decomposition of built-in complex and
1648 // vector types.
1649 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1650 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1651 DD->setInvalidDecl();
1652 return;
1653 }
1654 if (auto *VT = DecompType->getAs<VectorType>()) {
1655 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1656 DD->setInvalidDecl();
1657 return;
1658 }
1659 if (auto *CT = DecompType->getAs<ComplexType>()) {
1660 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1661 DD->setInvalidDecl();
1662 return;
1663 }
1664
1665 // C++1z [dcl.decomp]/3:
1666 // if the expression std::tuple_size<E>::value is a well-formed integral
1667 // constant expression, [...]
1668 unsigned TupleSize;
1669 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1670 case IsTupleLike::Error:
1671 DD->setInvalidDecl();
1672 return;
1673
1674 case IsTupleLike::TupleLike:
1675 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1676 DD->setInvalidDecl();
1677 return;
1678
1679 case IsTupleLike::NotTupleLike:
1680 break;
1681 }
1682
1683 // C++1z [dcl.dcl]/8:
1684 // [E shall be of array or non-union class type]
1685 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1686 if (!RD || RD->isUnion()) {
1687 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1688 << DD << !RD << DecompType;
1689 DD->setInvalidDecl();
1690 return;
1691 }
1692
1693 // C++1z [dcl.decomp]/4:
1694 // all of E's non-static data members shall be [...] direct members of
1695 // E or of the same unambiguous public base class of E, ...
1696 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1697 DD->setInvalidDecl();
1698}
1699
1700UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1701 SourceLocation Loc) {
1702 const ASTContext &Ctx = getASTContext();
1703 assert(!T->isDependentType());
1704
1705 Qualifiers Quals;
1706 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1707 Quals.removeCVRQualifiers();
1708 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1709
1710 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1711 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1712 if (auto *VT = T->getAs<VectorType>())
1713 return VT->getNumElements();
1714 if (T->getAs<ComplexType>())
1715 return 2u;
1716
1717 unsigned TupleSize;
1718 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1719 case IsTupleLike::Error:
1720 return std::nullopt;
1721 case IsTupleLike::TupleLike:
1722 return TupleSize;
1723 case IsTupleLike::NotTupleLike:
1724 break;
1725 }
1726
1727 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1728 if (!OrigRD || OrigRD->isUnion())
1729 return std::nullopt;
1730
1731 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1732 return std::nullopt;
1733
1734 CXXCastPath BasePath;
1735 DeclAccessPair BasePair =
1736 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1737 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1738 if (!RD)
1739 return std::nullopt;
1740
1741 unsigned NumFields = llvm::count_if(
1742 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1743
1744 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1745 return std::nullopt;
1746
1747 return NumFields;
1748}
1749
1750void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1751 // Shortcut if exceptions are disabled.
1752 if (!getLangOpts().CXXExceptions)
1753 return;
1754
1755 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1756 "Should only be called if types are otherwise the same.");
1757
1758 QualType NewType = New->getType();
1759 QualType OldType = Old->getType();
1760
1761 // We're only interested in pointers and references to functions, as well
1762 // as pointers to member functions.
1763 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1764 NewType = R->getPointeeType();
1765 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1766 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1767 NewType = P->getPointeeType();
1768 OldType = OldType->castAs<PointerType>()->getPointeeType();
1769 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1770 NewType = M->getPointeeType();
1771 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1772 }
1773
1774 if (!NewType->isFunctionProtoType())
1775 return;
1776
1777 // There's lots of special cases for functions. For function pointers, system
1778 // libraries are hopefully not as broken so that we don't need these
1779 // workarounds.
1780 if (CheckEquivalentExceptionSpec(
1781 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1782 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1783 New->setInvalidDecl();
1784 }
1785}
1786
1787/// CheckCXXDefaultArguments - Verify that the default arguments for a
1788/// function declaration are well-formed according to C++
1789/// [dcl.fct.default].
1790void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1791 // This checking doesn't make sense for explicit specializations; their
1792 // default arguments are determined by the declaration we're specializing,
1793 // not by FD.
1794 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1795 return;
1796 if (auto *FTD = FD->getDescribedFunctionTemplate())
1797 if (FTD->isMemberSpecialization())
1798 return;
1799
1800 unsigned NumParams = FD->getNumParams();
1801 unsigned ParamIdx = 0;
1802
1803 // Find first parameter with a default argument
1804 for (; ParamIdx < NumParams; ++ParamIdx) {
1805 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1806 if (Param->hasDefaultArg())
1807 break;
1808 }
1809
1810 // C++20 [dcl.fct.default]p4:
1811 // In a given function declaration, each parameter subsequent to a parameter
1812 // with a default argument shall have a default argument supplied in this or
1813 // a previous declaration, unless the parameter was expanded from a
1814 // parameter pack, or shall be a function parameter pack.
1815 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1816 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1817 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1818 (CurrentInstantiationScope &&
1819 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1820 continue;
1821 if (Param->isInvalidDecl())
1822 /* We already complained about this parameter. */;
1823 else if (Param->getIdentifier())
1824 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1825 << Param->getIdentifier();
1826 else
1827 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1828 }
1829}
1830
1831/// Check that the given type is a literal type. Issue a diagnostic if not,
1832/// if Kind is Diagnose.
1833/// \return \c true if a problem has been found (and optionally diagnosed).
1834template <typename... Ts>
1835static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1836 SourceLocation Loc, QualType T, unsigned DiagID,
1837 Ts &&...DiagArgs) {
1838 if (T->isDependentType())
1839 return false;
1840
1841 switch (Kind) {
1842 case Sema::CheckConstexprKind::Diagnose:
1843 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1844 std::forward<Ts>(DiagArgs)...);
1845
1846 case Sema::CheckConstexprKind::CheckValid:
1847 return !T->isLiteralType(Ctx: SemaRef.Context);
1848 }
1849
1850 llvm_unreachable("unknown CheckConstexprKind");
1851}
1852
1853/// Determine whether a destructor cannot be constexpr due to
1854static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1855 const CXXDestructorDecl *DD,
1856 Sema::CheckConstexprKind Kind) {
1857 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1858 "this check is obsolete for C++23");
1859 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1860 const CXXRecordDecl *RD =
1861 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1862 if (!RD || RD->hasConstexprDestructor())
1863 return true;
1864
1865 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1867 << static_cast<int>(DD->getConstexprKind()) << !FD
1868 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1869 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1870 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1871 }
1872 return false;
1873 };
1874
1875 const CXXRecordDecl *RD = DD->getParent();
1876 for (const CXXBaseSpecifier &B : RD->bases())
1877 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1878 return false;
1879 for (const FieldDecl *FD : RD->fields())
1880 if (!Check(FD->getLocation(), FD->getType(), FD))
1881 return false;
1882 return true;
1883}
1884
1885/// Check whether a function's parameter types are all literal types. If so,
1886/// return true. If not, produce a suitable diagnostic and return false.
1887static bool CheckConstexprParameterTypes(Sema &SemaRef,
1888 const FunctionDecl *FD,
1889 Sema::CheckConstexprKind Kind) {
1890 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1891 "this check is obsolete for C++23");
1892 unsigned ArgIndex = 0;
1893 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1894 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1895 e = FT->param_type_end();
1896 i != e; ++i, ++ArgIndex) {
1897 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1898 assert(PD && "null in a parameter list");
1899 SourceLocation ParamLoc = PD->getLocation();
1900 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1901 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1902 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1903 DiagArgs: FD->isConsteval()))
1904 return false;
1905 }
1906 return true;
1907}
1908
1909/// Check whether a function's return type is a literal type. If so, return
1910/// true. If not, produce a suitable diagnostic and return false.
1911static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1912 Sema::CheckConstexprKind Kind) {
1913 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1914 "this check is obsolete for C++23");
1915 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1916 DiagID: diag::err_constexpr_non_literal_return,
1917 DiagArgs: FD->isConsteval()))
1918 return false;
1919 return true;
1920}
1921
1922/// Get diagnostic %select index for tag kind for
1923/// record diagnostic message.
1924/// WARNING: Indexes apply to particular diagnostics only!
1925///
1926/// \returns diagnostic %select index.
1927static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1928 switch (Tag) {
1929 case TagTypeKind::Struct:
1930 return 0;
1931 case TagTypeKind::Interface:
1932 return 1;
1933 case TagTypeKind::Class:
1934 return 2;
1935 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1936 }
1937}
1938
1939static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1940 Stmt *Body,
1941 Sema::CheckConstexprKind Kind);
1942static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1943
1944bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1945 CheckConstexprKind Kind) {
1946 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1947 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1948 // C++11 [dcl.constexpr]p4:
1949 // The definition of a constexpr constructor shall satisfy the following
1950 // constraints:
1951 // - the class shall not have any virtual base classes;
1952 //
1953 // FIXME: This only applies to constructors and destructors, not arbitrary
1954 // member functions.
1955 const CXXRecordDecl *RD = MD->getParent();
1956 if (RD->getNumVBases()) {
1957 if (Kind == CheckConstexprKind::CheckValid)
1958 return false;
1959
1960 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1961 << isa<CXXConstructorDecl>(Val: NewFD)
1962 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1963 for (const auto &I : RD->vbases())
1964 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1965 << I.getSourceRange();
1966 return false;
1967 }
1968 }
1969
1970 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1971 // C++11 [dcl.constexpr]p3:
1972 // The definition of a constexpr function shall satisfy the following
1973 // constraints:
1974 // - it shall not be virtual; (removed in C++20)
1975 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
1976 if (Method && Method->isVirtual()) {
1977 if (getLangOpts().CPlusPlus20) {
1978 if (Kind == CheckConstexprKind::Diagnose)
1979 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
1980 } else {
1981 if (Kind == CheckConstexprKind::CheckValid)
1982 return false;
1983
1984 Method = Method->getCanonicalDecl();
1985 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
1986
1987 // If it's not obvious why this function is virtual, find an overridden
1988 // function which uses the 'virtual' keyword.
1989 const CXXMethodDecl *WrittenVirtual = Method;
1990 while (!WrittenVirtual->isVirtualAsWritten())
1991 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1992 if (WrittenVirtual != Method)
1993 Diag(Loc: WrittenVirtual->getLocation(),
1994 DiagID: diag::note_overridden_virtual_function);
1995 return false;
1996 }
1997 }
1998
1999 // - its return type shall be a literal type; (removed in C++23)
2000 if (!getLangOpts().CPlusPlus23 &&
2001 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
2002 return false;
2003 }
2004
2005 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
2006 // A destructor can be constexpr only if the defaulted destructor could be;
2007 // we don't need to check the members and bases if we already know they all
2008 // have constexpr destructors. (removed in C++23)
2009 if (!getLangOpts().CPlusPlus23 &&
2010 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2011 if (Kind == CheckConstexprKind::CheckValid)
2012 return false;
2013 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
2014 return false;
2015 }
2016 }
2017
2018 // - each of its parameter types shall be a literal type; (removed in C++23)
2019 if (!getLangOpts().CPlusPlus23 &&
2020 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
2021 return false;
2022
2023 Stmt *Body = NewFD->getBody();
2024 assert(Body &&
2025 "CheckConstexprFunctionDefinition called on function with no body");
2026 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2027}
2028
2029/// Check the given declaration statement is legal within a constexpr function
2030/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2031///
2032/// \return true if the body is OK (maybe only as an extension), false if we
2033/// have diagnosed a problem.
2034static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2035 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2036 Sema::CheckConstexprKind Kind) {
2037 // C++11 [dcl.constexpr]p3 and p4:
2038 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2039 // contain only
2040 for (const auto *DclIt : DS->decls()) {
2041 switch (DclIt->getKind()) {
2042 case Decl::StaticAssert:
2043 case Decl::Using:
2044 case Decl::UsingShadow:
2045 case Decl::UsingDirective:
2046 case Decl::UnresolvedUsingTypename:
2047 case Decl::UnresolvedUsingValue:
2048 case Decl::UsingEnum:
2049 // - static_assert-declarations
2050 // - using-declarations,
2051 // - using-directives,
2052 // - using-enum-declaration
2053 continue;
2054
2055 case Decl::CXXExpansionStmt:
2056 continue;
2057
2058 case Decl::Typedef:
2059 case Decl::TypeAlias: {
2060 // - typedef declarations and alias-declarations that do not define
2061 // classes or enumerations,
2062 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2063 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2064 // Don't allow variably-modified types in constexpr functions.
2065 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2066 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2067 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2068 << TL.getSourceRange() << TL.getType()
2069 << isa<CXXConstructorDecl>(Val: Dcl);
2070 }
2071 return false;
2072 }
2073 continue;
2074 }
2075
2076 case Decl::Enum:
2077 case Decl::CXXRecord:
2078 // C++1y allows types to be defined, not just declared.
2079 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2080 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2081 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2082 CompatDiagId: diag_compat::constexpr_type_definition)
2083 << isa<CXXConstructorDecl>(Val: Dcl);
2084 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2085 return false;
2086 }
2087 }
2088 continue;
2089
2090 case Decl::EnumConstant:
2091 case Decl::IndirectField:
2092 case Decl::ParmVar:
2093 // These can only appear with other declarations which are banned in
2094 // C++11 and permitted in C++1y, so ignore them.
2095 continue;
2096
2097 case Decl::Var:
2098 case Decl::Decomposition: {
2099 // C++1y [dcl.constexpr]p3 allows anything except:
2100 // a definition of a variable of non-literal type or of static or
2101 // thread storage duration or [before C++2a] for which no
2102 // initialization is performed.
2103 const auto *VD = cast<VarDecl>(Val: DclIt);
2104 if (VD->isThisDeclarationADefinition()) {
2105 if (VD->isStaticLocal()) {
2106 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2107 SemaRef.DiagCompat(Loc: VD->getLocation(),
2108 CompatDiagId: diag_compat::constexpr_static_var)
2109 << isa<CXXConstructorDecl>(Val: Dcl)
2110 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2111 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2112 return false;
2113 }
2114 }
2115 if (SemaRef.LangOpts.CPlusPlus23) {
2116 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2117 DiagID: diag::warn_cxx20_compat_constexpr_var,
2118 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2119 } else if (CheckLiteralType(
2120 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2121 DiagID: diag::err_constexpr_local_var_non_literal_type,
2122 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2123 return false;
2124 }
2125 if (!VD->getType()->isDependentType() &&
2126 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2127 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2128 SemaRef.DiagCompat(Loc: VD->getLocation(),
2129 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2130 << isa<CXXConstructorDecl>(Val: Dcl);
2131 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2132 return false;
2133 }
2134 continue;
2135 }
2136 }
2137 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2138 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2139 << isa<CXXConstructorDecl>(Val: Dcl);
2140 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2141 return false;
2142 }
2143 continue;
2144 }
2145
2146 case Decl::NamespaceAlias:
2147 case Decl::Function:
2148 // These are disallowed in C++11 and permitted in C++1y. Allow them
2149 // everywhere as an extension.
2150 if (!Cxx1yLoc.isValid())
2151 Cxx1yLoc = DS->getBeginLoc();
2152 continue;
2153
2154 default:
2155 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2156 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2157 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2158 }
2159 return false;
2160 }
2161 }
2162
2163 return true;
2164}
2165
2166/// Check that the given field is initialized within a constexpr constructor.
2167///
2168/// \param Dcl The constexpr constructor being checked.
2169/// \param Field The field being checked. This may be a member of an anonymous
2170/// struct or union nested within the class being checked.
2171/// \param Inits All declarations, including anonymous struct/union members and
2172/// indirect members, for which any initialization was provided.
2173/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2174/// multiple notes for different members to the same error.
2175/// \param Kind Whether we're diagnosing a constructor as written or determining
2176/// whether the formal requirements are satisfied.
2177/// \return \c false if we're checking for validity and the constructor does
2178/// not satisfy the requirements on a constexpr constructor.
2179static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2180 const FunctionDecl *Dcl,
2181 FieldDecl *Field,
2182 llvm::SmallPtrSet<Decl *, 16> &Inits,
2183 bool &Diagnosed,
2184 Sema::CheckConstexprKind Kind) {
2185 // In C++20 onwards, there's nothing to check for validity.
2186 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2187 SemaRef.getLangOpts().CPlusPlus20)
2188 return true;
2189
2190 if (Field->isInvalidDecl())
2191 return true;
2192
2193 if (Field->isUnnamedBitField())
2194 return true;
2195
2196 // Anonymous unions with no variant members and empty anonymous structs do not
2197 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2198 // indirect fields don't need initializing.
2199 if (Field->isAnonymousStructOrUnion() &&
2200 (Field->getType()->isUnionType()
2201 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2202 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2203 return true;
2204
2205 if (!Inits.count(Ptr: Field)) {
2206 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2207 if (!Diagnosed) {
2208 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2209 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2210 Diagnosed = true;
2211 }
2212 SemaRef.Diag(Loc: Field->getLocation(),
2213 DiagID: diag::note_constexpr_ctor_missing_init);
2214 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2215 return false;
2216 }
2217 } else if (Field->isAnonymousStructOrUnion()) {
2218 const auto *RD = Field->getType()->castAsRecordDecl();
2219 for (auto *I : RD->fields())
2220 // If an anonymous union contains an anonymous struct of which any member
2221 // is initialized, all members must be initialized.
2222 if (!RD->isUnion() || Inits.count(Ptr: I))
2223 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2224 Kind))
2225 return false;
2226 }
2227 return true;
2228}
2229
2230/// Check the provided statement is allowed in a constexpr function
2231/// definition.
2232static bool
2233CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2234 SmallVectorImpl<SourceLocation> &ReturnStmts,
2235 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2236 SourceLocation &Cxx2bLoc,
2237 Sema::CheckConstexprKind Kind) {
2238 // - its function-body shall be [...] a compound-statement that contains only
2239 switch (S->getStmtClass()) {
2240 case Stmt::NullStmtClass:
2241 // - null statements,
2242 return true;
2243
2244 case Stmt::DeclStmtClass:
2245 // - static_assert-declarations
2246 // - using-declarations,
2247 // - using-directives,
2248 // - typedef declarations and alias-declarations that do not define
2249 // classes or enumerations,
2250 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2251 return false;
2252 return true;
2253
2254 case Stmt::ReturnStmtClass:
2255 // - and exactly one return statement;
2256 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2257 // C++1y allows return statements in constexpr constructors.
2258 if (!Cxx1yLoc.isValid())
2259 Cxx1yLoc = S->getBeginLoc();
2260 return true;
2261 }
2262
2263 ReturnStmts.push_back(Elt: S->getBeginLoc());
2264 return true;
2265
2266 case Stmt::AttributedStmtClass:
2267 // Attributes on a statement don't affect its formal kind and hence don't
2268 // affect its validity in a constexpr function.
2269 return CheckConstexprFunctionStmt(
2270 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2271 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2272
2273 case Stmt::CompoundStmtClass: {
2274 // C++1y allows compound-statements.
2275 if (!Cxx1yLoc.isValid())
2276 Cxx1yLoc = S->getBeginLoc();
2277
2278 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2279 for (auto *BodyIt : CompStmt->body()) {
2280 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2281 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2282 return false;
2283 }
2284 return true;
2285 }
2286
2287 case Stmt::IfStmtClass: {
2288 // C++1y allows if-statements.
2289 if (!Cxx1yLoc.isValid())
2290 Cxx1yLoc = S->getBeginLoc();
2291
2292 IfStmt *If = cast<IfStmt>(Val: S);
2293 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2294 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2295 return false;
2296 if (If->getElse() &&
2297 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2298 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2299 return false;
2300 return true;
2301 }
2302
2303 case Stmt::WhileStmtClass:
2304 case Stmt::DoStmtClass:
2305 case Stmt::ForStmtClass:
2306 case Stmt::CXXForRangeStmtClass:
2307 case Stmt::ContinueStmtClass:
2308 // C++1y allows all of these. We don't allow them as extensions in C++11,
2309 // because they don't make sense without variable mutation.
2310 if (!SemaRef.getLangOpts().CPlusPlus14)
2311 break;
2312 if (!Cxx1yLoc.isValid())
2313 Cxx1yLoc = S->getBeginLoc();
2314 for (Stmt *SubStmt : S->children()) {
2315 if (SubStmt &&
2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2318 return false;
2319 }
2320 return true;
2321
2322 case Stmt::SwitchStmtClass:
2323 case Stmt::CaseStmtClass:
2324 case Stmt::DefaultStmtClass:
2325 case Stmt::BreakStmtClass:
2326 // C++1y allows switch-statements, and since they don't need variable
2327 // mutation, we can reasonably allow them in C++11 as an extension.
2328 if (!Cxx1yLoc.isValid())
2329 Cxx1yLoc = S->getBeginLoc();
2330 for (Stmt *SubStmt : S->children()) {
2331 if (SubStmt &&
2332 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2333 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2334 return false;
2335 }
2336 return true;
2337
2338 case Stmt::LabelStmtClass:
2339 case Stmt::GotoStmtClass:
2340 if (Cxx2bLoc.isInvalid())
2341 Cxx2bLoc = S->getBeginLoc();
2342 for (Stmt *SubStmt : S->children()) {
2343 if (SubStmt &&
2344 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2345 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2346 return false;
2347 }
2348 return true;
2349
2350 case Stmt::GCCAsmStmtClass:
2351 case Stmt::MSAsmStmtClass:
2352 // C++2a allows inline assembly statements.
2353 case Stmt::CXXTryStmtClass:
2354 if (Cxx2aLoc.isInvalid())
2355 Cxx2aLoc = S->getBeginLoc();
2356 for (Stmt *SubStmt : S->children()) {
2357 if (SubStmt &&
2358 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2359 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2360 return false;
2361 }
2362 return true;
2363
2364 case Stmt::CXXCatchStmtClass:
2365 // Do not bother checking the language mode (already covered by the
2366 // try block check).
2367 if (!CheckConstexprFunctionStmt(
2368 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2369 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2370 return false;
2371 return true;
2372
2373 default:
2374 if (!isa<Expr>(Val: S))
2375 break;
2376
2377 // C++1y allows expression-statements.
2378 if (!Cxx1yLoc.isValid())
2379 Cxx1yLoc = S->getBeginLoc();
2380 return true;
2381 }
2382
2383 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2384 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2385 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2386 }
2387 return false;
2388}
2389
2390/// Check the body for the given constexpr function declaration only contains
2391/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2392///
2393/// \return true if the body is OK, false if we have found or diagnosed a
2394/// problem.
2395static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2396 Stmt *Body,
2397 Sema::CheckConstexprKind Kind) {
2398 SmallVector<SourceLocation, 4> ReturnStmts;
2399
2400 if (isa<CXXTryStmt>(Val: Body)) {
2401 // C++11 [dcl.constexpr]p3:
2402 // The definition of a constexpr function shall satisfy the following
2403 // constraints: [...]
2404 // - its function-body shall be = delete, = default, or a
2405 // compound-statement
2406 //
2407 // C++11 [dcl.constexpr]p4:
2408 // In the definition of a constexpr constructor, [...]
2409 // - its function-body shall not be a function-try-block;
2410 //
2411 // This restriction is lifted in C++2a, as long as inner statements also
2412 // apply the general constexpr rules.
2413 switch (Kind) {
2414 case Sema::CheckConstexprKind::CheckValid:
2415 if (!SemaRef.getLangOpts().CPlusPlus20)
2416 return false;
2417 break;
2418
2419 case Sema::CheckConstexprKind::Diagnose:
2420 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2421 CompatDiagId: diag_compat::constexpr_function_try_block)
2422 << isa<CXXConstructorDecl>(Val: Dcl);
2423 break;
2424 }
2425 }
2426
2427 // - its function-body shall be [...] a compound-statement that contains only
2428 // [... list of cases ...]
2429 //
2430 // Note that walking the children here is enough to properly check for
2431 // CompoundStmt and CXXTryStmt body.
2432 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2433 for (Stmt *SubStmt : Body->children()) {
2434 if (SubStmt &&
2435 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2436 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2437 return false;
2438 }
2439
2440 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2441 // If this is only valid as an extension, report that we don't satisfy the
2442 // constraints of the current language.
2443 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2444 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2445 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2446 return false;
2447 } else if (Cxx2bLoc.isValid()) {
2448 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2449 << isa<CXXConstructorDecl>(Val: Dcl);
2450 } else if (Cxx2aLoc.isValid()) {
2451 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2452 << isa<CXXConstructorDecl>(Val: Dcl);
2453 } else if (Cxx1yLoc.isValid()) {
2454 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2455 << isa<CXXConstructorDecl>(Val: Dcl);
2456 }
2457
2458 if (const CXXConstructorDecl *Constructor
2459 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2460 const CXXRecordDecl *RD = Constructor->getParent();
2461 // DR1359:
2462 // - every non-variant non-static data member and base class sub-object
2463 // shall be initialized;
2464 // DR1460:
2465 // - if the class is a union having variant members, exactly one of them
2466 // shall be initialized;
2467 if (RD->isUnion()) {
2468 if (Constructor->getNumCtorInitializers() == 0 &&
2469 RD->hasVariantMembers()) {
2470 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2471 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2472 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2473 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2474 return false;
2475 }
2476 }
2477 } else if (!Constructor->isDependentContext() &&
2478 !Constructor->isDelegatingConstructor()) {
2479 // Skip detailed checking if we have enough initializers, and we would
2480 // allow at most one initializer per member.
2481 bool AnyAnonStructUnionMembers = false;
2482 unsigned Fields = 0;
2483 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2484 E = RD->field_end(); I != E; ++I, ++Fields) {
2485 if (I->isAnonymousStructOrUnion()) {
2486 AnyAnonStructUnionMembers = true;
2487 break;
2488 }
2489 }
2490 // DR1460:
2491 // - if the class is a union-like class, but is not a union, for each of
2492 // its anonymous union members having variant members, exactly one of
2493 // them shall be initialized;
2494 if (AnyAnonStructUnionMembers ||
2495 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2496 // Check initialization of non-static data members. Base classes are
2497 // always initialized so do not need to be checked. Dependent bases
2498 // might not have initializers in the member initializer list.
2499 llvm::SmallPtrSet<Decl *, 16> Inits;
2500 for (const auto *I: Constructor->inits()) {
2501 if (FieldDecl *FD = I->getMember())
2502 Inits.insert(Ptr: FD);
2503 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2504 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2505 }
2506
2507 bool Diagnosed = false;
2508 for (auto *I : RD->fields())
2509 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2510 Kind))
2511 return false;
2512 }
2513 }
2514 } else {
2515 if (ReturnStmts.empty()) {
2516 switch (Kind) {
2517 case Sema::CheckConstexprKind::Diagnose:
2518 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2519 return false;
2520 break;
2521
2522 case Sema::CheckConstexprKind::CheckValid:
2523 // The formal requirements don't include this rule in C++14, even
2524 // though the "must be able to produce a constant expression" rules
2525 // still imply it in some cases.
2526 if (!SemaRef.getLangOpts().CPlusPlus14)
2527 return false;
2528 break;
2529 }
2530 } else if (ReturnStmts.size() > 1) {
2531 switch (Kind) {
2532 case Sema::CheckConstexprKind::Diagnose:
2533 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2534 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2535 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2536 SemaRef.Diag(Loc: ReturnStmts[I],
2537 DiagID: diag::note_constexpr_body_previous_return);
2538 break;
2539
2540 case Sema::CheckConstexprKind::CheckValid:
2541 if (!SemaRef.getLangOpts().CPlusPlus14)
2542 return false;
2543 break;
2544 }
2545 }
2546 }
2547
2548 // C++11 [dcl.constexpr]p5:
2549 // if no function argument values exist such that the function invocation
2550 // substitution would produce a constant expression, the program is
2551 // ill-formed; no diagnostic required.
2552 // C++11 [dcl.constexpr]p3:
2553 // - every constructor call and implicit conversion used in initializing the
2554 // return value shall be one of those allowed in a constant expression.
2555 // C++11 [dcl.constexpr]p4:
2556 // - every constructor involved in initializing non-static data members and
2557 // base class sub-objects shall be a constexpr constructor.
2558 //
2559 // Note that this rule is distinct from the "requirements for a constexpr
2560 // function", so is not checked in CheckValid mode. Because the check for
2561 // constexpr potential is expensive, skip the check if the diagnostic is
2562 // disabled, the function is declared in a system header, or we're in C++23
2563 // or later mode (see https://wg21.link/P2448).
2564 bool SkipCheck =
2565 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2566 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2567 SemaRef.getDiagnostics().isIgnored(
2568 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2569 SmallVector<PartialDiagnosticAt, 8> Diags;
2570 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2571 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2572 SemaRef.Diag(Loc: Dcl->getLocation(),
2573 DiagID: diag::ext_constexpr_function_never_constant_expr)
2574 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2575 << Dcl->getNameInfo().getSourceRange();
2576 for (const auto &Diag : Diags)
2577 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2578 // Don't return false here: we allow this for compatibility in
2579 // system headers.
2580 }
2581
2582 return true;
2583}
2584
2585static bool CheckConstexprMissingReturn(Sema &SemaRef,
2586 const FunctionDecl *Dcl) {
2587 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2588 Dcl->getReturnType()->isDependentType();
2589 // Skip emitting a missing return error diagnostic for non-void functions
2590 // since C++23 no longer mandates constexpr functions to yield constant
2591 // expressions.
2592 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2593 return true;
2594
2595 // C++14 doesn't require constexpr functions to contain a 'return'
2596 // statement. We still do, unless the return type might be void, because
2597 // otherwise if there's no return statement, the function cannot
2598 // be used in a core constant expression.
2599 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2600 SemaRef.Diag(Loc: Dcl->getLocation(),
2601 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2602 : diag::err_constexpr_body_no_return)
2603 << Dcl->isConsteval();
2604 return OK;
2605}
2606
2607bool Sema::CheckImmediateEscalatingFunctionDefinition(
2608 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2609 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2610 return true;
2611 FD->setBodyContainsImmediateEscalatingExpressions(
2612 FSI->FoundImmediateEscalatingExpression);
2613 if (FSI->FoundImmediateEscalatingExpression) {
2614 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2615 if (it != UndefinedButUsed.end()) {
2616 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2617 << it->first;
2618 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2619 if (FD->isImmediateFunction() && !FD->isConsteval())
2620 DiagnoseImmediateEscalatingReason(FD);
2621 return false;
2622 }
2623 }
2624 return true;
2625}
2626
2627void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2628 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2629 "expected an immediate function");
2630 assert(FD->hasBody() && "expected the function to have a body");
2631 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2632 Sema &SemaRef;
2633
2634 const FunctionDecl *ImmediateFn;
2635 bool ImmediateFnIsConstructor;
2636 CXXConstructorDecl *CurrentConstructor = nullptr;
2637 CXXCtorInitializer *CurrentInit = nullptr;
2638
2639 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2640 : SemaRef(SemaRef), ImmediateFn(FD),
2641 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2642 ShouldVisitImplicitCode = true;
2643 ShouldVisitLambdaBody = false;
2644 }
2645
2646 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2647 SourceLocation Loc = E->getBeginLoc();
2648 SourceRange Range = E->getSourceRange();
2649 if (CurrentConstructor && CurrentInit) {
2650 Loc = CurrentConstructor->getLocation();
2651 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2652 : SourceRange();
2653 }
2654
2655 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2656
2657 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2658 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2659 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2660 << (InitializedField != nullptr)
2661 << (CurrentInit && !CurrentInit->isWritten())
2662 << InitializedField << Range;
2663 }
2664 bool TraverseCallExpr(CallExpr *E) override {
2665 if (const auto *DR =
2666 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2667 DR && DR->isImmediateEscalating()) {
2668 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2669 return false;
2670 }
2671
2672 for (Expr *A : E->arguments())
2673 if (!TraverseStmt(S: A))
2674 return false;
2675
2676 return true;
2677 }
2678
2679 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2680 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2681 ReferencedFn && E->isImmediateEscalating()) {
2682 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2683 return false;
2684 }
2685
2686 return true;
2687 }
2688
2689 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2690 CXXConstructorDecl *D = E->getConstructor();
2691 if (E->isImmediateEscalating()) {
2692 Diag(E, Fn: D, /*IsCall=*/true);
2693 return false;
2694 }
2695 return true;
2696 }
2697
2698 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2699 llvm::SaveAndRestore RAII(CurrentInit, Init);
2700 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2701 }
2702
2703 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2704 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2705 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2706 }
2707
2708 bool TraverseType(QualType T, bool TraverseQualifier) override {
2709 return true;
2710 }
2711 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2712
2713 } Visitor(*this, FD);
2714 Visitor.TraverseDecl(D: FD);
2715}
2716
2717CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2718 assert(getLangOpts().CPlusPlus && "No class names in C!");
2719
2720 if (SS && SS->isInvalid())
2721 return nullptr;
2722
2723 if (SS && SS->isNotEmpty()) {
2724 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2725 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2726 }
2727
2728 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2729}
2730
2731bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2732 const CXXScopeSpec *SS) {
2733 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2734 return CurDecl && &II == CurDecl->getIdentifier();
2735}
2736
2737bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2738 assert(getLangOpts().CPlusPlus && "No class names in C!");
2739
2740 if (!getLangOpts().SpellChecking)
2741 return false;
2742
2743 CXXRecordDecl *CurDecl;
2744 if (SS && SS->isSet() && !SS->isInvalid()) {
2745 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2746 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2747 } else
2748 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2749
2750 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2751 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2752 < II->getLength()) {
2753 II = CurDecl->getIdentifier();
2754 return true;
2755 }
2756
2757 return false;
2758}
2759
2760CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2761 SourceRange SpecifierRange,
2762 bool Virtual, AccessSpecifier Access,
2763 TypeSourceInfo *TInfo,
2764 SourceLocation EllipsisLoc) {
2765 QualType BaseType = TInfo->getType();
2766 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2767 if (BaseType->containsErrors()) {
2768 // Already emitted a diagnostic when parsing the error type.
2769 return nullptr;
2770 }
2771
2772 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2773 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2774 << TInfo->getTypeLoc().getSourceRange();
2775 EllipsisLoc = SourceLocation();
2776 }
2777
2778 auto *BaseDecl =
2779 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2780 // C++ [class.derived.general]p2:
2781 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2782 // that is not an incompletely defined class; any cv-qualifiers are
2783 // ignored.
2784 if (BaseDecl) {
2785 // C++ [class.union.general]p4:
2786 // [...] A union shall not be used as a base class.
2787 if (BaseDecl->isUnion()) {
2788 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2789 return nullptr;
2790 }
2791
2792 if (BaseType.hasQualifiers()) {
2793 std::string Quals =
2794 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2795 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2796 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2797 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2798 }
2799
2800 // For the MS ABI, propagate DLL attributes to base class templates.
2801 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2802 Context.getTargetInfo().getTriple().isPS()) {
2803 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2804 if (auto *BaseSpec =
2805 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2806 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2807 BaseLoc);
2808 }
2809 }
2810 }
2811
2812 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2813 Args: SpecifierRange)) {
2814 Class->setInvalidDecl();
2815 return nullptr;
2816 }
2817
2818 BaseDecl = BaseDecl->getDefinition();
2819 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2820
2821 // Microsoft docs say:
2822 // "If a base-class has a code_seg attribute, derived classes must have the
2823 // same attribute."
2824 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2825 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2826 if ((DerivedCSA || BaseCSA) &&
2827 (!BaseCSA || !DerivedCSA ||
2828 BaseCSA->getName() != DerivedCSA->getName())) {
2829 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2830 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2831 << BaseDecl;
2832 return nullptr;
2833 }
2834
2835 // A class which contains a flexible array member is not suitable for use as
2836 // a base class:
2837 // - If the layout determines that a base comes before another base,
2838 // the flexible array member would index into the subsequent base.
2839 // - If the layout determines that base comes before the derived class,
2840 // the flexible array member would index into the derived class.
2841 if (BaseDecl->hasFlexibleArrayMember()) {
2842 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2843 << BaseDecl->getDeclName();
2844 return nullptr;
2845 }
2846
2847 // C++ [class]p3:
2848 // If a class is marked final and it appears as a base-type-specifier in
2849 // base-clause, the program is ill-formed.
2850 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2851 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2852 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2853 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2854 << BaseDecl->getDeclName() << FA->getRange();
2855 return nullptr;
2856 }
2857
2858 // If the base class is invalid the derived class is as well.
2859 if (BaseDecl->isInvalidDecl())
2860 Class->setInvalidDecl();
2861 } else if (BaseType->isDependentType()) {
2862 // Make sure that we don't make an ill-formed AST where the type of the
2863 // Class is non-dependent and its attached base class specifier is an
2864 // dependent type, which violates invariants in many clang code paths (e.g.
2865 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2866 // explicitly mark the Class decl invalid. The diagnostic was already
2867 // emitted.
2868 if (!Class->isDependentContext())
2869 Class->setInvalidDecl();
2870 } else {
2871 // The base class is some non-dependent non-class type.
2872 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2873 return nullptr;
2874 }
2875
2876 // In HLSL, unspecified class access is public rather than private.
2877 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2878 Access == AS_none)
2879 Access = AS_public;
2880
2881 // Create the base specifier.
2882 return new (Context) CXXBaseSpecifier(
2883 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2884 Access, TInfo, EllipsisLoc);
2885}
2886
2887BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2888 const ParsedAttributesView &Attributes,
2889 bool Virtual, AccessSpecifier Access,
2890 ParsedType basetype, SourceLocation BaseLoc,
2891 SourceLocation EllipsisLoc) {
2892 if (!classdecl)
2893 return true;
2894
2895 AdjustDeclIfTemplate(Decl&: classdecl);
2896 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2897 if (!Class)
2898 return true;
2899
2900 // We haven't yet attached the base specifiers.
2901 Class->setIsParsingBaseSpecifiers();
2902
2903 // We do not support any C++11 attributes on base-specifiers yet.
2904 // Diagnose any attributes we see.
2905 for (const ParsedAttr &AL : Attributes) {
2906 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2907 continue;
2908 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2909 DiagnoseUnknownAttribute(AL);
2910 else
2911 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2912 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2913 }
2914
2915 TypeSourceInfo *TInfo = nullptr;
2916 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2917
2918 if (EllipsisLoc.isInvalid() &&
2919 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2920 UPPC: UPPC_BaseType))
2921 return true;
2922
2923 // C++ [class.union.general]p4:
2924 // [...] A union shall not have base classes.
2925 if (Class->isUnion()) {
2926 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2927 << SpecifierRange;
2928 return true;
2929 }
2930
2931 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2932 Virtual, Access, TInfo,
2933 EllipsisLoc))
2934 return BaseSpec;
2935
2936 Class->setInvalidDecl();
2937 return true;
2938}
2939
2940/// Use small set to collect indirect bases. As this is only used
2941/// locally, there's no need to abstract the small size parameter.
2942typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2943
2944/// Recursively add the bases of Type. Don't add Type itself.
2945static void
2946NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2947 const QualType &Type)
2948{
2949 // Even though the incoming type is a base, it might not be
2950 // a class -- it could be a template parm, for instance.
2951 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2952 // Iterate over its bases.
2953 for (const auto &BaseSpec : Decl->bases()) {
2954 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2955 .getUnqualifiedType();
2956 if (Set.insert(Ptr: Base).second)
2957 // If we've not already seen it, recurse.
2958 NoteIndirectBases(Context, Set, Type: Base);
2959 }
2960 }
2961}
2962
2963bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2964 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2965 if (Bases.empty())
2966 return false;
2967
2968 // Used to keep track of which base types we have already seen, so
2969 // that we can properly diagnose redundant direct base types. Note
2970 // that the key is always the unqualified canonical type of the base
2971 // class.
2972 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2973
2974 // Used to track indirect bases so we can see if a direct base is
2975 // ambiguous.
2976 IndirectBaseSet IndirectBaseTypes;
2977
2978 // Copy non-redundant base specifiers into permanent storage.
2979 unsigned NumGoodBases = 0;
2980 bool Invalid = false;
2981 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2982 QualType NewBaseType
2983 = Context.getCanonicalType(T: Bases[idx]->getType());
2984 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2985
2986 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2987 if (KnownBase) {
2988 // C++ [class.mi]p3:
2989 // A class shall not be specified as a direct base class of a
2990 // derived class more than once.
2991 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
2992 << KnownBase->getType() << Bases[idx]->getSourceRange();
2993
2994 // Delete the duplicate base class specifier; we're going to
2995 // overwrite its pointer later.
2996 Context.Deallocate(Ptr: Bases[idx]);
2997
2998 Invalid = true;
2999 } else {
3000 // Okay, add this new base class.
3001 KnownBase = Bases[idx];
3002 Bases[NumGoodBases++] = Bases[idx];
3003
3004 if (NewBaseType->isDependentType())
3005 continue;
3006 // Note this base's direct & indirect bases, if there could be ambiguity.
3007 if (Bases.size() > 1)
3008 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
3009
3010 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3011 if (Class->isInterface() &&
3012 (!RD->isInterfaceLike() ||
3013 KnownBase->getAccessSpecifier() != AS_public)) {
3014 // The Microsoft extension __interface does not permit bases that
3015 // are not themselves public interfaces.
3016 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
3017 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
3018 << RD->getSourceRange();
3019 Invalid = true;
3020 }
3021 if (RD->hasAttr<WeakAttr>())
3022 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
3023 }
3024 }
3025 }
3026
3027 // Attach the remaining base class specifiers to the derived class.
3028 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3029
3030 // Check that the only base classes that are duplicate are virtual.
3031 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3032 // Check whether this direct base is inaccessible due to ambiguity.
3033 QualType BaseType = Bases[idx]->getType();
3034
3035 // Skip all dependent types in templates being used as base specifiers.
3036 // Checks below assume that the base specifier is a CXXRecord.
3037 if (BaseType->isDependentType())
3038 continue;
3039
3040 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3041 .getUnqualifiedType();
3042
3043 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3044 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3045 /*DetectVirtual=*/true);
3046 bool found
3047 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3048 assert(found);
3049 (void)found;
3050
3051 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3052 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3053 << BaseType << getAmbiguousPathsDisplayString(Paths)
3054 << Bases[idx]->getSourceRange();
3055 else
3056 assert(Bases[idx]->isVirtual());
3057 }
3058
3059 // Delete the base class specifier, since its data has been copied
3060 // into the CXXRecordDecl.
3061 Context.Deallocate(Ptr: Bases[idx]);
3062 }
3063
3064 return Invalid;
3065}
3066
3067void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3068 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3069 if (!ClassDecl || Bases.empty())
3070 return;
3071
3072 AdjustDeclIfTemplate(Decl&: ClassDecl);
3073 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3074}
3075
3076bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3077 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3078 if (!getLangOpts().CPlusPlus)
3079 return false;
3080
3081 if (!Base || !Derived)
3082 return false;
3083
3084 // If either the base or the derived type is invalid, don't try to
3085 // check whether one is derived from the other.
3086 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3087 return false;
3088
3089 // FIXME: In a modules build, do we need the entire path to be visible for us
3090 // to be able to use the inheritance relationship?
3091 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3092 !Derived->isBeingDefined())
3093 return false;
3094
3095 return Derived->isDerivedFrom(Base, Paths);
3096}
3097
3098bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3099 CXXRecordDecl *Base) {
3100 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3101 /*DetectVirtual=*/false);
3102 return IsDerivedFrom(Loc, Derived, Base, Paths);
3103}
3104
3105bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3106 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3107 /*DetectVirtual=*/false);
3108 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3109 Base: Base->getAsCXXRecordDecl(), Paths);
3110}
3111
3112bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3113 CXXBasePaths &Paths) {
3114 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3115 Base: Base->getAsCXXRecordDecl(), Paths);
3116}
3117
3118static void BuildBasePathArray(const CXXBasePath &Path,
3119 CXXCastPath &BasePathArray) {
3120 // We first go backward and check if we have a virtual base.
3121 // FIXME: It would be better if CXXBasePath had the base specifier for
3122 // the nearest virtual base.
3123 unsigned Start = 0;
3124 for (unsigned I = Path.size(); I != 0; --I) {
3125 if (Path[I - 1].Base->isVirtual()) {
3126 Start = I - 1;
3127 break;
3128 }
3129 }
3130
3131 // Now add all bases.
3132 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3133 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3134}
3135
3136
3137void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3138 CXXCastPath &BasePathArray) {
3139 assert(BasePathArray.empty() && "Base path array must be empty!");
3140 assert(Paths.isRecordingPaths() && "Must record paths!");
3141 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3142}
3143
3144bool
3145Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3146 unsigned InaccessibleBaseID,
3147 unsigned AmbiguousBaseConvID,
3148 SourceLocation Loc, SourceRange Range,
3149 DeclarationName Name,
3150 CXXCastPath *BasePath,
3151 bool IgnoreAccess) {
3152 // First, determine whether the path from Derived to Base is
3153 // ambiguous. This is slightly more expensive than checking whether
3154 // the Derived to Base conversion exists, because here we need to
3155 // explore multiple paths to determine if there is an ambiguity.
3156 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3157 /*DetectVirtual=*/false);
3158 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3159 if (!DerivationOkay)
3160 return true;
3161
3162 const CXXBasePath *Path = nullptr;
3163 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3164 Path = &Paths.front();
3165
3166 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3167 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3168 // user to access such bases.
3169 if (!Path && getLangOpts().MSVCCompat) {
3170 for (const CXXBasePath &PossiblePath : Paths) {
3171 if (PossiblePath.size() == 1) {
3172 Path = &PossiblePath;
3173 if (AmbiguousBaseConvID)
3174 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3175 << Base << Derived << Range;
3176 break;
3177 }
3178 }
3179 }
3180
3181 if (Path) {
3182 if (!IgnoreAccess) {
3183 // Check that the base class can be accessed.
3184 switch (
3185 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3186 case AR_inaccessible:
3187 return true;
3188 case AR_accessible:
3189 case AR_dependent:
3190 case AR_delayed:
3191 break;
3192 }
3193 }
3194
3195 // Build a base path if necessary.
3196 if (BasePath)
3197 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3198 return false;
3199 }
3200
3201 if (AmbiguousBaseConvID) {
3202 // We know that the derived-to-base conversion is ambiguous, and
3203 // we're going to produce a diagnostic. Perform the derived-to-base
3204 // search just one more time to compute all of the possible paths so
3205 // that we can print them out. This is more expensive than any of
3206 // the previous derived-to-base checks we've done, but at this point
3207 // performance isn't as much of an issue.
3208 Paths.clear();
3209 Paths.setRecordingPaths(true);
3210 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3211 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3212 (void)StillOkay;
3213
3214 // Build up a textual representation of the ambiguous paths, e.g.,
3215 // D -> B -> A, that will be used to illustrate the ambiguous
3216 // conversions in the diagnostic. We only print one of the paths
3217 // to each base class subobject.
3218 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3219
3220 Diag(Loc, DiagID: AmbiguousBaseConvID)
3221 << Derived << Base << PathDisplayStr << Range << Name;
3222 }
3223 return true;
3224}
3225
3226bool
3227Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3228 SourceLocation Loc, SourceRange Range,
3229 CXXCastPath *BasePath,
3230 bool IgnoreAccess) {
3231 return CheckDerivedToBaseConversion(
3232 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3233 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3234 BasePath, IgnoreAccess);
3235}
3236
3237std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3238 std::string PathDisplayStr;
3239 std::set<unsigned> DisplayedPaths;
3240 for (const CXXBasePath &Path : Paths) {
3241 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3242 // We haven't displayed a path to this particular base
3243 // class subobject yet.
3244 PathDisplayStr += "\n ";
3245 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3246 .getAsString();
3247 for (const CXXBasePathElement &Element : Path)
3248 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3249 }
3250 }
3251
3252 return PathDisplayStr;
3253}
3254
3255//===----------------------------------------------------------------------===//
3256// C++ class member Handling
3257//===----------------------------------------------------------------------===//
3258
3259bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3260 SourceLocation ColonLoc,
3261 const ParsedAttributesView &Attrs) {
3262 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3263 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3264 ASLoc, ColonLoc);
3265 CurContext->addHiddenDecl(D: ASDecl);
3266 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3267}
3268
3269void Sema::CheckOverrideControl(NamedDecl *D) {
3270 if (D->isInvalidDecl())
3271 return;
3272
3273 // We only care about "override" and "final" declarations.
3274 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3275 return;
3276
3277 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3278
3279 // We can't check dependent instance methods.
3280 if (MD && MD->isInstance() &&
3281 (MD->getParent()->hasAnyDependentBases() ||
3282 MD->getType()->isDependentType()))
3283 return;
3284
3285 if (MD && !MD->isVirtual()) {
3286 // If we have a non-virtual method, check if it hides a virtual method.
3287 // (In that case, it's most likely the method has the wrong type.)
3288 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3289 FindHiddenVirtualMethods(MD, OverloadedMethods);
3290
3291 if (!OverloadedMethods.empty()) {
3292 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3293 Diag(Loc: OA->getLocation(),
3294 DiagID: diag::override_keyword_hides_virtual_member_function)
3295 << "override" << (OverloadedMethods.size() > 1);
3296 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3297 Diag(Loc: FA->getLocation(),
3298 DiagID: diag::override_keyword_hides_virtual_member_function)
3299 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3300 << (OverloadedMethods.size() > 1);
3301 }
3302 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3303 MD->setInvalidDecl();
3304 return;
3305 }
3306 // Fall through into the general case diagnostic.
3307 // FIXME: We might want to attempt typo correction here.
3308 }
3309
3310 if (!MD || !MD->isVirtual()) {
3311 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3312 Diag(Loc: OA->getLocation(),
3313 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3314 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3315 D->dropAttr<OverrideAttr>();
3316 }
3317 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3318 Diag(Loc: FA->getLocation(),
3319 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3320 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3321 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3322 D->dropAttr<FinalAttr>();
3323 }
3324 return;
3325 }
3326
3327 // C++11 [class.virtual]p5:
3328 // If a function is marked with the virt-specifier override and
3329 // does not override a member function of a base class, the program is
3330 // ill-formed.
3331 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3332 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3333 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3334 << MD->getDeclName();
3335}
3336
3337void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3338 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3339 return;
3340 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3341 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3342 return;
3343
3344 SourceLocation Loc = MD->getLocation();
3345 SourceLocation SpellingLoc = Loc;
3346 if (getSourceManager().isMacroArgExpansion(Loc))
3347 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3348 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3349 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3350 return;
3351
3352 if (MD->size_overridden_methods() > 0) {
3353 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3354 unsigned DiagID =
3355 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3356 ? DiagInconsistent
3357 : DiagSuggest;
3358 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3359 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3360 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3361 };
3362 if (isa<CXXDestructorDecl>(Val: MD))
3363 EmitDiag(
3364 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3365 diag::warn_suggest_destructor_marked_not_override_overriding);
3366 else
3367 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3368 diag::warn_suggest_function_marked_not_override_overriding);
3369 }
3370}
3371
3372bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3373 const CXXMethodDecl *Old) {
3374 FinalAttr *FA = Old->getAttr<FinalAttr>();
3375 if (!FA)
3376 return false;
3377
3378 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3379 << New->getDeclName()
3380 << FA->isSpelledAsSealed();
3381 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3382 return true;
3383}
3384
3385static bool InitializationHasSideEffects(const FieldDecl &FD) {
3386 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3387 // FIXME: Destruction of ObjC lifetime types has side-effects.
3388 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3389 return !RD->isCompleteDefinition() ||
3390 !RD->hasTrivialDefaultConstructor() ||
3391 !RD->hasTrivialDestructor();
3392 return false;
3393}
3394
3395void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3396 DeclarationName FieldName,
3397 const CXXRecordDecl *RD,
3398 bool DeclIsField) {
3399 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3400 return;
3401
3402 // To record a shadowed field in a base
3403 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3404 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3405 CXXBasePath &Path) {
3406 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3407 // Record an ambiguous path directly
3408 if (Bases.find(x: Base) != Bases.end())
3409 return true;
3410 for (const auto Field : Base->lookup(Name: FieldName)) {
3411 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3412 Field->getAccess() != AS_private) {
3413 assert(Field->getAccess() != AS_none);
3414 assert(Bases.find(Base) == Bases.end());
3415 Bases[Base] = Field;
3416 return true;
3417 }
3418 }
3419 return false;
3420 };
3421
3422 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3423 /*DetectVirtual=*/true);
3424 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3425 return;
3426
3427 for (const auto &P : Paths) {
3428 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3429 auto It = Bases.find(x: Base);
3430 // Skip duplicated bases
3431 if (It == Bases.end())
3432 continue;
3433 auto BaseField = It->second;
3434 assert(BaseField->getAccess() != AS_private);
3435 if (AS_none !=
3436 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3437 Diag(Loc, DiagID: diag::warn_shadow_field)
3438 << FieldName << RD << Base << DeclIsField;
3439 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3440 Bases.erase(position: It);
3441 }
3442 }
3443}
3444
3445template <typename AttrType>
3446inline static bool HasAttribute(const QualType &T) {
3447 if (const TagDecl *TD = T->getAsTagDecl())
3448 return TD->hasAttr<AttrType>();
3449 if (const TypedefType *TDT = T->getAs<TypedefType>())
3450 return TDT->getDecl()->hasAttr<AttrType>();
3451 return false;
3452}
3453
3454static bool IsUnusedPrivateField(const FieldDecl *FD) {
3455 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3456 QualType FieldType = FD->getType();
3457 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3458 return true;
3459
3460 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3461 !FD->getParent()->isDependentContext() &&
3462 !HasAttribute<UnusedAttr>(T: FieldType) &&
3463 !InitializationHasSideEffects(FD: *FD);
3464 }
3465 return false;
3466}
3467
3468NamedDecl *
3469Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3470 MultiTemplateParamsArg TemplateParameterLists,
3471 Expr *BitWidth, const VirtSpecifiers &VS,
3472 InClassInitStyle InitStyle) {
3473 const DeclSpec &DS = D.getDeclSpec();
3474 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3475 DeclarationName Name = NameInfo.getName();
3476 SourceLocation Loc = NameInfo.getLoc();
3477
3478 // For anonymous bitfields, the location should point to the type.
3479 if (Loc.isInvalid())
3480 Loc = D.getBeginLoc();
3481
3482 assert(isa<CXXRecordDecl>(CurContext));
3483 assert(!DS.isFriendSpecified());
3484
3485 bool isFunc = D.isDeclarationOfFunction();
3486 const ParsedAttr *MSPropertyAttr =
3487 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3488
3489 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3490 // The Microsoft extension __interface only permits public member functions
3491 // and prohibits constructors, destructors, operators, non-public member
3492 // functions, static methods and data members.
3493 unsigned InvalidDecl;
3494 bool ShowDeclName = true;
3495 if (!isFunc &&
3496 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3497 InvalidDecl = 0;
3498 else if (!isFunc)
3499 InvalidDecl = 1;
3500 else if (AS != AS_public)
3501 InvalidDecl = 2;
3502 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3503 InvalidDecl = 3;
3504 else switch (Name.getNameKind()) {
3505 case DeclarationName::CXXConstructorName:
3506 InvalidDecl = 4;
3507 ShowDeclName = false;
3508 break;
3509
3510 case DeclarationName::CXXDestructorName:
3511 InvalidDecl = 5;
3512 ShowDeclName = false;
3513 break;
3514
3515 case DeclarationName::CXXOperatorName:
3516 case DeclarationName::CXXConversionFunctionName:
3517 InvalidDecl = 6;
3518 break;
3519
3520 default:
3521 InvalidDecl = 0;
3522 break;
3523 }
3524
3525 if (InvalidDecl) {
3526 if (ShowDeclName)
3527 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3528 << (InvalidDecl-1) << Name;
3529 else
3530 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3531 << (InvalidDecl-1) << "";
3532 return nullptr;
3533 }
3534 }
3535
3536 // HLSL prohibits user defined constructors and destructors.
3537 if (getLangOpts().HLSL) {
3538 switch (Name.getNameKind()) {
3539 case DeclarationName::CXXConstructorName:
3540 case DeclarationName::CXXDestructorName:
3541 Diag(Loc, DiagID: diag::err_hlsl_cstor_dstor);
3542 return nullptr;
3543 default:
3544 break;
3545 }
3546 }
3547
3548 // C++ 9.2p6: A member shall not be declared to have automatic storage
3549 // duration (auto, register) or with the extern storage-class-specifier.
3550 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3551 // data members and cannot be applied to names declared const or static,
3552 // and cannot be applied to reference members.
3553 switch (DS.getStorageClassSpec()) {
3554 case DeclSpec::SCS_unspecified:
3555 case DeclSpec::SCS_typedef:
3556 case DeclSpec::SCS_static:
3557 break;
3558 case DeclSpec::SCS_mutable:
3559 if (isFunc) {
3560 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3561
3562 // FIXME: It would be nicer if the keyword was ignored only for this
3563 // declarator. Otherwise we could get follow-up errors.
3564 D.getMutableDeclSpec().ClearStorageClassSpecs();
3565 }
3566 break;
3567 default:
3568 Diag(Loc: DS.getStorageClassSpecLoc(),
3569 DiagID: diag::err_storageclass_invalid_for_member);
3570 D.getMutableDeclSpec().ClearStorageClassSpecs();
3571 break;
3572 }
3573
3574 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3575 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3576 !isFunc && TemplateParameterLists.empty();
3577
3578 if (DS.hasConstexprSpecifier() && isInstField) {
3579 SemaDiagnosticBuilder B =
3580 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3581 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3582 if (InitStyle == ICIS_NoInit) {
3583 B << 0 << 0;
3584 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3585 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3586 else {
3587 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3588 D.getMutableDeclSpec().ClearConstexprSpec();
3589 const char *PrevSpec;
3590 unsigned DiagID;
3591 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3592 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3593 (void)Failed;
3594 assert(!Failed && "Making a constexpr member const shouldn't fail");
3595 }
3596 } else {
3597 B << 1;
3598 const char *PrevSpec;
3599 unsigned DiagID;
3600 if (D.getMutableDeclSpec().SetStorageClassSpec(
3601 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3602 Policy: Context.getPrintingPolicy())) {
3603 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3604 "This is the only DeclSpec that should fail to be applied");
3605 B << 1;
3606 } else {
3607 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3608 isInstField = false;
3609 }
3610 }
3611 }
3612
3613 NamedDecl *Member;
3614 if (isInstField) {
3615 CXXScopeSpec &SS = D.getCXXScopeSpec();
3616
3617 // Data members must have identifiers for names.
3618 if (!Name.isIdentifier()) {
3619 Diag(Loc, DiagID: diag::err_bad_variable_name)
3620 << Name;
3621 return nullptr;
3622 }
3623
3624 IdentifierInfo *II = Name.getAsIdentifierInfo();
3625 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3626 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3627 << II
3628 << SourceRange(D.getName().TemplateId->LAngleLoc,
3629 D.getName().TemplateId->RAngleLoc)
3630 << D.getName().TemplateId->LAngleLoc;
3631 D.SetIdentifier(Id: II, IdLoc: Loc);
3632 }
3633
3634 if (SS.isSet() && !SS.isInvalid()) {
3635 // The user provided a superfluous scope specifier inside a class
3636 // definition:
3637 //
3638 // class X {
3639 // int X::member;
3640 // };
3641 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3642 TemplateIdAnnotation *TemplateId =
3643 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3644 ? D.getName().TemplateId
3645 : nullptr;
3646 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3647 TemplateId,
3648 /*IsMemberSpecialization=*/false);
3649 } else {
3650 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3651 << Name << SS.getRange();
3652 }
3653 SS.clear();
3654 }
3655
3656 if (MSPropertyAttr) {
3657 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3658 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3659 if (!Member)
3660 return nullptr;
3661 isInstField = false;
3662 } else {
3663 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3664 BitfieldWidth: BitWidth, InitStyle, AS);
3665 if (!Member)
3666 return nullptr;
3667 }
3668
3669 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3670 } else {
3671 Member = HandleDeclarator(S, D, TemplateParameterLists);
3672 if (!Member)
3673 return nullptr;
3674
3675 // Non-instance-fields can't have a bitfield.
3676 if (BitWidth) {
3677 if (Member->isInvalidDecl()) {
3678 // don't emit another diagnostic.
3679 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3680 // C++ 9.6p3: A bit-field shall not be a static member.
3681 // "static member 'A' cannot be a bit-field"
3682 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3683 << Name << BitWidth->getSourceRange();
3684 } else if (isa<TypedefDecl>(Val: Member)) {
3685 // "typedef member 'x' cannot be a bit-field"
3686 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3687 << Name << BitWidth->getSourceRange();
3688 } else {
3689 // A function typedef ("typedef int f(); f a;").
3690 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3691 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3692 << Name << cast<ValueDecl>(Val: Member)->getType()
3693 << BitWidth->getSourceRange();
3694 }
3695
3696 BitWidth = nullptr;
3697 Member->setInvalidDecl();
3698 }
3699
3700 NamedDecl *NonTemplateMember = Member;
3701 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3702 NonTemplateMember = FunTmpl->getTemplatedDecl();
3703 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3704 NonTemplateMember = VarTmpl->getTemplatedDecl();
3705
3706 Member->setAccess(AS);
3707
3708 // If we have declared a member function template or static data member
3709 // template, set the access of the templated declaration as well.
3710 if (NonTemplateMember != Member)
3711 NonTemplateMember->setAccess(AS);
3712
3713 // C++ [temp.deduct.guide]p3:
3714 // A deduction guide [...] for a member class template [shall be
3715 // declared] with the same access [as the template].
3716 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3717 auto *TD = DG->getDeducedTemplate();
3718 // Access specifiers are only meaningful if both the template and the
3719 // deduction guide are from the same scope.
3720 if (AS != TD->getAccess() &&
3721 TD->getDeclContext()->getRedeclContext()->Equals(
3722 DC: DG->getDeclContext()->getRedeclContext())) {
3723 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3724 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3725 << TD->getAccess();
3726 const AccessSpecDecl *LastAccessSpec = nullptr;
3727 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3728 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3729 LastAccessSpec = AccessSpec;
3730 }
3731 assert(LastAccessSpec && "differing access with no access specifier");
3732 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3733 << AS;
3734 }
3735 }
3736 }
3737
3738 if (VS.isOverrideSpecified())
3739 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3740 if (VS.isFinalSpecified())
3741 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3742 S: VS.isFinalSpelledSealed()
3743 ? FinalAttr::Keyword_sealed
3744 : FinalAttr::Keyword_final));
3745
3746 if (VS.getLastLocation().isValid()) {
3747 // Update the end location of a method that has a virt-specifiers.
3748 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3749 MD->setRangeEnd(VS.getLastLocation());
3750 }
3751
3752 CheckOverrideControl(D: Member);
3753
3754 assert((Name || isInstField) && "No identifier for non-field ?");
3755
3756 if (isInstField) {
3757 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3758 FieldCollector->Add(D: FD);
3759
3760 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3761 IsUnusedPrivateField(FD)) {
3762 // Remember all explicit private FieldDecls that have a name, no side
3763 // effects and are not part of a dependent type declaration.
3764 UnusedPrivateFields.insert(X: FD);
3765 }
3766 }
3767
3768 return Member;
3769}
3770
3771namespace {
3772 class UninitializedFieldVisitor
3773 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3774 Sema &S;
3775 // List of Decls to generate a warning on. Also remove Decls that become
3776 // initialized.
3777 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3778 // List of base classes of the record. Classes are removed after their
3779 // initializers.
3780 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3781 // Vector of decls to be removed from the Decl set prior to visiting the
3782 // nodes. These Decls may have been initialized in the prior initializer.
3783 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3784 // If non-null, add a note to the warning pointing back to the constructor.
3785 const CXXConstructorDecl *Constructor;
3786 // Variables to hold state when processing an initializer list. When
3787 // InitList is true, special case initialization of FieldDecls matching
3788 // InitListFieldDecl.
3789 bool InitList;
3790 FieldDecl *InitListFieldDecl;
3791 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3792
3793 public:
3794 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3795 UninitializedFieldVisitor(Sema &S,
3796 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3797 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3798 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3799 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3800
3801 // Returns true if the use of ME is not an uninitialized use.
3802 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3803 bool CheckReferenceOnly) {
3804 llvm::SmallVector<FieldDecl*, 4> Fields;
3805 bool ReferenceField = false;
3806 while (ME) {
3807 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3808 if (!FD)
3809 return false;
3810 Fields.push_back(Elt: FD);
3811 if (FD->getType()->isReferenceType())
3812 ReferenceField = true;
3813 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3814 }
3815
3816 // Binding a reference to an uninitialized field is not an
3817 // uninitialized use.
3818 if (CheckReferenceOnly && !ReferenceField)
3819 return true;
3820
3821 // Discard the first field since it is the field decl that is being
3822 // initialized.
3823 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3824 auto UsedIter = UsedFields.begin();
3825 const auto UsedEnd = UsedFields.end();
3826
3827 for (const unsigned Orig : InitFieldIndex) {
3828 if (UsedIter == UsedEnd)
3829 break;
3830 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3831 if (UsedIndex < Orig)
3832 return true;
3833 if (UsedIndex > Orig)
3834 break;
3835 ++UsedIter;
3836 }
3837
3838 return false;
3839 }
3840
3841 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3842 bool AddressOf) {
3843 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3844 return;
3845
3846 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3847 // or union.
3848 MemberExpr *FieldME = ME;
3849
3850 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3851
3852 Expr *Base = ME;
3853 while (MemberExpr *SubME =
3854 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3855
3856 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3857 return;
3858
3859 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3860 if (!FD->isAnonymousStructOrUnion())
3861 FieldME = SubME;
3862
3863 if (!FieldME->getType().isPODType(Context: S.Context))
3864 AllPODFields = false;
3865
3866 Base = SubME->getBase();
3867 }
3868
3869 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3870 Visit(S: Base);
3871 return;
3872 }
3873
3874 if (AddressOf && AllPODFields)
3875 return;
3876
3877 ValueDecl* FoundVD = FieldME->getMemberDecl();
3878
3879 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3880 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3881 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3882 }
3883
3884 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3885 QualType T = BaseCast->getType();
3886 if (T->isPointerType() &&
3887 BaseClasses.count(Ptr: T->getPointeeType())) {
3888 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3889 << T->getPointeeType() << FoundVD;
3890 }
3891 }
3892 }
3893
3894 if (!Decls.count(Ptr: FoundVD))
3895 return;
3896
3897 const bool IsReference = FoundVD->getType()->isReferenceType();
3898
3899 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3900 // Special checking for initializer lists.
3901 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3902 return;
3903 }
3904 } else {
3905 // Prevent double warnings on use of unbounded references.
3906 if (CheckReferenceOnly && !IsReference)
3907 return;
3908 }
3909
3910 unsigned diag = IsReference
3911 ? diag::warn_reference_field_is_uninit
3912 : diag::warn_field_is_uninit;
3913 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3914 if (Constructor)
3915 S.Diag(Loc: Constructor->getLocation(),
3916 DiagID: diag::note_uninit_in_this_constructor)
3917 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3918
3919 }
3920
3921 void HandleValue(Expr *E, bool AddressOf) {
3922 E = E->IgnoreParens();
3923
3924 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3925 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3926 AddressOf /*AddressOf*/);
3927 return;
3928 }
3929
3930 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3931 Visit(S: CO->getCond());
3932 HandleValue(E: CO->getTrueExpr(), AddressOf);
3933 HandleValue(E: CO->getFalseExpr(), AddressOf);
3934 return;
3935 }
3936
3937 if (BinaryConditionalOperator *BCO =
3938 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3939 Visit(S: BCO->getCond());
3940 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3941 return;
3942 }
3943
3944 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3945 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3946 return;
3947 }
3948
3949 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3950 switch (BO->getOpcode()) {
3951 default:
3952 break;
3953 case(BO_PtrMemD):
3954 case(BO_PtrMemI):
3955 HandleValue(E: BO->getLHS(), AddressOf);
3956 Visit(S: BO->getRHS());
3957 return;
3958 case(BO_Comma):
3959 Visit(S: BO->getLHS());
3960 HandleValue(E: BO->getRHS(), AddressOf);
3961 return;
3962 }
3963 }
3964
3965 Visit(S: E);
3966 }
3967
3968 void CheckInitListExpr(InitListExpr *ILE) {
3969 InitFieldIndex.push_back(Elt: 0);
3970 for (auto *Child : ILE->children()) {
3971 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3972 CheckInitListExpr(ILE: SubList);
3973 } else {
3974 Visit(S: Child);
3975 }
3976 ++InitFieldIndex.back();
3977 }
3978 InitFieldIndex.pop_back();
3979 }
3980
3981 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3982 FieldDecl *Field, const Type *BaseClass) {
3983 // Remove Decls that may have been initialized in the previous
3984 // initializer.
3985 for (ValueDecl* VD : DeclsToRemove)
3986 Decls.erase(Ptr: VD);
3987 DeclsToRemove.clear();
3988
3989 Constructor = FieldConstructor;
3990 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3991
3992 if (ILE && Field) {
3993 InitList = true;
3994 InitListFieldDecl = Field;
3995 InitFieldIndex.clear();
3996 CheckInitListExpr(ILE);
3997 } else {
3998 InitList = false;
3999 Visit(S: E);
4000 }
4001
4002 if (Field)
4003 Decls.erase(Ptr: Field);
4004 if (BaseClass)
4005 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4006 }
4007
4008 void VisitMemberExpr(MemberExpr *ME) {
4009 // All uses of unbounded reference fields will warn.
4010 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4011 }
4012
4013 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4014 if (E->getCastKind() == CK_LValueToRValue) {
4015 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4016 return;
4017 }
4018
4019 Inherited::VisitImplicitCastExpr(S: E);
4020 }
4021
4022 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4023 if (E->getConstructor()->isCopyConstructor()) {
4024 Expr *ArgExpr = E->getArg(Arg: 0);
4025 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4026 if (ILE->getNumInits() == 1)
4027 ArgExpr = ILE->getInit(Init: 0);
4028 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4029 if (ICE->getCastKind() == CK_NoOp)
4030 ArgExpr = ICE->getSubExpr();
4031 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4032 return;
4033 }
4034 Inherited::VisitCXXConstructExpr(S: E);
4035 }
4036
4037 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4038 Expr *Callee = E->getCallee();
4039 if (isa<MemberExpr>(Val: Callee)) {
4040 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4041 for (auto *Arg : E->arguments())
4042 Visit(S: Arg);
4043 return;
4044 }
4045
4046 Inherited::VisitCXXMemberCallExpr(S: E);
4047 }
4048
4049 void VisitCallExpr(CallExpr *E) {
4050 // Treat std::move as a use.
4051 if (E->isCallToStdMove()) {
4052 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4053 return;
4054 }
4055
4056 Inherited::VisitCallExpr(CE: E);
4057 }
4058
4059 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4060 Expr *Callee = E->getCallee();
4061
4062 if (isa<UnresolvedLookupExpr>(Val: Callee))
4063 return Inherited::VisitCXXOperatorCallExpr(S: E);
4064
4065 Visit(S: Callee);
4066 for (auto *Arg : E->arguments())
4067 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4068 }
4069
4070 void VisitBinaryOperator(BinaryOperator *E) {
4071 // If a field assignment is detected, remove the field from the
4072 // uninitiailized field set.
4073 if (E->getOpcode() == BO_Assign)
4074 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4075 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4076 if (!FD->getType()->isReferenceType())
4077 DeclsToRemove.push_back(Elt: FD);
4078
4079 if (E->isCompoundAssignmentOp()) {
4080 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4081 Visit(S: E->getRHS());
4082 return;
4083 }
4084
4085 Inherited::VisitBinaryOperator(S: E);
4086 }
4087
4088 void VisitUnaryOperator(UnaryOperator *E) {
4089 if (E->isIncrementDecrementOp()) {
4090 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4091 return;
4092 }
4093 if (E->getOpcode() == UO_AddrOf) {
4094 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4095 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4096 return;
4097 }
4098 }
4099
4100 Inherited::VisitUnaryOperator(S: E);
4101 }
4102 };
4103
4104 // Diagnose value-uses of fields to initialize themselves, e.g.
4105 // foo(foo)
4106 // where foo is not also a parameter to the constructor.
4107 // Also diagnose across field uninitialized use such as
4108 // x(y), y(x)
4109 // TODO: implement -Wuninitialized and fold this into that framework.
4110 static void DiagnoseUninitializedFields(
4111 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4112
4113 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4114 Loc: Constructor->getLocation())) {
4115 return;
4116 }
4117
4118 if (Constructor->isInvalidDecl())
4119 return;
4120
4121 const CXXRecordDecl *RD = Constructor->getParent();
4122
4123 if (RD->isDependentContext())
4124 return;
4125
4126 // Holds fields that are uninitialized.
4127 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4128
4129 // At the beginning, all fields are uninitialized.
4130 for (auto *I : RD->decls()) {
4131 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4132 UninitializedFields.insert(Ptr: FD);
4133 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4134 UninitializedFields.insert(Ptr: IFD->getAnonField());
4135 }
4136 }
4137
4138 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4139 for (const auto &I : RD->bases())
4140 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4141
4142 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4143 return;
4144
4145 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4146 UninitializedFields,
4147 UninitializedBaseClasses);
4148
4149 for (const auto *FieldInit : Constructor->inits()) {
4150 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4151 break;
4152
4153 Expr *InitExpr = FieldInit->getInit();
4154 if (!InitExpr)
4155 continue;
4156
4157 if (CXXDefaultInitExpr *Default =
4158 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4159 InitExpr = Default->getExpr();
4160 if (!InitExpr)
4161 continue;
4162 // In class initializers will point to the constructor.
4163 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4164 Field: FieldInit->getAnyMember(),
4165 BaseClass: FieldInit->getBaseClass());
4166 } else {
4167 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4168 Field: FieldInit->getAnyMember(),
4169 BaseClass: FieldInit->getBaseClass());
4170 }
4171 }
4172 }
4173} // namespace
4174
4175void Sema::ActOnStartCXXInClassMemberInitializer() {
4176 // Create a synthetic function scope to represent the call to the constructor
4177 // that notionally surrounds a use of this initializer.
4178 PushFunctionScope();
4179}
4180
4181void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4182 if (!D.isFunctionDeclarator())
4183 return;
4184 auto &FTI = D.getFunctionTypeInfo();
4185 if (!FTI.Params)
4186 return;
4187 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4188 FTI.NumParams)) {
4189 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4190 if (ParamDecl->getDeclName())
4191 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4192 }
4193}
4194
4195ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4196 return ActOnRequiresClause(ConstraintExpr);
4197}
4198
4199ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4200 if (ConstraintExpr.isInvalid())
4201 return ExprError();
4202
4203 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4204 UPPC: UPPC_RequiresClause))
4205 return ExprError();
4206
4207 return ConstraintExpr;
4208}
4209
4210ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4211 Expr *InitExpr,
4212 SourceLocation InitLoc) {
4213 InitializedEntity Entity =
4214 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4215 InitializationKind Kind =
4216 FD->getInClassInitStyle() == ICIS_ListInit
4217 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4218 LBraceLoc: InitExpr->getBeginLoc(),
4219 RBraceLoc: InitExpr->getEndLoc())
4220 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4221 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4222 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4223}
4224
4225void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4226 SourceLocation InitLoc,
4227 ExprResult InitExpr) {
4228 // Pop the notional constructor scope we created earlier.
4229 PopFunctionScopeInfo(WP: nullptr, D);
4230
4231 // Microsoft C++'s property declaration cannot have a default member
4232 // initializer.
4233 if (isa<MSPropertyDecl>(Val: D)) {
4234 D->setInvalidDecl();
4235 return;
4236 }
4237
4238 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4239 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4240 "must set init style when field is created");
4241
4242 if (!InitExpr.isUsable() ||
4243 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4244 FD->setInvalidDecl();
4245 ExprResult RecoveryInit =
4246 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4247 if (RecoveryInit.isUsable())
4248 FD->setInClassInitializer(RecoveryInit.get());
4249 return;
4250 }
4251
4252 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4253 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4254 // C++11 [class.base.init]p7:
4255 // The initialization of each base and member constitutes a
4256 // full-expression.
4257 if (!InitExpr.isInvalid())
4258 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4259 if (InitExpr.isInvalid()) {
4260 FD->setInvalidDecl();
4261 return;
4262 }
4263 }
4264
4265 FD->setInClassInitializer(InitExpr.get());
4266}
4267
4268/// Find the direct and/or virtual base specifiers that
4269/// correspond to the given base type, for use in base initialization
4270/// within a constructor.
4271static bool FindBaseInitializer(Sema &SemaRef,
4272 CXXRecordDecl *ClassDecl,
4273 QualType BaseType,
4274 const CXXBaseSpecifier *&DirectBaseSpec,
4275 const CXXBaseSpecifier *&VirtualBaseSpec) {
4276 // First, check for a direct base class.
4277 DirectBaseSpec = nullptr;
4278 for (const auto &Base : ClassDecl->bases()) {
4279 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4280 // We found a direct base of this type. That's what we're
4281 // initializing.
4282 DirectBaseSpec = &Base;
4283 break;
4284 }
4285 }
4286
4287 // Check for a virtual base class.
4288 // FIXME: We might be able to short-circuit this if we know in advance that
4289 // there are no virtual bases.
4290 VirtualBaseSpec = nullptr;
4291 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4292 // We haven't found a base yet; search the class hierarchy for a
4293 // virtual base class.
4294 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4295 /*DetectVirtual=*/false);
4296 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4297 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4298 Base: BaseType, Paths)) {
4299 for (const CXXBasePath &Path : Paths) {
4300 if (Path.back().Base->isVirtual()) {
4301 VirtualBaseSpec = Path.back().Base;
4302 break;
4303 }
4304 }
4305 }
4306 }
4307
4308 return DirectBaseSpec || VirtualBaseSpec;
4309}
4310
4311MemInitResult
4312Sema::ActOnMemInitializer(Decl *ConstructorD,
4313 Scope *S,
4314 CXXScopeSpec &SS,
4315 IdentifierInfo *MemberOrBase,
4316 ParsedType TemplateTypeTy,
4317 const DeclSpec &DS,
4318 SourceLocation IdLoc,
4319 Expr *InitList,
4320 SourceLocation EllipsisLoc) {
4321 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4322 DS, IdLoc, Init: InitList,
4323 EllipsisLoc);
4324}
4325
4326MemInitResult
4327Sema::ActOnMemInitializer(Decl *ConstructorD,
4328 Scope *S,
4329 CXXScopeSpec &SS,
4330 IdentifierInfo *MemberOrBase,
4331 ParsedType TemplateTypeTy,
4332 const DeclSpec &DS,
4333 SourceLocation IdLoc,
4334 SourceLocation LParenLoc,
4335 ArrayRef<Expr *> Args,
4336 SourceLocation RParenLoc,
4337 SourceLocation EllipsisLoc) {
4338 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4339 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4340 DS, IdLoc, Init: List, EllipsisLoc);
4341}
4342
4343namespace {
4344
4345// Callback to only accept typo corrections that can be a valid C++ member
4346// initializer: either a non-static field member or a base class.
4347class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4348public:
4349 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4350 : ClassDecl(ClassDecl) {}
4351
4352 bool ValidateCandidate(const TypoCorrection &candidate) override {
4353 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4354 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4355 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4356 return isa<TypeDecl>(Val: ND);
4357 }
4358 return false;
4359 }
4360
4361 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4362 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4363 }
4364
4365private:
4366 CXXRecordDecl *ClassDecl;
4367};
4368
4369}
4370
4371bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4372 RecordDecl *ClassDecl,
4373 const IdentifierInfo *Name) {
4374 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4375 DeclContextLookupResult::iterator Found =
4376 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4377 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4378 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4379 });
4380 // We did not find a placeholder variable
4381 if (Found == Result.end())
4382 return false;
4383 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4384 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4385 const NamedDecl *ND = *It;
4386 if (ND->getDeclContext() != ND->getDeclContext())
4387 break;
4388 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4389 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4390 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4391 }
4392 return true;
4393}
4394
4395ValueDecl *
4396Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4397 const IdentifierInfo *MemberOrBase) {
4398 ValueDecl *ND = nullptr;
4399 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4400 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4401 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4402 if (ND) {
4403 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4404 return nullptr;
4405 break;
4406 }
4407 if (!IsPlaceholder)
4408 return cast<ValueDecl>(Val: D);
4409 ND = cast<ValueDecl>(Val: D);
4410 }
4411 }
4412 return ND;
4413}
4414
4415ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4416 CXXScopeSpec &SS,
4417 ParsedType TemplateTypeTy,
4418 IdentifierInfo *MemberOrBase) {
4419 if (SS.getScopeRep() || TemplateTypeTy)
4420 return nullptr;
4421 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4422}
4423
4424MemInitResult
4425Sema::BuildMemInitializer(Decl *ConstructorD,
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 if (!ConstructorD || !Init)
4435 return true;
4436
4437 AdjustDeclIfTemplate(Decl&: ConstructorD);
4438
4439 CXXConstructorDecl *Constructor
4440 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4441 if (!Constructor) {
4442 // The user wrote a constructor initializer on a function that is
4443 // not a C++ constructor. Ignore the error for now, because we may
4444 // have more member initializers coming; we'll diagnose it just
4445 // once in ActOnMemInitializers.
4446 return true;
4447 }
4448
4449 CXXRecordDecl *ClassDecl = Constructor->getParent();
4450
4451 // C++ [class.base.init]p2:
4452 // Names in a mem-initializer-id are looked up in the scope of the
4453 // constructor's class and, if not found in that scope, are looked
4454 // up in the scope containing the constructor's definition.
4455 // [Note: if the constructor's class contains a member with the
4456 // same name as a direct or virtual base class of the class, a
4457 // mem-initializer-id naming the member or base class and composed
4458 // of a single identifier refers to the class member. A
4459 // mem-initializer-id for the hidden base class may be specified
4460 // using a qualified name. ]
4461
4462 // Look for a member, first.
4463 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4464 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4465 if (EllipsisLoc.isValid())
4466 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4467 << MemberOrBase
4468 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4469
4470 return BuildMemberInitializer(Member, Init, IdLoc);
4471 }
4472 // It didn't name a member, so see if it names a class.
4473 QualType BaseType;
4474 TypeSourceInfo *TInfo = nullptr;
4475
4476 if (TemplateTypeTy) {
4477 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4478 if (BaseType.isNull())
4479 return true;
4480 } else if (DS.getTypeSpecType() == TST_decltype) {
4481 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4482 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4483 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4484 return true;
4485 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4486 BaseType =
4487 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4488 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4489 } else {
4490 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4491 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4492
4493 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4494 if (!TyD) {
4495 if (R.isAmbiguous()) return true;
4496
4497 // We don't want access-control diagnostics here.
4498 R.suppressDiagnostics();
4499
4500 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4501 bool NotUnknownSpecialization = false;
4502 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4503 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4504 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4505
4506 if (!NotUnknownSpecialization) {
4507 // When the scope specifier can refer to a member of an unknown
4508 // specialization, we take it as a type name.
4509 BaseType = CheckTypenameType(
4510 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4511 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4512 if (BaseType.isNull())
4513 return true;
4514
4515 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4516 DependentNameTypeLoc TL =
4517 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4518 if (!TL.isNull()) {
4519 TL.setNameLoc(IdLoc);
4520 TL.setElaboratedKeywordLoc(SourceLocation());
4521 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4522 }
4523
4524 R.clear();
4525 R.setLookupName(MemberOrBase);
4526 }
4527 }
4528
4529 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4530 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4531 auto *TempSpec = cast<TemplateSpecializationType>(
4532 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4533 TemplateName TN = TempSpec->getTemplateName();
4534 for (auto const &Base : ClassDecl->bases()) {
4535 auto BaseTemplate =
4536 Base.getType()->getAs<TemplateSpecializationType>();
4537 if (BaseTemplate &&
4538 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4539 /*IgnoreDeduced=*/true)) {
4540 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4541 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4542 BaseType = Base.getType();
4543 break;
4544 }
4545 }
4546 }
4547 }
4548
4549 // If no results were found, try to correct typos.
4550 TypoCorrection Corr;
4551 MemInitializerValidatorCCC CCC(ClassDecl);
4552 if (R.empty() && BaseType.isNull() &&
4553 (Corr =
4554 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4555 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4556 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
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(Correction: Corr,
4561 TypoDiag: PDiag(DiagID: 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(SemaRef&: *this, ClassDecl,
4568 BaseType: Context.getTypeDeclType(Decl: Type),
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(Correction: Corr,
4574 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4575 << MemberOrBase << false,
4576 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4577
4578 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4579 : VirtualBaseSpec;
4580 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: 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(Loc: IdLoc, DiagID: 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 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4597
4598 TypeLocBuilder TLB;
4599 // FIXME: This is missing building the UsingType for TyD, if any.
4600 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4601 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4602 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4603 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4604 TL.setElaboratedKeywordLoc(SourceLocation());
4605 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4606 TL.setNameLoc(IdLoc);
4607 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4608 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4609 Qualifier: SS.getScopeRep(), Decl: TN);
4610 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4611 /*ElaboratedKeywordLoc=*/SourceLocation(),
4612 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4613 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4614 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4615 Qualifier: SS.getScopeRep(), D: UD);
4616 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4617 /*ElaboratedKeywordLoc=*/SourceLocation(),
4618 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4619 } else {
4620 // FIXME: What else can appear here?
4621 assert(SS.isEmpty());
4622 BaseType = Context.getTypeDeclType(Decl: TyD);
4623 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4624 }
4625 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4626 }
4627 }
4628
4629 if (!TInfo)
4630 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4631
4632 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4633}
4634
4635MemInitResult
4636Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4637 SourceLocation IdLoc) {
4638 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4639 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4640 assert((DirectMember || IndirectMember) &&
4641 "Member must be a FieldDecl or IndirectFieldDecl");
4642
4643 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4644 return true;
4645
4646 if (Member->isInvalidDecl())
4647 return true;
4648
4649 MultiExprArg Args;
4650 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4651 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4652 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4653 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4654 } else {
4655 // Template instantiation doesn't reconstruct ParenListExprs for us.
4656 Args = Init;
4657 }
4658
4659 SourceRange InitRange = Init->getSourceRange();
4660
4661 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4662 // Can't check initialization for a member of dependent type or when
4663 // any of the arguments are type-dependent expressions.
4664 DiscardCleanupsInEvaluationContext();
4665 } else {
4666 bool InitList = false;
4667 if (isa<InitListExpr>(Val: Init)) {
4668 InitList = true;
4669 Args = Init;
4670 }
4671
4672 // Initialize the member.
4673 InitializedEntity MemberEntity =
4674 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4675 : InitializedEntity::InitializeMember(Member: IndirectMember,
4676 Parent: nullptr);
4677 InitializationKind Kind =
4678 InitList ? InitializationKind::CreateDirectList(
4679 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4680 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4681 RParenLoc: InitRange.getEnd());
4682
4683 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4684 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4685 ResultType: nullptr);
4686 if (!MemberInit.isInvalid()) {
4687 // C++11 [class.base.init]p7:
4688 // The initialization of each base and member constitutes a
4689 // full-expression.
4690 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4691 /*DiscardedValue*/ false);
4692 }
4693
4694 if (MemberInit.isInvalid()) {
4695 // Args were sensible expressions but we couldn't initialize the member
4696 // from them. Preserve them in a RecoveryExpr instead.
4697 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4698 T: Member->getType())
4699 .get();
4700 if (!Init)
4701 return true;
4702 } else {
4703 Init = MemberInit.get();
4704 }
4705 }
4706
4707 if (DirectMember) {
4708 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4709 InitRange.getBegin(), Init,
4710 InitRange.getEnd());
4711 } else {
4712 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4713 InitRange.getBegin(), Init,
4714 InitRange.getEnd());
4715 }
4716}
4717
4718MemInitResult
4719Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4720 CXXRecordDecl *ClassDecl) {
4721 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4722 if (!LangOpts.CPlusPlus11)
4723 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4724 << TInfo->getTypeLoc().getSourceRange();
4725 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4726
4727 bool InitList = true;
4728 MultiExprArg Args = Init;
4729 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4730 InitList = false;
4731 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4732 }
4733
4734 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4735
4736 SourceRange InitRange = Init->getSourceRange();
4737 // Initialize the object.
4738 InitializedEntity DelegationEntity =
4739 InitializedEntity::InitializeDelegation(Type: ClassType);
4740 InitializationKind Kind =
4741 InitList ? InitializationKind::CreateDirectList(
4742 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4743 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4744 RParenLoc: InitRange.getEnd());
4745 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4746 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4747 Args, ResultType: nullptr);
4748 if (!DelegationInit.isInvalid()) {
4749 assert((DelegationInit.get()->containsErrors() ||
4750 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4751 "Delegating constructor with no target?");
4752
4753 // C++11 [class.base.init]p7:
4754 // The initialization of each base and member constitutes a
4755 // full-expression.
4756 DelegationInit = ActOnFinishFullExpr(
4757 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4758 }
4759
4760 if (DelegationInit.isInvalid()) {
4761 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4762 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4763 if (DelegationInit.isInvalid())
4764 return true;
4765 } else {
4766 // If we are in a dependent context, template instantiation will
4767 // perform this type-checking again. Just save the arguments that we
4768 // received in a ParenListExpr.
4769 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4770 // of the information that we have about the base
4771 // initializer. However, deconstructing the ASTs is a dicey process,
4772 // and this approach is far more likely to get the corner cases right.
4773 if (CurContext->isDependentContext())
4774 DelegationInit = Init;
4775 }
4776
4777 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4778 DelegationInit.getAs<Expr>(),
4779 InitRange.getEnd());
4780}
4781
4782MemInitResult
4783Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4784 Expr *Init, CXXRecordDecl *ClassDecl,
4785 SourceLocation EllipsisLoc) {
4786 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4787
4788 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4789 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4790 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4791
4792 // C++ [class.base.init]p2:
4793 // [...] Unless the mem-initializer-id names a nonstatic data
4794 // member of the constructor's class or a direct or virtual base
4795 // of that class, the mem-initializer is ill-formed. A
4796 // mem-initializer-list can initialize a base class using any
4797 // name that denotes that base class type.
4798
4799 // We can store the initializers in "as-written" form and delay analysis until
4800 // instantiation if the constructor is dependent. But not for dependent
4801 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4802 bool Dependent = CurContext->isDependentContext() &&
4803 (BaseType->isDependentType() || Init->isTypeDependent());
4804
4805 SourceRange InitRange = Init->getSourceRange();
4806 if (EllipsisLoc.isValid()) {
4807 // This is a pack expansion.
4808 if (!BaseType->containsUnexpandedParameterPack()) {
4809 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4810 << SourceRange(BaseLoc, InitRange.getEnd());
4811
4812 EllipsisLoc = SourceLocation();
4813 }
4814 } else {
4815 // Check for any unexpanded parameter packs.
4816 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4817 return true;
4818
4819 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4820 return true;
4821 }
4822
4823 // Check for direct and virtual base classes.
4824 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4825 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4826 if (!Dependent) {
4827 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4828 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4829
4830 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4831 VirtualBaseSpec);
4832
4833 // C++ [base.class.init]p2:
4834 // Unless the mem-initializer-id names a nonstatic data member of the
4835 // constructor's class or a direct or virtual base of that class, the
4836 // mem-initializer is ill-formed.
4837 if (!DirectBaseSpec && !VirtualBaseSpec) {
4838 // If the class has any dependent bases, then it's possible that
4839 // one of those types will resolve to the same type as
4840 // BaseType. Therefore, just treat this as a dependent base
4841 // class initialization. FIXME: Should we try to check the
4842 // initialization anyway? It seems odd.
4843 if (ClassDecl->hasAnyDependentBases())
4844 Dependent = true;
4845 else
4846 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4847 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4848 << BaseTInfo->getTypeLoc().getSourceRange();
4849 }
4850 }
4851
4852 if (Dependent) {
4853 DiscardCleanupsInEvaluationContext();
4854
4855 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4856 /*IsVirtual=*/false,
4857 InitRange.getBegin(), Init,
4858 InitRange.getEnd(), EllipsisLoc);
4859 }
4860
4861 // C++ [base.class.init]p2:
4862 // If a mem-initializer-id is ambiguous because it designates both
4863 // a direct non-virtual base class and an inherited virtual base
4864 // class, the mem-initializer is ill-formed.
4865 if (DirectBaseSpec && VirtualBaseSpec)
4866 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4867 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4868
4869 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4870 if (!BaseSpec)
4871 BaseSpec = VirtualBaseSpec;
4872
4873 // Initialize the base.
4874 bool InitList = true;
4875 MultiExprArg Args = Init;
4876 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4877 InitList = false;
4878 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4879 }
4880
4881 InitializedEntity BaseEntity =
4882 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4883 InitializationKind Kind =
4884 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4885 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4886 RParenLoc: InitRange.getEnd());
4887 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4888 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4889 if (!BaseInit.isInvalid()) {
4890 // C++11 [class.base.init]p7:
4891 // The initialization of each base and member constitutes a
4892 // full-expression.
4893 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4894 /*DiscardedValue*/ false);
4895 }
4896
4897 if (BaseInit.isInvalid()) {
4898 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4899 SubExprs: Args, T: BaseType);
4900 if (BaseInit.isInvalid())
4901 return true;
4902 } else {
4903 // If we are in a dependent context, template instantiation will
4904 // perform this type-checking again. Just save the arguments that we
4905 // received in a ParenListExpr.
4906 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4907 // of the information that we have about the base
4908 // initializer. However, deconstructing the ASTs is a dicey process,
4909 // and this approach is far more likely to get the corner cases right.
4910 if (CurContext->isDependentContext())
4911 BaseInit = Init;
4912 }
4913
4914 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4915 BaseSpec->isVirtual(),
4916 InitRange.getBegin(),
4917 BaseInit.getAs<Expr>(),
4918 InitRange.getEnd(), EllipsisLoc);
4919}
4920
4921// Create a static_cast\<T&&>(expr).
4922static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4923 QualType TargetType =
4924 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4925 Loc: SourceLocation(), Entity: DeclarationName());
4926 SourceLocation ExprLoc = E->getBeginLoc();
4927 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4928 T: TargetType, Loc: ExprLoc);
4929
4930 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4931 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4932 Parens: E->getSourceRange()).get();
4933}
4934
4935/// ImplicitInitializerKind - How an implicit base or member initializer should
4936/// initialize its base or member.
4937enum ImplicitInitializerKind {
4938 IIK_Default,
4939 IIK_Copy,
4940 IIK_Move,
4941 IIK_Inherit
4942};
4943
4944static bool
4945BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4946 ImplicitInitializerKind ImplicitInitKind,
4947 CXXBaseSpecifier *BaseSpec,
4948 bool IsInheritedVirtualBase,
4949 CXXCtorInitializer *&CXXBaseInit) {
4950 InitializedEntity InitEntity
4951 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4952 IsInheritedVirtualBase);
4953
4954 ExprResult BaseInit;
4955
4956 switch (ImplicitInitKind) {
4957 case IIK_Inherit:
4958 case IIK_Default: {
4959 InitializationKind InitKind
4960 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4961 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4962 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4963 break;
4964 }
4965
4966 case IIK_Move:
4967 case IIK_Copy: {
4968 bool Moving = ImplicitInitKind == IIK_Move;
4969 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
4970 QualType ParamType = Param->getType().getNonReferenceType();
4971
4972 Expr *CopyCtorArg =
4973 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
4974 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
4975 NameLoc: Constructor->getLocation(), T: ParamType,
4976 VK: VK_LValue, FoundD: nullptr);
4977
4978 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4979
4980 // Cast to the base class to avoid ambiguities.
4981 QualType ArgTy =
4982 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4983 Qs: ParamType.getQualifiers());
4984
4985 if (Moving) {
4986 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4987 }
4988
4989 CXXCastPath BasePath;
4990 BasePath.push_back(Elt: BaseSpec);
4991 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4992 CK: CK_UncheckedDerivedToBase,
4993 VK: Moving ? VK_XValue : VK_LValue,
4994 BasePath: &BasePath).get();
4995
4996 InitializationKind InitKind
4997 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4998 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4999 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5000 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
5001 break;
5002 }
5003 }
5004
5005 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
5006 if (BaseInit.isInvalid())
5007 return true;
5008
5009 CXXBaseInit =
5010 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5011 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5012 Loc: SourceLocation()),
5013 BaseSpec->isVirtual(),
5014 SourceLocation(),
5015 BaseInit.getAs<Expr>(),
5016 SourceLocation(),
5017 SourceLocation());
5018
5019 return false;
5020}
5021
5022static bool RefersToRValueRef(Expr *MemRef) {
5023 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5024 return Referenced->getType()->isRValueReferenceType();
5025}
5026
5027static bool
5028BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5029 ImplicitInitializerKind ImplicitInitKind,
5030 FieldDecl *Field, IndirectFieldDecl *Indirect,
5031 CXXCtorInitializer *&CXXMemberInit) {
5032 if (Field->isInvalidDecl())
5033 return true;
5034
5035 SourceLocation Loc = Constructor->getLocation();
5036
5037 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5038 bool Moving = ImplicitInitKind == IIK_Move;
5039 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5040 QualType ParamType = Param->getType().getNonReferenceType();
5041
5042 // Suppress copying zero-width bitfields.
5043 if (Field->isZeroLengthBitField())
5044 return false;
5045
5046 Expr *MemberExprBase =
5047 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5048 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5049 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5050
5051 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5052
5053 if (Moving) {
5054 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5055 }
5056
5057 // Build a reference to this field within the parameter.
5058 CXXScopeSpec SS;
5059 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5060 Sema::LookupMemberName);
5061 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5062 : cast<ValueDecl>(Val: Field), AS: AS_public);
5063 MemberLookup.resolveKind();
5064 ExprResult CtorArg
5065 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5066 BaseType: ParamType, OpLoc: Loc,
5067 /*IsArrow=*/false,
5068 SS,
5069 /*TemplateKWLoc=*/SourceLocation(),
5070 /*FirstQualifierInScope=*/nullptr,
5071 R&: MemberLookup,
5072 /*TemplateArgs=*/nullptr,
5073 /*S*/nullptr);
5074 if (CtorArg.isInvalid())
5075 return true;
5076
5077 // C++11 [class.copy]p15:
5078 // - if a member m has rvalue reference type T&&, it is direct-initialized
5079 // with static_cast<T&&>(x.m);
5080 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5081 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5082 }
5083
5084 InitializedEntity Entity =
5085 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5086 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5087
5088 // Direct-initialize to use the copy constructor.
5089 InitializationKind InitKind =
5090 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5091
5092 Expr *CtorArgE = CtorArg.getAs<Expr>();
5093 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5094 ExprResult MemberInit =
5095 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5096 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5097 if (MemberInit.isInvalid())
5098 return true;
5099
5100 if (Indirect)
5101 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5102 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5103 else
5104 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5105 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5106 return false;
5107 }
5108
5109 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5110 "Unhandled implicit init kind!");
5111
5112 QualType FieldBaseElementType =
5113 SemaRef.Context.getBaseElementType(QT: Field->getType());
5114
5115 if (FieldBaseElementType->isRecordType()) {
5116 InitializedEntity InitEntity =
5117 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5118 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5119 InitializationKind InitKind =
5120 InitializationKind::CreateDefault(InitLoc: Loc);
5121
5122 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5123 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5124
5125 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5126 if (MemberInit.isInvalid())
5127 return true;
5128
5129 if (Indirect)
5130 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5131 Indirect, Loc,
5132 Loc,
5133 MemberInit.get(),
5134 Loc);
5135 else
5136 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5137 Field, Loc, Loc,
5138 MemberInit.get(),
5139 Loc);
5140 return false;
5141 }
5142
5143 if (!Field->getParent()->isUnion()) {
5144 if (FieldBaseElementType->isReferenceType()) {
5145 SemaRef.Diag(Loc: Constructor->getLocation(),
5146 DiagID: diag::err_uninitialized_member_in_ctor)
5147 << (int)Constructor->isImplicit()
5148 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5149 << Field->getDeclName();
5150 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5151 return true;
5152 }
5153
5154 if (FieldBaseElementType.isConstQualified()) {
5155 SemaRef.Diag(Loc: Constructor->getLocation(),
5156 DiagID: diag::err_uninitialized_member_in_ctor)
5157 << (int)Constructor->isImplicit()
5158 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5159 << Field->getDeclName();
5160 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5161 return true;
5162 }
5163 }
5164
5165 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5166 // ARC and Weak:
5167 // Default-initialize Objective-C pointers to NULL.
5168 CXXMemberInit
5169 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5170 Loc, Loc,
5171 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5172 Loc);
5173 return false;
5174 }
5175
5176 // Nothing to initialize.
5177 CXXMemberInit = nullptr;
5178 return false;
5179}
5180
5181namespace {
5182struct BaseAndFieldInfo {
5183 Sema &S;
5184 CXXConstructorDecl *Ctor;
5185 bool AnyErrorsInInits;
5186 ImplicitInitializerKind IIK;
5187 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5188 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5189 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5190
5191 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5192 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5193 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5194 if (Ctor->getInheritedConstructor())
5195 IIK = IIK_Inherit;
5196 else if (Generated && Ctor->isCopyConstructor())
5197 IIK = IIK_Copy;
5198 else if (Generated && Ctor->isMoveConstructor())
5199 IIK = IIK_Move;
5200 else
5201 IIK = IIK_Default;
5202 }
5203
5204 bool isImplicitCopyOrMove() const {
5205 switch (IIK) {
5206 case IIK_Copy:
5207 case IIK_Move:
5208 return true;
5209
5210 case IIK_Default:
5211 case IIK_Inherit:
5212 return false;
5213 }
5214
5215 llvm_unreachable("Invalid ImplicitInitializerKind!");
5216 }
5217
5218 bool addFieldInitializer(CXXCtorInitializer *Init) {
5219 AllToInit.push_back(Elt: Init);
5220
5221 // Check whether this initializer makes the field "used".
5222 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5223 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5224
5225 return false;
5226 }
5227
5228 bool isInactiveUnionMember(FieldDecl *Field) {
5229 RecordDecl *Record = Field->getParent();
5230 if (!Record->isUnion())
5231 return false;
5232
5233 if (FieldDecl *Active =
5234 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5235 return Active != Field->getCanonicalDecl();
5236
5237 // In an implicit copy or move constructor, ignore any in-class initializer.
5238 if (isImplicitCopyOrMove())
5239 return true;
5240
5241 // If there's no explicit initialization, the field is active only if it
5242 // has an in-class initializer...
5243 if (Field->hasInClassInitializer())
5244 return false;
5245 // ... or it's an anonymous struct or union whose class has an in-class
5246 // initializer.
5247 if (!Field->isAnonymousStructOrUnion())
5248 return true;
5249 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5250 return !FieldRD->hasInClassInitializer();
5251 }
5252
5253 /// Determine whether the given field is, or is within, a union member
5254 /// that is inactive (because there was an initializer given for a different
5255 /// member of the union, or because the union was not initialized at all).
5256 bool isWithinInactiveUnionMember(FieldDecl *Field,
5257 IndirectFieldDecl *Indirect) {
5258 if (!Indirect)
5259 return isInactiveUnionMember(Field);
5260
5261 for (auto *C : Indirect->chain()) {
5262 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5263 if (Field && isInactiveUnionMember(Field))
5264 return true;
5265 }
5266 return false;
5267 }
5268};
5269}
5270
5271/// Determine whether the given type is an incomplete or zero-lenfgth
5272/// array type.
5273static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5274 if (T->isIncompleteArrayType())
5275 return true;
5276
5277 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5278 if (ArrayT->isZeroSize())
5279 return true;
5280
5281 T = ArrayT->getElementType();
5282 }
5283
5284 return false;
5285}
5286
5287static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5288 FieldDecl *Field,
5289 IndirectFieldDecl *Indirect = nullptr) {
5290 if (Field->isInvalidDecl())
5291 return false;
5292
5293 // Overwhelmingly common case: we have a direct initializer for this field.
5294 if (CXXCtorInitializer *Init =
5295 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5296 return Info.addFieldInitializer(Init);
5297
5298 // C++11 [class.base.init]p8:
5299 // if the entity is a non-static data member that has a
5300 // brace-or-equal-initializer and either
5301 // -- the constructor's class is a union and no other variant member of that
5302 // union is designated by a mem-initializer-id or
5303 // -- the constructor's class is not a union, and, if the entity is a member
5304 // of an anonymous union, no other member of that union is designated by
5305 // a mem-initializer-id,
5306 // the entity is initialized as specified in [dcl.init].
5307 //
5308 // We also apply the same rules to handle anonymous structs within anonymous
5309 // unions.
5310 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5311 return false;
5312
5313 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5314 ExprResult DIE =
5315 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5316 if (DIE.isInvalid())
5317 return true;
5318
5319 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5320 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5321
5322 CXXCtorInitializer *Init;
5323 if (Indirect)
5324 Init = new (SemaRef.Context)
5325 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5326 SourceLocation(), DIE.get(), SourceLocation());
5327 else
5328 Init = new (SemaRef.Context)
5329 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5330 SourceLocation(), DIE.get(), SourceLocation());
5331 return Info.addFieldInitializer(Init);
5332 }
5333
5334 // Don't initialize incomplete or zero-length arrays.
5335 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5336 return false;
5337
5338 // Don't try to build an implicit initializer if there were semantic
5339 // errors in any of the initializers (and therefore we might be
5340 // missing some that the user actually wrote).
5341 if (Info.AnyErrorsInInits)
5342 return false;
5343
5344 CXXCtorInitializer *Init = nullptr;
5345 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5346 Indirect, CXXMemberInit&: Init))
5347 return true;
5348
5349 if (!Init)
5350 return false;
5351
5352 return Info.addFieldInitializer(Init);
5353}
5354
5355bool
5356Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5357 CXXCtorInitializer *Initializer) {
5358 assert(Initializer->isDelegatingInitializer());
5359 Constructor->setNumCtorInitializers(1);
5360 CXXCtorInitializer **initializer =
5361 new (Context) CXXCtorInitializer*[1];
5362 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5363 Constructor->setCtorInitializers(initializer);
5364
5365 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5366 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5367 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5368 }
5369
5370 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5371
5372 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5373
5374 return false;
5375}
5376
5377static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5378 CXXRecordDecl *Class) {
5379 if (Class->isInvalidDecl())
5380 return nullptr;
5381 if (Class->hasIrrelevantDestructor())
5382 return nullptr;
5383
5384 // Dtor might still be missing, e.g because it's invalid.
5385 return S.LookupDestructor(Class);
5386}
5387
5388static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5389 FieldDecl *Field) {
5390 if (Field->isInvalidDecl())
5391 return;
5392
5393 // Don't destroy incomplete or zero-length arrays.
5394 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5395 return;
5396
5397 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5398
5399 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5400 if (!FieldClassDecl)
5401 return;
5402
5403 // The destructor for an implicit anonymous union member is never invoked.
5404 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5405 return;
5406
5407 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5408 if (!Dtor)
5409 return;
5410
5411 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5412 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5413 << Field->getDeclName() << FieldType);
5414
5415 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5416 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5417}
5418
5419static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5420 CXXRecordDecl *ClassDecl) {
5421 if (ClassDecl->isDependentContext())
5422 return;
5423
5424 // We only potentially invoke the destructors of potentially constructed
5425 // subobjects.
5426 bool VisitVirtualBases = !ClassDecl->isAbstract();
5427
5428 // If the destructor exists and has already been marked used in the MS ABI,
5429 // then virtual base destructors have already been checked and marked used.
5430 // Skip checking them again to avoid duplicate diagnostics.
5431 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5432 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5433 if (Dtor && Dtor->isUsed())
5434 VisitVirtualBases = false;
5435 }
5436
5437 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5438
5439 // Bases.
5440 for (const auto &Base : ClassDecl->bases()) {
5441 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5442 if (!BaseClassDecl)
5443 continue;
5444
5445 // Remember direct virtual bases.
5446 if (Base.isVirtual()) {
5447 if (!VisitVirtualBases)
5448 continue;
5449 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5450 }
5451
5452 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5453 if (!Dtor)
5454 continue;
5455
5456 // FIXME: caret should be on the start of the class name
5457 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5458 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5459 << Base.getType() << Base.getSourceRange(),
5460 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5461
5462 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5463 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5464 }
5465
5466 if (VisitVirtualBases)
5467 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5468 DirectVirtualBases: &DirectVirtualBases);
5469}
5470
5471bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5472 ArrayRef<CXXCtorInitializer *> Initializers) {
5473 if (Constructor->isDependentContext()) {
5474 // Just store the initializers as written, they will be checked during
5475 // instantiation.
5476 if (!Initializers.empty()) {
5477 Constructor->setNumCtorInitializers(Initializers.size());
5478 CXXCtorInitializer **baseOrMemberInitializers =
5479 new (Context) CXXCtorInitializer*[Initializers.size()];
5480 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5481 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5482 Constructor->setCtorInitializers(baseOrMemberInitializers);
5483 }
5484
5485 // Let template instantiation know whether we had errors.
5486 if (AnyErrors)
5487 Constructor->setInvalidDecl();
5488
5489 return false;
5490 }
5491
5492 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5493
5494 // We need to build the initializer AST according to order of construction
5495 // and not what user specified in the Initializers list.
5496 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5497 if (!ClassDecl)
5498 return true;
5499
5500 bool HadError = false;
5501
5502 for (CXXCtorInitializer *Member : Initializers) {
5503 if (Member->isBaseInitializer())
5504 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5505 Member;
5506 else {
5507 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5508
5509 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5510 for (auto *C : F->chain()) {
5511 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5512 if (FD && FD->getParent()->isUnion())
5513 Info.ActiveUnionMember.insert(KV: std::make_pair(
5514 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5515 }
5516 } else if (FieldDecl *FD = Member->getMember()) {
5517 if (FD->getParent()->isUnion())
5518 Info.ActiveUnionMember.insert(KV: std::make_pair(
5519 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5520 }
5521 }
5522 }
5523
5524 // Keep track of the direct virtual bases.
5525 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5526 for (auto &I : ClassDecl->bases()) {
5527 if (I.isVirtual())
5528 DirectVBases.insert(Ptr: &I);
5529 }
5530
5531 // Push virtual bases before others.
5532 for (auto &VBase : ClassDecl->vbases()) {
5533 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5534 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5535 // [class.base.init]p7, per DR257:
5536 // A mem-initializer where the mem-initializer-id names a virtual base
5537 // class is ignored during execution of a constructor of any class that
5538 // is not the most derived class.
5539 if (ClassDecl->isAbstract()) {
5540 // FIXME: Provide a fixit to remove the base specifier. This requires
5541 // tracking the location of the associated comma for a base specifier.
5542 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5543 << VBase.getType() << ClassDecl;
5544 DiagnoseAbstractType(RD: ClassDecl);
5545 }
5546
5547 Info.AllToInit.push_back(Elt: Value);
5548 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5549 // [class.base.init]p8, per DR257:
5550 // If a given [...] base class is not named by a mem-initializer-id
5551 // [...] and the entity is not a virtual base class of an abstract
5552 // class, then [...] the entity is default-initialized.
5553 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5554 CXXCtorInitializer *CXXBaseInit;
5555 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5556 BaseSpec: &VBase, IsInheritedVirtualBase,
5557 CXXBaseInit)) {
5558 HadError = true;
5559 continue;
5560 }
5561
5562 Info.AllToInit.push_back(Elt: CXXBaseInit);
5563 }
5564 }
5565
5566 // Non-virtual bases.
5567 for (auto &Base : ClassDecl->bases()) {
5568 // Virtuals are in the virtual base list and already constructed.
5569 if (Base.isVirtual())
5570 continue;
5571
5572 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5573 Val: Base.getType()->getAsCanonical<RecordType>())) {
5574 Info.AllToInit.push_back(Elt: Value);
5575 } else if (!AnyErrors) {
5576 CXXCtorInitializer *CXXBaseInit;
5577 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5578 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5579 CXXBaseInit)) {
5580 HadError = true;
5581 continue;
5582 }
5583
5584 Info.AllToInit.push_back(Elt: CXXBaseInit);
5585 }
5586 }
5587
5588 // Fields.
5589 for (auto *Mem : ClassDecl->decls()) {
5590 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5591 // C++ [class.bit]p2:
5592 // A declaration for a bit-field that omits the identifier declares an
5593 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5594 // initialized.
5595 if (F->isUnnamedBitField())
5596 continue;
5597
5598 // If we're not generating the implicit copy/move constructor, then we'll
5599 // handle anonymous struct/union fields based on their individual
5600 // indirect fields.
5601 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5602 continue;
5603
5604 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5605 HadError = true;
5606 continue;
5607 }
5608
5609 // Beyond this point, we only consider default initialization.
5610 if (Info.isImplicitCopyOrMove())
5611 continue;
5612
5613 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5614 if (F->getType()->isIncompleteArrayType()) {
5615 assert(ClassDecl->hasFlexibleArrayMember() &&
5616 "Incomplete array type is not valid");
5617 continue;
5618 }
5619
5620 // Initialize each field of an anonymous struct individually.
5621 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5622 HadError = true;
5623
5624 continue;
5625 }
5626 }
5627
5628 unsigned NumInitializers = Info.AllToInit.size();
5629 if (NumInitializers > 0) {
5630 Constructor->setNumCtorInitializers(NumInitializers);
5631 CXXCtorInitializer **baseOrMemberInitializers =
5632 new (Context) CXXCtorInitializer*[NumInitializers];
5633 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5634 n: NumInitializers * sizeof(CXXCtorInitializer*));
5635 Constructor->setCtorInitializers(baseOrMemberInitializers);
5636
5637 SourceLocation Location = Constructor->getLocation();
5638
5639 // Constructors implicitly reference the base and member
5640 // destructors.
5641
5642 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5643 FieldDecl *Field = Initializer->getAnyMember();
5644 if (!Field)
5645 continue;
5646
5647 // C++ [class.base.init]p12:
5648 // In a non-delegating constructor, the destructor for each
5649 // potentially constructed subobject of class type is potentially
5650 // invoked.
5651 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5652 }
5653
5654 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5655 }
5656
5657 return HadError;
5658}
5659
5660static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5661 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5662 const RecordDecl *RD = RT->getDecl();
5663 if (RD->isAnonymousStructOrUnion()) {
5664 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5665 PopulateKeysForFields(Field, IdealInits);
5666 return;
5667 }
5668 }
5669 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5670}
5671
5672static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5673 return Context.getCanonicalType(T: BaseType).getTypePtr();
5674}
5675
5676static const void *GetKeyForMember(ASTContext &Context,
5677 CXXCtorInitializer *Member) {
5678 if (!Member->isAnyMemberInitializer())
5679 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5680
5681 return Member->getAnyMember()->getCanonicalDecl();
5682}
5683
5684static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5685 const CXXCtorInitializer *Previous,
5686 const CXXCtorInitializer *Current) {
5687 if (Previous->isAnyMemberInitializer())
5688 Diag << 0 << Previous->getAnyMember();
5689 else
5690 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5691
5692 if (Current->isAnyMemberInitializer())
5693 Diag << 0 << Current->getAnyMember();
5694 else
5695 Diag << 1 << Current->getTypeSourceInfo()->getType();
5696}
5697
5698static void DiagnoseBaseOrMemInitializerOrder(
5699 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5700 ArrayRef<CXXCtorInitializer *> Inits) {
5701 if (Constructor->getDeclContext()->isDependentContext())
5702 return;
5703
5704 // Don't check initializers order unless the warning is enabled at the
5705 // location of at least one initializer.
5706 bool ShouldCheckOrder = false;
5707 for (const CXXCtorInitializer *Init : Inits) {
5708 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5709 Loc: Init->getSourceLocation())) {
5710 ShouldCheckOrder = true;
5711 break;
5712 }
5713 }
5714 if (!ShouldCheckOrder)
5715 return;
5716
5717 // Build the list of bases and members in the order that they'll
5718 // actually be initialized. The explicit initializers should be in
5719 // this same order but may be missing things.
5720 SmallVector<const void*, 32> IdealInitKeys;
5721
5722 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5723
5724 // 1. Virtual bases.
5725 for (const auto &VBase : ClassDecl->vbases())
5726 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5727
5728 // 2. Non-virtual bases.
5729 for (const auto &Base : ClassDecl->bases()) {
5730 if (Base.isVirtual())
5731 continue;
5732 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5733 }
5734
5735 // 3. Direct fields.
5736 for (auto *Field : ClassDecl->fields()) {
5737 if (Field->isUnnamedBitField())
5738 continue;
5739
5740 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5741 }
5742
5743 unsigned NumIdealInits = IdealInitKeys.size();
5744 unsigned IdealIndex = 0;
5745
5746 // Track initializers that are in an incorrect order for either a warning or
5747 // note if multiple ones occur.
5748 SmallVector<unsigned> WarnIndexes;
5749 // Correlates the index of an initializer in the init-list to the index of
5750 // the field/base in the class.
5751 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5752
5753 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5754 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5755
5756 // Scan forward to try to find this initializer in the idealized
5757 // initializers list.
5758 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5759 if (InitKey == IdealInitKeys[IdealIndex])
5760 break;
5761
5762 // If we didn't find this initializer, it must be because we
5763 // scanned past it on a previous iteration. That can only
5764 // happen if we're out of order; emit a warning.
5765 if (IdealIndex == NumIdealInits && InitIndex) {
5766 WarnIndexes.push_back(Elt: InitIndex);
5767
5768 // Move back to the initializer's location in the ideal list.
5769 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5770 if (InitKey == IdealInitKeys[IdealIndex])
5771 break;
5772
5773 assert(IdealIndex < NumIdealInits &&
5774 "initializer not found in initializer list");
5775 }
5776 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5777 }
5778
5779 if (WarnIndexes.empty())
5780 return;
5781
5782 // Sort based on the ideal order, first in the pair.
5783 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5784
5785 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5786 // emit the diagnostic before we can try adding notes.
5787 {
5788 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5789 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5790 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5791 : diag::warn_some_initializers_out_of_order);
5792
5793 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5794 if (CorrelatedInitOrder[I].second == I)
5795 continue;
5796 // Ideally we would be using InsertFromRange here, but clang doesn't
5797 // appear to handle InsertFromRange correctly when the source range is
5798 // modified by another fix-it.
5799 D << FixItHint::CreateReplacement(
5800 RemoveRange: Inits[I]->getSourceRange(),
5801 Code: Lexer::getSourceText(
5802 Range: CharSourceRange::getTokenRange(
5803 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5804 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5805 }
5806
5807 // If there is only 1 item out of order, the warning expects the name and
5808 // type of each being added to it.
5809 if (WarnIndexes.size() == 1) {
5810 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5811 Current: Inits[WarnIndexes.front()]);
5812 return;
5813 }
5814 }
5815 // More than 1 item to warn, create notes letting the user know which ones
5816 // are bad.
5817 for (unsigned WarnIndex : WarnIndexes) {
5818 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5819 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5820 DiagID: diag::note_initializer_out_of_order);
5821 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5822 D << PrevInit->getSourceRange();
5823 }
5824}
5825
5826namespace {
5827bool CheckRedundantInit(Sema &S,
5828 CXXCtorInitializer *Init,
5829 CXXCtorInitializer *&PrevInit) {
5830 if (!PrevInit) {
5831 PrevInit = Init;
5832 return false;
5833 }
5834
5835 if (FieldDecl *Field = Init->getAnyMember())
5836 S.Diag(Loc: Init->getSourceLocation(),
5837 DiagID: diag::err_multiple_mem_initialization)
5838 << Field->getDeclName()
5839 << Init->getSourceRange();
5840 else {
5841 const Type *BaseClass = Init->getBaseClass();
5842 assert(BaseClass && "neither field nor base");
5843 S.Diag(Loc: Init->getSourceLocation(),
5844 DiagID: diag::err_multiple_base_initialization)
5845 << QualType(BaseClass, 0)
5846 << Init->getSourceRange();
5847 }
5848 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5849 << 0 << PrevInit->getSourceRange();
5850
5851 return true;
5852}
5853
5854typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5855typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5856
5857bool CheckRedundantUnionInit(Sema &S,
5858 CXXCtorInitializer *Init,
5859 RedundantUnionMap &Unions) {
5860 FieldDecl *Field = Init->getAnyMember();
5861 RecordDecl *Parent = Field->getParent();
5862 NamedDecl *Child = Field;
5863
5864 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5865 if (Parent->isUnion()) {
5866 UnionEntry &En = Unions[Parent];
5867 if (En.first && En.first != Child) {
5868 S.Diag(Loc: Init->getSourceLocation(),
5869 DiagID: diag::err_multiple_mem_union_initialization)
5870 << Field->getDeclName()
5871 << Init->getSourceRange();
5872 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5873 << 0 << En.second->getSourceRange();
5874 return true;
5875 }
5876 if (!En.first) {
5877 En.first = Child;
5878 En.second = Init;
5879 }
5880 if (!Parent->isAnonymousStructOrUnion())
5881 return false;
5882 }
5883
5884 Child = Parent;
5885 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5886 }
5887
5888 return false;
5889}
5890} // namespace
5891
5892void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5893 SourceLocation ColonLoc,
5894 ArrayRef<CXXCtorInitializer*> MemInits,
5895 bool AnyErrors) {
5896 if (!ConstructorDecl)
5897 return;
5898
5899 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5900
5901 CXXConstructorDecl *Constructor
5902 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5903
5904 if (!Constructor) {
5905 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5906 return;
5907 }
5908
5909 // Mapping for the duplicate initializers check.
5910 // For member initializers, this is keyed with a FieldDecl*.
5911 // For base initializers, this is keyed with a Type*.
5912 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5913
5914 // Mapping for the inconsistent anonymous-union initializers check.
5915 RedundantUnionMap MemberUnions;
5916
5917 bool HadError = false;
5918 for (unsigned i = 0; i < MemInits.size(); i++) {
5919 CXXCtorInitializer *Init = MemInits[i];
5920
5921 // Set the source order index.
5922 Init->setSourceOrder(i);
5923
5924 if (Init->isAnyMemberInitializer()) {
5925 const void *Key = GetKeyForMember(Context, Member: Init);
5926 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5927 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5928 HadError = true;
5929 } else if (Init->isBaseInitializer()) {
5930 const void *Key = GetKeyForMember(Context, Member: Init);
5931 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5932 HadError = true;
5933 } else {
5934 assert(Init->isDelegatingInitializer());
5935 // This must be the only initializer
5936 if (MemInits.size() != 1) {
5937 Diag(Loc: Init->getSourceLocation(),
5938 DiagID: diag::err_delegating_initializer_alone)
5939 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5940 // We will treat this as being the only initializer.
5941 }
5942 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5943 // Return immediately as the initializer is set.
5944 return;
5945 }
5946 }
5947
5948 if (HadError)
5949 return;
5950
5951 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5952
5953 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5954
5955 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5956}
5957
5958void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5959 CXXRecordDecl *ClassDecl) {
5960 // Ignore dependent contexts. Also ignore unions, since their members never
5961 // have destructors implicitly called.
5962 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5963 return;
5964
5965 // FIXME: all the access-control diagnostics are positioned on the
5966 // field/base declaration. That's probably good; that said, the
5967 // user might reasonably want to know why the destructor is being
5968 // emitted, and we currently don't say.
5969
5970 // Non-static data members.
5971 for (auto *Field : ClassDecl->fields()) {
5972 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5973 }
5974
5975 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
5976}
5977
5978void Sema::MarkVirtualBaseDestructorsReferenced(
5979 SourceLocation Location, CXXRecordDecl *ClassDecl,
5980 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5981 // Virtual bases.
5982 for (const auto &VBase : ClassDecl->vbases()) {
5983 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5984 if (!BaseClassDecl)
5985 continue;
5986
5987 // Ignore already visited direct virtual bases.
5988 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
5989 continue;
5990
5991 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
5992 if (!Dtor)
5993 continue;
5994
5995 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
5996 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
5997 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
5998 << CT << VBase.getType(),
5999 objectType: CT) == AR_accessible) {
6000 CheckDerivedToBaseConversion(
6001 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
6002 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
6003 }
6004
6005 MarkFunctionReferenced(Loc: Location, Func: Dtor);
6006 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
6007 }
6008}
6009
6010void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
6011 if (!CDtorDecl)
6012 return;
6013
6014 if (CXXConstructorDecl *Constructor
6015 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6016 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6017 !ClassDecl || ClassDecl->isInvalidDecl()) {
6018 return;
6019 }
6020 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6021 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6022 }
6023}
6024
6025bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6026 if (!getLangOpts().CPlusPlus)
6027 return false;
6028
6029 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6030 if (!RD)
6031 return false;
6032
6033 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6034 // class template specialization here, but doing so breaks a lot of code.
6035
6036 // We can't answer whether something is abstract until it has a
6037 // definition. If it's currently being defined, we'll walk back
6038 // over all the declarations when we have a full definition.
6039 const CXXRecordDecl *Def = RD->getDefinition();
6040 if (!Def || Def->isBeingDefined())
6041 return false;
6042
6043 return RD->isAbstract();
6044}
6045
6046bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6047 TypeDiagnoser &Diagnoser) {
6048 if (!isAbstractType(Loc, T))
6049 return false;
6050
6051 T = Context.getBaseElementType(QT: T);
6052 Diagnoser.diagnose(S&: *this, Loc, T);
6053 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6054 return true;
6055}
6056
6057void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6058 // Check if we've already emitted the list of pure virtual functions
6059 // for this class.
6060 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6061 return;
6062
6063 // If the diagnostic is suppressed, don't emit the notes. We're only
6064 // going to emit them once, so try to attach them to a diagnostic we're
6065 // actually going to show.
6066 if (Diags.isLastDiagnosticIgnored())
6067 return;
6068
6069 CXXFinalOverriderMap FinalOverriders;
6070 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6071
6072 // Keep a set of seen pure methods so we won't diagnose the same method
6073 // more than once.
6074 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6075
6076 for (const auto &M : FinalOverriders) {
6077 for (const auto &SO : M.second) {
6078 // C++ [class.abstract]p4:
6079 // A class is abstract if it contains or inherits at least one
6080 // pure virtual function for which the final overrider is pure
6081 // virtual.
6082
6083 if (SO.second.size() != 1)
6084 continue;
6085 const CXXMethodDecl *Method = SO.second.front().Method;
6086
6087 if (!Method->isPureVirtual())
6088 continue;
6089
6090 if (!SeenPureMethods.insert(Ptr: Method).second)
6091 continue;
6092
6093 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6094 << Method->getDeclName() << RD->getDeclName();
6095 }
6096 }
6097
6098 if (!PureVirtualClassDiagSet)
6099 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6100 PureVirtualClassDiagSet->insert(Ptr: RD);
6101}
6102
6103namespace {
6104struct AbstractUsageInfo {
6105 Sema &S;
6106 CXXRecordDecl *Record;
6107 CanQualType AbstractType;
6108 bool Invalid;
6109
6110 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6111 : S(S), Record(Record),
6112 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6113
6114 void DiagnoseAbstractType() {
6115 if (Invalid) return;
6116 S.DiagnoseAbstractType(RD: Record);
6117 Invalid = true;
6118 }
6119
6120 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6121};
6122
6123struct CheckAbstractUsage {
6124 AbstractUsageInfo &Info;
6125 const NamedDecl *Ctx;
6126
6127 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6128 : Info(Info), Ctx(Ctx) {}
6129
6130 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6131 switch (TL.getTypeLocClass()) {
6132#define ABSTRACT_TYPELOC(CLASS, PARENT)
6133#define TYPELOC(CLASS, PARENT) \
6134 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6135#include "clang/AST/TypeLocNodes.def"
6136 }
6137 }
6138
6139 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6140 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6141 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6142 if (!TL.getParam(i: I))
6143 continue;
6144
6145 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6146 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6147 }
6148 }
6149
6150 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6151 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6152 }
6153
6154 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6155 // Visit the type parameters from a permissive context.
6156 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6157 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6158 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6159 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6160 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6161 // TODO: other template argument types?
6162 }
6163 }
6164
6165 // Visit pointee types from a permissive context.
6166#define CheckPolymorphic(Type) \
6167 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6168 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6169 }
6170 CheckPolymorphic(PointerTypeLoc)
6171 CheckPolymorphic(ReferenceTypeLoc)
6172 CheckPolymorphic(MemberPointerTypeLoc)
6173 CheckPolymorphic(BlockPointerTypeLoc)
6174 CheckPolymorphic(AtomicTypeLoc)
6175
6176 /// Handle all the types we haven't given a more specific
6177 /// implementation for above.
6178 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6179 // Every other kind of type that we haven't called out already
6180 // that has an inner type is either (1) sugar or (2) contains that
6181 // inner type in some way as a subobject.
6182 if (TypeLoc Next = TL.getNextTypeLoc())
6183 return Visit(TL: Next, Sel);
6184
6185 // If there's no inner type and we're in a permissive context,
6186 // don't diagnose.
6187 if (Sel == Sema::AbstractNone) return;
6188
6189 // Check whether the type matches the abstract type.
6190 QualType T = TL.getType();
6191 if (T->isArrayType()) {
6192 Sel = Sema::AbstractArrayType;
6193 T = Info.S.Context.getBaseElementType(QT: T);
6194 }
6195 CanQualType CT = T->getCanonicalTypeUnqualified();
6196 if (CT != Info.AbstractType) return;
6197
6198 // It matched; do some magic.
6199 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6200 if (Sel == Sema::AbstractArrayType) {
6201 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6202 << T << TL.getSourceRange();
6203 } else {
6204 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6205 << Sel << T << TL.getSourceRange();
6206 }
6207 Info.DiagnoseAbstractType();
6208 }
6209};
6210
6211void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6212 Sema::AbstractDiagSelID Sel) {
6213 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6214}
6215
6216}
6217
6218/// Check for invalid uses of an abstract type in a function declaration.
6219static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6220 FunctionDecl *FD) {
6221 // Only definitions are required to refer to complete and
6222 // non-abstract types.
6223 if (!FD->doesThisDeclarationHaveABody())
6224 return;
6225
6226 // For safety's sake, just ignore it if we don't have type source
6227 // information. This should never happen for non-implicit methods,
6228 // but...
6229 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6230 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6231}
6232
6233/// Check for invalid uses of an abstract type in a variable0 declaration.
6234static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6235 VarDecl *VD) {
6236 // No need to do the check on definitions, which require that
6237 // the type is complete.
6238 if (VD->isThisDeclarationADefinition())
6239 return;
6240
6241 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6242 Sel: Sema::AbstractVariableType);
6243}
6244
6245/// Check for invalid uses of an abstract type within a class definition.
6246static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6247 CXXRecordDecl *RD) {
6248 for (auto *D : RD->decls()) {
6249 if (D->isImplicit()) continue;
6250
6251 // Step through friends to the befriended declaration.
6252 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6253 D = FD->getFriendDecl();
6254 if (!D) continue;
6255 }
6256
6257 // Functions and function templates.
6258 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6259 CheckAbstractClassUsage(Info, FD);
6260 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6261 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6262
6263 // Fields and static variables.
6264 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6265 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6266 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6267 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6268 CheckAbstractClassUsage(Info, VD);
6269 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6270 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6271
6272 // Nested classes and class templates.
6273 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6274 CheckAbstractClassUsage(Info, RD);
6275 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6276 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6277 }
6278 }
6279}
6280
6281static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6282 Attr *ClassAttr = getDLLAttr(D: Class);
6283 if (!ClassAttr)
6284 return;
6285
6286 assert(ClassAttr->getKind() == attr::DLLExport);
6287
6288 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6289
6290 if (TSK == TSK_ExplicitInstantiationDeclaration)
6291 // Don't go any further if this is just an explicit instantiation
6292 // declaration.
6293 return;
6294
6295 // Add a context note to explain how we got to any diagnostics produced below.
6296 struct MarkingClassDllexported {
6297 Sema &S;
6298 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6299 SourceLocation AttrLoc)
6300 : S(S) {
6301 Sema::CodeSynthesisContext Ctx;
6302 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6303 Ctx.PointOfInstantiation = AttrLoc;
6304 Ctx.Entity = Class;
6305 S.pushCodeSynthesisContext(Ctx);
6306 }
6307 ~MarkingClassDllexported() {
6308 S.popCodeSynthesisContext();
6309 }
6310 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6311
6312 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6313 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6314
6315 for (Decl *Member : Class->decls()) {
6316 // Skip members that were not marked exported.
6317 if (!Member->hasAttr<DLLExportAttr>())
6318 continue;
6319
6320 // Defined static variables that are members of an exported base
6321 // class must be marked export too.
6322 auto *VD = dyn_cast<VarDecl>(Val: Member);
6323 if (VD && VD->getStorageClass() == SC_Static &&
6324 TSK == TSK_ImplicitInstantiation)
6325 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6326
6327 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6328 if (!MD)
6329 continue;
6330
6331 if (MD->isUserProvided()) {
6332 // Instantiate non-default class member functions ...
6333
6334 // .. except for certain kinds of template specializations.
6335 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6336 continue;
6337
6338 // If this is an MS ABI dllexport default constructor, instantiate any
6339 // default arguments.
6340 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6341 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6342 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6343 S.BuildCtorClosureDefaultArgs(
6344 Loc: CD->getAttr<DLLExportAttr>()->getLocation(), Ctor: CD);
6345 }
6346 }
6347
6348 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6349
6350 // The function will be passed to the consumer when its definition is
6351 // encountered.
6352 } else if (MD->isExplicitlyDefaulted()) {
6353 // Synthesize and instantiate explicitly defaulted methods.
6354 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6355
6356 if (TSK != TSK_ExplicitInstantiationDefinition) {
6357 // Except for explicit instantiation defs, we will not see the
6358 // definition again later, so pass it to the consumer now.
6359 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6360 }
6361 } else if (!MD->isTrivial() ||
6362 MD->isCopyAssignmentOperator() ||
6363 MD->isMoveAssignmentOperator()) {
6364 // Synthesize and instantiate non-trivial implicit methods, and the copy
6365 // and move assignment operators. The latter are exported even if they
6366 // are trivial, because the address of an operator can be taken and
6367 // should compare equal across libraries.
6368 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6369
6370 // There is no later point when we will see the definition of this
6371 // function, so pass it to the consumer now.
6372 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6373 }
6374 }
6375}
6376
6377static void checkForMultipleExportedDefaultConstructors(Sema &S,
6378 CXXRecordDecl *Class) {
6379 // Only the MS ABI has default constructor closures, so we don't need to do
6380 // this semantic checking anywhere else.
6381 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6382 return;
6383
6384 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6385 for (Decl *Member : Class->decls()) {
6386 // Look for exported default constructors.
6387 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6388 if (!CD || !CD->isDefaultConstructor())
6389 continue;
6390 auto *Attr = CD->getAttr<DLLExportAttr>();
6391 if (!Attr)
6392 continue;
6393
6394 // If the class is non-dependent, mark the default arguments as ODR-used so
6395 // that we can properly codegen the constructor closure.
6396 if (!Class->isDependentContext()) {
6397 S.BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor: CD);
6398 S.DiscardCleanupsInEvaluationContext();
6399 }
6400
6401 if (LastExportedDefaultCtor) {
6402 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6403 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6404 << Class;
6405 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6406 << CD->getDeclName();
6407 return;
6408 }
6409 LastExportedDefaultCtor = CD;
6410 }
6411}
6412
6413static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6414 CXXRecordDecl *Class) {
6415 bool ErrorReported = false;
6416 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6417 ClassTemplateDecl *TD) {
6418 if (ErrorReported)
6419 return;
6420 S.Diag(Loc: TD->getLocation(),
6421 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6422 << /*surface*/ 0 << TD;
6423 ErrorReported = true;
6424 };
6425
6426 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6427 if (!TD) {
6428 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6429 if (!SD) {
6430 S.Diag(Loc: Class->getLocation(),
6431 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6432 << /*surface*/ 0 << Class;
6433 S.Diag(Loc: Class->getLocation(),
6434 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6435 << Class;
6436 return;
6437 }
6438 TD = SD->getSpecializedTemplate();
6439 }
6440
6441 TemplateParameterList *Params = TD->getTemplateParameters();
6442 unsigned N = Params->size();
6443
6444 if (N != 2) {
6445 reportIllegalClassTemplate(S, TD);
6446 S.Diag(Loc: TD->getLocation(),
6447 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6448 << TD << 2;
6449 }
6450 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6451 reportIllegalClassTemplate(S, TD);
6452 S.Diag(Loc: TD->getLocation(),
6453 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6454 << TD << /*1st*/ 0 << /*type*/ 0;
6455 }
6456 if (N > 1) {
6457 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6458 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6459 reportIllegalClassTemplate(S, TD);
6460 S.Diag(Loc: TD->getLocation(),
6461 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6462 << TD << /*2nd*/ 1 << /*integer*/ 1;
6463 }
6464 }
6465}
6466
6467static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6468 CXXRecordDecl *Class) {
6469 bool ErrorReported = false;
6470 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6471 ClassTemplateDecl *TD) {
6472 if (ErrorReported)
6473 return;
6474 S.Diag(Loc: TD->getLocation(),
6475 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6476 << /*texture*/ 1 << TD;
6477 ErrorReported = true;
6478 };
6479
6480 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6481 if (!TD) {
6482 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6483 if (!SD) {
6484 S.Diag(Loc: Class->getLocation(),
6485 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6486 << /*texture*/ 1 << Class;
6487 S.Diag(Loc: Class->getLocation(),
6488 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6489 << Class;
6490 return;
6491 }
6492 TD = SD->getSpecializedTemplate();
6493 }
6494
6495 TemplateParameterList *Params = TD->getTemplateParameters();
6496 unsigned N = Params->size();
6497
6498 if (N != 3) {
6499 reportIllegalClassTemplate(S, TD);
6500 S.Diag(Loc: TD->getLocation(),
6501 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6502 << TD << 3;
6503 }
6504 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6505 reportIllegalClassTemplate(S, TD);
6506 S.Diag(Loc: TD->getLocation(),
6507 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6508 << TD << /*1st*/ 0 << /*type*/ 0;
6509 }
6510 if (N > 1) {
6511 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6512 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6513 reportIllegalClassTemplate(S, TD);
6514 S.Diag(Loc: TD->getLocation(),
6515 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6516 << TD << /*2nd*/ 1 << /*integer*/ 1;
6517 }
6518 }
6519 if (N > 2) {
6520 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6521 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6522 reportIllegalClassTemplate(S, TD);
6523 S.Diag(Loc: TD->getLocation(),
6524 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6525 << TD << /*3rd*/ 2 << /*integer*/ 1;
6526 }
6527 }
6528}
6529
6530void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6531 // Mark any compiler-generated routines with the implicit code_seg attribute.
6532 for (auto *Method : Class->methods()) {
6533 if (Method->isUserProvided())
6534 continue;
6535 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6536 Method->addAttr(A);
6537 }
6538}
6539
6540void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6541 Attr *ClassAttr = getDLLAttr(D: Class);
6542
6543 // MSVC inherits DLL attributes to partial class template specializations.
6544 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6545 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6546 if (Attr *TemplateAttr =
6547 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6548 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6549 A->setInherited(true);
6550 ClassAttr = A;
6551 }
6552 }
6553 }
6554
6555 if (!ClassAttr)
6556 return;
6557
6558 // MSVC allows imported or exported template classes that have UniqueExternal
6559 // linkage. This occurs when the template class has been instantiated with
6560 // a template parameter which itself has internal linkage.
6561 // We drop the attribute to avoid exporting or importing any members.
6562 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6563 Context.getTargetInfo().getTriple().isPS()) &&
6564 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6565 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6566 return;
6567 }
6568
6569 if (!Class->isExternallyVisible()) {
6570 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6571 << Class << ClassAttr;
6572 return;
6573 }
6574
6575 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6576 !ClassAttr->isInherited()) {
6577 // Diagnose dll attributes on members of class with dll attribute.
6578 for (Decl *Member : Class->decls()) {
6579 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6580 continue;
6581 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6582 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6583 continue;
6584
6585 Diag(Loc: MemberAttr->getLocation(),
6586 DiagID: diag::err_attribute_dll_member_of_dll_class)
6587 << MemberAttr << ClassAttr;
6588 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6589 Member->setInvalidDecl();
6590 }
6591 }
6592
6593 if (Class->getDescribedClassTemplate())
6594 // Don't inherit dll attribute until the template is instantiated.
6595 return;
6596
6597 // The class is either imported or exported.
6598 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6599
6600 // Check if this was a dllimport attribute propagated from a derived class to
6601 // a base class template specialization. We don't apply these attributes to
6602 // static data members.
6603 const bool PropagatedImport =
6604 !ClassExported &&
6605 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6606
6607 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6608
6609 // Ignore explicit dllexport on explicit class template instantiation
6610 // declarations, except in MinGW mode.
6611 if (ClassExported && !ClassAttr->isInherited() &&
6612 TSK == TSK_ExplicitInstantiationDeclaration &&
6613 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6614 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6615 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6616 Class->dropAttr<DLLExportAttr>();
6617 }
6618 return;
6619 }
6620
6621 // Force declaration of implicit members so they can inherit the attribute.
6622 ForceDeclarationOfImplicitMembers(Class);
6623
6624 // Inherited constructors are created lazily; force their creation now so the
6625 // loop below can propagate the DLL attribute to them.
6626 if (ClassExported && getLangOpts().DllExportInlines) {
6627 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6628 for (Decl *D : Class->decls())
6629 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6630 Shadows.push_back(Elt: S);
6631 for (ConstructorUsingShadowDecl *S : Shadows) {
6632 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6633 if (!BC || BC->isDeleted())
6634 continue;
6635 // Skip constructors whose requires clause is not satisfied.
6636 // Normally overload resolution filters these, but we are bypassing
6637 // it to eagerly create inherited constructors for dllexport.
6638 if (BC->getTrailingRequiresClause()) {
6639 ConstraintSatisfaction Satisfaction;
6640 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6641 !Satisfaction.IsSatisfied)
6642 continue;
6643 }
6644 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6645 }
6646 }
6647
6648 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6649 // seem to be true in practice?
6650
6651 for (Decl *Member : Class->decls()) {
6652 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6653 continue;
6654
6655 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6656 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6657
6658 // Only methods and static fields inherit the attributes.
6659 if (!VD && !MD)
6660 continue;
6661
6662 if (MD) {
6663 // Don't process deleted methods.
6664 if (MD->isDeleted())
6665 continue;
6666
6667 if (ClassExported && getLangOpts().DllExportInlines) {
6668 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6669 if (CD && CD->getInheritedConstructor()) {
6670 // Inherited constructors already had their base constructor's
6671 // constraints checked before creation via
6672 // findInheritingConstructor, so only ABI-compatibility checks
6673 // are needed here.
6674 //
6675 // Don't export inherited constructors whose parameters prevent
6676 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6677 // CodeGen) returns false, Clang inlines the constructor body
6678 // instead of emitting a forwarding thunk, producing code that
6679 // is not ABI-compatible with MSVC. Suppress the export and warn
6680 // so the user gets a linker error rather than a silent runtime
6681 // mismatch.
6682 if (CD->isVariadic()) {
6683 Diag(Loc: CD->getLocation(),
6684 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6685 << /*variadic=*/0;
6686 continue;
6687 }
6688 if (Context.getTargetInfo()
6689 .getCXXABI()
6690 .areArgsDestroyedLeftToRightInCallee()) {
6691 bool HasCalleeCleanupParam = false;
6692 for (const ParmVarDecl *P : CD->parameters())
6693 if (P->needsDestruction(Ctx: Context)) {
6694 HasCalleeCleanupParam = true;
6695 break;
6696 }
6697 if (HasCalleeCleanupParam) {
6698 Diag(Loc: CD->getLocation(),
6699 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6700 << /*callee-cleanup=*/1;
6701 continue;
6702 }
6703 }
6704 } else if (MD->getTrailingRequiresClause()) {
6705 // Don't export methods whose requires clause is not satisfied.
6706 // For class template specializations, member constraints may
6707 // depend on template arguments and an unsatisfied constraint
6708 // means the member should not be available in this
6709 // specialization.
6710 ConstraintSatisfaction Satisfaction;
6711 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6712 !Satisfaction.IsSatisfied)
6713 continue;
6714 }
6715 }
6716
6717 if (MD->isInlined()) {
6718 // MinGW does not import or export inline methods. But do it for
6719 // template instantiations and inherited constructors (which are
6720 // marked inline but must be exported to match MSVC behavior).
6721 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6722 TSK != TSK_ExplicitInstantiationDeclaration &&
6723 TSK != TSK_ExplicitInstantiationDefinition) {
6724 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6725 !CD || !CD->getInheritedConstructor())
6726 continue;
6727 }
6728
6729 // MSVC versions before 2015 don't export the move assignment operators
6730 // and move constructor, so don't attempt to import/export them if
6731 // we have a definition.
6732 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6733 if ((MD->isMoveAssignmentOperator() ||
6734 (Ctor && Ctor->isMoveConstructor())) &&
6735 getLangOpts().isCompatibleWithMSVC() &&
6736 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6737 continue;
6738
6739 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6740 // operator is exported anyway.
6741 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6742 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6743 continue;
6744 }
6745 }
6746
6747 // Don't apply dllimport attributes to static data members of class template
6748 // instantiations when the attribute is propagated from a derived class.
6749 if (VD && PropagatedImport)
6750 continue;
6751
6752 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6753 continue;
6754
6755 if (!getDLLAttr(D: Member)) {
6756 InheritableAttr *NewAttr = nullptr;
6757
6758 // Do not export/import inline function when -fno-dllexport-inlines is
6759 // passed. But add attribute for later local static var check.
6760 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6761 TSK != TSK_ExplicitInstantiationDeclaration &&
6762 TSK != TSK_ExplicitInstantiationDefinition) {
6763 if (ClassExported) {
6764 NewAttr = ::new (getASTContext())
6765 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6766 } else {
6767 NewAttr = ::new (getASTContext())
6768 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6769 }
6770 } else {
6771 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6772 }
6773
6774 NewAttr->setInherited(true);
6775 Member->addAttr(A: NewAttr);
6776
6777 if (MD) {
6778 // Propagate DLLAttr to friend re-declarations of MD that have already
6779 // been constructed.
6780 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6781 FD = FD->getPreviousDecl()) {
6782 if (FD->getFriendObjectKind() == Decl::FOK_None)
6783 continue;
6784 assert(!getDLLAttr(FD) &&
6785 "friend re-decl should not already have a DLLAttr");
6786 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6787 NewAttr->setInherited(true);
6788 FD->addAttr(A: NewAttr);
6789 }
6790 }
6791 }
6792 }
6793
6794 if (ClassExported)
6795 DelayedDllExportClasses.push_back(Elt: Class);
6796}
6797
6798void Sema::propagateDLLAttrToBaseClassTemplate(
6799 CXXRecordDecl *Class, Attr *ClassAttr,
6800 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6801 if (getDLLAttr(
6802 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6803 // If the base class template has a DLL attribute, don't try to change it.
6804 return;
6805 }
6806
6807 auto TSK = BaseTemplateSpec->getSpecializationKind();
6808 if (!getDLLAttr(D: BaseTemplateSpec) &&
6809 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6810 TSK == TSK_ImplicitInstantiation)) {
6811 // The template hasn't been instantiated yet (or it has, but only as an
6812 // explicit instantiation declaration or implicit instantiation, which means
6813 // we haven't codegenned any members yet), so propagate the attribute.
6814 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6815 NewAttr->setInherited(true);
6816 BaseTemplateSpec->addAttr(A: NewAttr);
6817
6818 // If this was an import, mark that we propagated it from a derived class to
6819 // a base class template specialization.
6820 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6821 ImportAttr->setPropagatedToBaseTemplate();
6822
6823 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6824 // needs to be run again to work see the new attribute. Otherwise this will
6825 // get run whenever the template is instantiated.
6826 if (TSK != TSK_Undeclared)
6827 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6828
6829 return;
6830 }
6831
6832 if (getDLLAttr(D: BaseTemplateSpec)) {
6833 // The template has already been specialized or instantiated with an
6834 // attribute, explicitly or through propagation. We should not try to change
6835 // it.
6836 return;
6837 }
6838
6839 // The template was previously instantiated or explicitly specialized without
6840 // a dll attribute, It's too late for us to add an attribute, so warn that
6841 // this is unsupported.
6842 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6843 << BaseTemplateSpec->isExplicitSpecialization();
6844 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6845 if (BaseTemplateSpec->isExplicitSpecialization()) {
6846 Diag(Loc: BaseTemplateSpec->getLocation(),
6847 DiagID: diag::note_template_class_explicit_specialization_was_here)
6848 << BaseTemplateSpec;
6849 } else {
6850 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6851 DiagID: diag::note_template_class_instantiation_was_here)
6852 << BaseTemplateSpec;
6853 }
6854}
6855
6856Sema::DefaultedFunctionKind
6857Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6858 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6859 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6860 if (Ctor->isDefaultConstructor())
6861 return CXXSpecialMemberKind::DefaultConstructor;
6862
6863 if (Ctor->isCopyConstructor())
6864 return CXXSpecialMemberKind::CopyConstructor;
6865
6866 if (Ctor->isMoveConstructor())
6867 return CXXSpecialMemberKind::MoveConstructor;
6868 }
6869
6870 if (MD->isCopyAssignmentOperator())
6871 return CXXSpecialMemberKind::CopyAssignment;
6872
6873 if (MD->isMoveAssignmentOperator())
6874 return CXXSpecialMemberKind::MoveAssignment;
6875
6876 if (isa<CXXDestructorDecl>(Val: FD))
6877 return CXXSpecialMemberKind::Destructor;
6878 }
6879
6880 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6881 case OO_EqualEqual:
6882 return DefaultedComparisonKind::Equal;
6883
6884 case OO_ExclaimEqual:
6885 return DefaultedComparisonKind::NotEqual;
6886
6887 case OO_Spaceship:
6888 // No point allowing this if <=> doesn't exist in the current language mode.
6889 if (!getLangOpts().CPlusPlus20)
6890 break;
6891 return DefaultedComparisonKind::ThreeWay;
6892
6893 case OO_Less:
6894 case OO_LessEqual:
6895 case OO_Greater:
6896 case OO_GreaterEqual:
6897 // No point allowing this if <=> doesn't exist in the current language mode.
6898 if (!getLangOpts().CPlusPlus20)
6899 break;
6900 return DefaultedComparisonKind::Relational;
6901
6902 default:
6903 break;
6904 }
6905
6906 // Not defaultable.
6907 return DefaultedFunctionKind();
6908}
6909
6910namespace {
6911/// RAII object to restore the floating-point (FP) features active at the time
6912/// a defaulted function was declared. This ensures that the synthesized body
6913/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6914/// that were in effect when the function was explicitly defaulted.
6915struct DefaultedFunctionFPFeaturesRAII {
6916 Sema::FPFeaturesStateRAII SavedFPFeatures;
6917 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6918 : SavedFPFeatures(S) {
6919 auto *Info = FD->getDefaultedOrDeletedInfo();
6920 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6921 S.CurFPFeatures = FPO.applyOverrides(LO: S.LangOpts);
6922 S.FpPragmaStack.CurrentValue = FPO;
6923 }
6924
6925 ~DefaultedFunctionFPFeaturesRAII() = default;
6926};
6927} // namespace
6928
6929static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6930 SourceLocation DefaultLoc) {
6931 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6932 if (DFK.isComparison())
6933 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6934
6935 switch (DFK.asSpecialMember()) {
6936 case CXXSpecialMemberKind::DefaultConstructor:
6937 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6938 Constructor: cast<CXXConstructorDecl>(Val: FD));
6939 break;
6940 case CXXSpecialMemberKind::CopyConstructor:
6941 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6942 break;
6943 case CXXSpecialMemberKind::CopyAssignment:
6944 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6945 break;
6946 case CXXSpecialMemberKind::Destructor:
6947 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6948 break;
6949 case CXXSpecialMemberKind::MoveConstructor:
6950 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6951 break;
6952 case CXXSpecialMemberKind::MoveAssignment:
6953 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6954 break;
6955 case CXXSpecialMemberKind::Invalid:
6956 llvm_unreachable("Invalid special member.");
6957 }
6958}
6959
6960/// Determine whether a type is permitted to be passed or returned in
6961/// registers, per C++ [class.temporary]p3.
6962static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6963 TargetInfo::CallingConvKind CCK) {
6964 if (D->isDependentType() || D->isInvalidDecl())
6965 return false;
6966
6967 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6968 // The PS4 platform ABI follows the behavior of Clang 3.2.
6969 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6970 return !D->hasNonTrivialDestructorForCall() &&
6971 !D->hasNonTrivialCopyConstructorForCall();
6972
6973 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6974 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6975 bool DtorIsTrivialForCall = false;
6976
6977 // If a class has at least one eligible, trivial copy constructor, it
6978 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6979 //
6980 // Note: This permits classes with non-trivial copy or move ctors to be
6981 // passed in registers, so long as they *also* have a trivial copy ctor,
6982 // which is non-conforming.
6983 if (D->needsImplicitCopyConstructor()) {
6984 if (!D->defaultedCopyConstructorIsDeleted()) {
6985 if (D->hasTrivialCopyConstructor())
6986 CopyCtorIsTrivial = true;
6987 if (D->hasTrivialCopyConstructorForCall())
6988 CopyCtorIsTrivialForCall = true;
6989 }
6990 } else {
6991 for (const CXXConstructorDecl *CD : D->ctors()) {
6992 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6993 !CD->isIneligibleOrNotSelected()) {
6994 if (CD->isTrivial())
6995 CopyCtorIsTrivial = true;
6996 if (CD->isTrivialForCall())
6997 CopyCtorIsTrivialForCall = true;
6998 }
6999 }
7000 }
7001
7002 if (D->needsImplicitDestructor()) {
7003 if (!D->defaultedDestructorIsDeleted() &&
7004 D->hasTrivialDestructorForCall())
7005 DtorIsTrivialForCall = true;
7006 } else if (const auto *DD = D->getDestructor()) {
7007 if (!DD->isDeleted() && DD->isTrivialForCall())
7008 DtorIsTrivialForCall = true;
7009 }
7010
7011 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7012 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7013 return true;
7014
7015 // If a class has a destructor, we'd really like to pass it indirectly
7016 // because it allows us to elide copies. Unfortunately, MSVC makes that
7017 // impossible for small types, which it will pass in a single register or
7018 // stack slot. Most objects with dtors are large-ish, so handle that early.
7019 // We can't call out all large objects as being indirect because there are
7020 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7021 // how we pass large POD types.
7022
7023 // Note: This permits small classes with nontrivial destructors to be
7024 // passed in registers, which is non-conforming.
7025 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7026 uint64_t TypeSize = isAArch64 ? 128 : 64;
7027
7028 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7029 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
7030 return true;
7031 return false;
7032 }
7033
7034 // Per C++ [class.temporary]p3, the relevant condition is:
7035 // each copy constructor, move constructor, and destructor of X is
7036 // either trivial or deleted, and X has at least one non-deleted copy
7037 // or move constructor
7038 bool HasNonDeletedCopyOrMove = false;
7039
7040 if (D->needsImplicitCopyConstructor() &&
7041 !D->defaultedCopyConstructorIsDeleted()) {
7042 if (!D->hasTrivialCopyConstructorForCall())
7043 return false;
7044 HasNonDeletedCopyOrMove = true;
7045 }
7046
7047 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7048 !D->defaultedMoveConstructorIsDeleted()) {
7049 if (!D->hasTrivialMoveConstructorForCall())
7050 return false;
7051 HasNonDeletedCopyOrMove = true;
7052 }
7053
7054 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7055 !D->hasTrivialDestructorForCall())
7056 return false;
7057
7058 for (const CXXMethodDecl *MD : D->methods()) {
7059 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7060 continue;
7061
7062 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7063 if (CD && CD->isCopyOrMoveConstructor())
7064 HasNonDeletedCopyOrMove = true;
7065 else if (!isa<CXXDestructorDecl>(Val: MD))
7066 continue;
7067
7068 if (!MD->isTrivialForCall())
7069 return false;
7070 }
7071
7072 return HasNonDeletedCopyOrMove;
7073}
7074
7075/// Report an error regarding overriding, along with any relevant
7076/// overridden methods.
7077///
7078/// \param DiagID the primary error to report.
7079/// \param MD the overriding method.
7080static bool
7081ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7082 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7083 bool IssuedDiagnostic = false;
7084 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7085 if (Report(O)) {
7086 if (!IssuedDiagnostic) {
7087 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7088 IssuedDiagnostic = true;
7089 }
7090 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7091 }
7092 }
7093 return IssuedDiagnostic;
7094}
7095
7096void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7097 if (!Record)
7098 return;
7099
7100 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7101 AbstractUsageInfo Info(*this, Record);
7102 CheckAbstractClassUsage(Info, RD: Record);
7103 }
7104
7105 // If this is not an aggregate type and has no user-declared constructor,
7106 // complain about any non-static data members of reference or const scalar
7107 // type, since they will never get initializers.
7108 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7109 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7110 !Record->isLambda()) {
7111 bool Complained = false;
7112 for (const auto *F : Record->fields()) {
7113 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7114 continue;
7115
7116 if (F->getType()->isReferenceType() ||
7117 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7118 if (!Complained) {
7119 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7120 << Record->getTagKind() << Record;
7121 Complained = true;
7122 }
7123
7124 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7125 << F->getType()->isReferenceType()
7126 << F->getDeclName();
7127 }
7128 }
7129 }
7130
7131 if (Record->getIdentifier()) {
7132 // C++ [class.mem]p13:
7133 // If T is the name of a class, then each of the following shall have a
7134 // name different from T:
7135 // - every member of every anonymous union that is a member of class T.
7136 //
7137 // C++ [class.mem]p14:
7138 // In addition, if class T has a user-declared constructor (12.1), every
7139 // non-static data member of class T shall have a name different from T.
7140 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7141 const NamedDecl *D = Element->getUnderlyingDecl();
7142 // Invalid IndirectFieldDecls have already been diagnosed with
7143 // err_anonymous_record_member_redecl in
7144 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7145 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7146 Record->hasUserDeclaredConstructor()) ||
7147 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7148 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7149 << D->getDeclName();
7150 break;
7151 }
7152 }
7153 }
7154
7155 // Warn if the class has virtual methods but non-virtual public destructor.
7156 if (Record->isPolymorphic() && !Record->isDependentType()) {
7157 CXXDestructorDecl *dtor = Record->getDestructor();
7158 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7159 !Record->hasAttr<FinalAttr>())
7160 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7161 DiagID: diag::warn_non_virtual_dtor)
7162 << Context.getCanonicalTagType(TD: Record);
7163 }
7164
7165 if (Record->isAbstract()) {
7166 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7167 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7168 << FA->isSpelledAsSealed();
7169 DiagnoseAbstractType(RD: Record);
7170 }
7171 }
7172
7173 // Warn if the class has a final destructor but is not itself marked final.
7174 if (!Record->hasAttr<FinalAttr>()) {
7175 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7176 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7177 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7178 << FA->isSpelledAsSealed()
7179 << FixItHint::CreateInsertion(
7180 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7181 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7182 Diag(Loc: Record->getLocation(),
7183 DiagID: diag::note_final_dtor_non_final_class_silence)
7184 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7185 }
7186 }
7187 }
7188
7189 // See if trivial_abi has to be dropped.
7190 if (Record->hasAttr<TrivialABIAttr>())
7191 checkIllFormedTrivialABIStruct(RD&: *Record);
7192
7193 // Set HasTrivialSpecialMemberForCall if the record has attribute
7194 // "trivial_abi".
7195 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7196
7197 if (HasTrivialABI)
7198 Record->setHasTrivialSpecialMemberForCall();
7199
7200 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7201 // We check these last because they can depend on the properties of the
7202 // primary comparison functions (==, <=>).
7203 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7204
7205 // Perform checks that can't be done until we know all the properties of a
7206 // member function (whether it's defaulted, deleted, virtual, overriding,
7207 // ...).
7208 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7209 // A static function cannot override anything.
7210 if (MD->getStorageClass() == SC_Static) {
7211 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7212 Report: [](const CXXMethodDecl *) { return true; }))
7213 return;
7214 }
7215
7216 // A deleted function cannot override a non-deleted function and vice
7217 // versa.
7218 if (ReportOverrides(S&: *this,
7219 DiagID: MD->isDeleted() ? diag::err_deleted_override
7220 : diag::err_non_deleted_override,
7221 MD, Report: [&](const CXXMethodDecl *V) {
7222 return MD->isDeleted() != V->isDeleted();
7223 })) {
7224 if (MD->isDefaulted() && MD->isDeleted())
7225 // Explain why this defaulted function was deleted.
7226 DiagnoseDeletedDefaultedFunction(FD: MD);
7227 return;
7228 }
7229
7230 // A consteval function cannot override a non-consteval function and vice
7231 // versa.
7232 if (ReportOverrides(S&: *this,
7233 DiagID: MD->isConsteval() ? diag::err_consteval_override
7234 : diag::err_non_consteval_override,
7235 MD, Report: [&](const CXXMethodDecl *V) {
7236 return MD->isConsteval() != V->isConsteval();
7237 })) {
7238 if (MD->isDefaulted() && MD->isDeleted())
7239 // Explain why this defaulted function was deleted.
7240 DiagnoseDeletedDefaultedFunction(FD: MD);
7241 return;
7242 }
7243 };
7244
7245 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7246 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7247 return false;
7248
7249 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7250 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7251 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7252 DefaultedSecondaryComparisons.push_back(Elt: FD);
7253 return true;
7254 }
7255
7256 CheckExplicitlyDefaultedFunction(S, MD: FD);
7257 return false;
7258 };
7259
7260 if (!Record->isInvalidDecl() &&
7261 Record->hasAttr<VTablePointerAuthenticationAttr>())
7262 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7263
7264 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7265 // Check whether the explicitly-defaulted members are valid.
7266 bool Incomplete = CheckForDefaultedFunction(M);
7267
7268 // Skip the rest of the checks for a member of a dependent class.
7269 if (Record->isDependentType())
7270 return;
7271
7272 // For an explicitly defaulted or deleted special member, we defer
7273 // determining triviality until the class is complete. That time is now!
7274 CXXSpecialMemberKind CSM = getSpecialMember(MD: M);
7275 if (!M->isImplicit() && !M->isUserProvided()) {
7276 if (CSM != CXXSpecialMemberKind::Invalid) {
7277 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7278 // Inform the class that we've finished declaring this member.
7279 Record->finishedDefaultedOrDeletedMember(MD: M);
7280 M->setTrivialForCall(
7281 HasTrivialABI ||
7282 SpecialMemberIsTrivial(MD: M, CSM,
7283 TAH: TrivialABIHandling::ConsiderTrivialABI));
7284 Record->setTrivialForCallFlags(M);
7285 }
7286 }
7287
7288 // Set triviality for the purpose of calls if this is a user-provided
7289 // copy/move constructor or destructor.
7290 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7291 CSM == CXXSpecialMemberKind::MoveConstructor ||
7292 CSM == CXXSpecialMemberKind::Destructor) &&
7293 M->isUserProvided()) {
7294 M->setTrivialForCall(HasTrivialABI);
7295 Record->setTrivialForCallFlags(M);
7296 }
7297
7298 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7299 M->hasAttr<DLLExportAttr>()) {
7300 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7301 M->isTrivial() &&
7302 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7303 CSM == CXXSpecialMemberKind::CopyConstructor ||
7304 CSM == CXXSpecialMemberKind::Destructor))
7305 M->dropAttr<DLLExportAttr>();
7306
7307 if (M->hasAttr<DLLExportAttr>()) {
7308 // Define after any fields with in-class initializers have been parsed.
7309 DelayedDllExportMemberFunctions.push_back(Elt: M);
7310 }
7311 }
7312
7313 bool EffectivelyConstexprDestructor = true;
7314 // Avoid triggering vtable instantiation due to a dtor that is not
7315 // "effectively constexpr" for better compatibility.
7316 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7317 if (isa<CXXDestructorDecl>(Val: M)) {
7318 llvm::SmallDenseSet<QualType> Visited;
7319 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7320 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7321 return false;
7322 const CXXRecordDecl *RD =
7323 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7324 if (!RD || !RD->isCompleteDefinition())
7325 return true;
7326
7327 if (!RD->hasConstexprDestructor())
7328 return false;
7329
7330 for (const CXXBaseSpecifier &B : RD->bases())
7331 if (!Check(B.getType(), Check))
7332 return false;
7333 for (const FieldDecl *FD : RD->fields())
7334 if (!Check(FD->getType(), Check))
7335 return false;
7336 return true;
7337 };
7338 EffectivelyConstexprDestructor =
7339 Check(Context.getCanonicalTagType(TD: Record), Check);
7340 }
7341
7342 // Define defaulted constexpr virtual functions that override a base class
7343 // function right away.
7344 // FIXME: We can defer doing this until the vtable is marked as used.
7345 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7346 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7347 EffectivelyConstexprDestructor)
7348 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7349
7350 if (!Incomplete)
7351 CheckCompletedMemberFunction(M);
7352 };
7353
7354 // Check the destructor before any other member function. We need to
7355 // determine whether it's trivial in order to determine whether the claas
7356 // type is a literal type, which is a prerequisite for determining whether
7357 // other special member functions are valid and whether they're implicitly
7358 // 'constexpr'.
7359 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7360 CompleteMemberFunction(Dtor);
7361
7362 bool HasMethodWithOverrideControl = false,
7363 HasOverridingMethodWithoutOverrideControl = false;
7364 for (auto *D : Record->decls()) {
7365 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7366 // FIXME: We could do this check for dependent types with non-dependent
7367 // bases.
7368 if (!Record->isDependentType()) {
7369 // See if a method overloads virtual methods in a base
7370 // class without overriding any.
7371 if (!M->isStatic())
7372 DiagnoseHiddenVirtualMethods(MD: M);
7373
7374 if (M->hasAttr<OverrideAttr>()) {
7375 HasMethodWithOverrideControl = true;
7376 } else if (M->size_overridden_methods() > 0) {
7377 HasOverridingMethodWithoutOverrideControl = true;
7378 } else {
7379 // Warn on newly-declared virtual methods in `final` classes
7380 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7381 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7382 << M;
7383 }
7384 }
7385 }
7386
7387 if (!isa<CXXDestructorDecl>(Val: M))
7388 CompleteMemberFunction(M);
7389 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7390 CheckForDefaultedFunction(
7391 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7392 }
7393 }
7394
7395 if (HasOverridingMethodWithoutOverrideControl) {
7396 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7397 for (auto *M : Record->methods())
7398 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7399 }
7400
7401 // Check the defaulted secondary comparisons after any other member functions.
7402 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7403 CheckExplicitlyDefaultedFunction(S, MD: FD);
7404
7405 // If this is a member function, we deferred checking it until now.
7406 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7407 CheckCompletedMemberFunction(MD);
7408 }
7409
7410 // {ms,gcc}_struct is a request to change ABI rules to either follow
7411 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7412 // present, we do not layout classes following foreign ABI rules, but
7413 // instead enter a special "compatibility mode", which only changes
7414 // alignments of fundamental types and layout of bit fields.
7415 // Check whether this class uses any C++ features that are implemented
7416 // completely differently in the requested ABI, and if so, emit a
7417 // diagnostic. That diagnostic defaults to an error, but we allow
7418 // projects to map it down to a warning (or ignore it). It's a fairly
7419 // common practice among users of the ms_struct pragma to
7420 // mass-annotate headers, sweeping up a bunch of types that the
7421 // project doesn't really rely on MSVC-compatible layout for. We must
7422 // therefore support "ms_struct except for C++ stuff" as a secondary
7423 // ABI.
7424 // Don't emit this diagnostic if the feature was enabled as a
7425 // language option (as opposed to via a pragma or attribute), as
7426 // the option -mms-bitfields otherwise essentially makes it impossible
7427 // to build C++ code, unless this diagnostic is turned off.
7428 if (Context.getLangOpts().getLayoutCompatibility() ==
7429 LangOptions::LayoutCompatibilityKind::Default &&
7430 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7431 (Record->isPolymorphic() || Record->getNumBases())) {
7432 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7433 }
7434
7435 checkClassLevelDLLAttribute(Class: Record);
7436 checkClassLevelCodeSegAttribute(Class: Record);
7437
7438 bool ClangABICompat4 =
7439 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver4);
7440 TargetInfo::CallingConvKind CCK =
7441 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7442 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7443
7444 // Do not change ArgPassingRestrictions if it has already been set to
7445 // RecordArgPassingKind::CanNeverPassInRegs.
7446 if (Record->getArgPassingRestrictions() !=
7447 RecordArgPassingKind::CanNeverPassInRegs)
7448 Record->setArgPassingRestrictions(
7449 CanPass ? RecordArgPassingKind::CanPassInRegs
7450 : RecordArgPassingKind::CannotPassInRegs);
7451
7452 // If canPassInRegisters returns true despite the record having a non-trivial
7453 // destructor, the record is destructed in the callee. This happens only when
7454 // the record or one of its subobjects has a field annotated with trivial_abi
7455 // or a field qualified with ObjC __strong/__weak.
7456 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7457 Record->setParamDestroyedInCallee(true);
7458 else if (Record->hasNonTrivialDestructor())
7459 Record->setParamDestroyedInCallee(CanPass);
7460
7461 if (getLangOpts().ForceEmitVTables) {
7462 // If we want to emit all the vtables, we need to mark it as used. This
7463 // is especially required for cases like vtable assumption loads.
7464 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7465 }
7466
7467 if (getLangOpts().CUDA) {
7468 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7469 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7470 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7471 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7472 }
7473
7474 llvm::SmallDenseMap<OverloadedOperatorKind,
7475 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7476 TypeAwareDecls{{OO_New, {}},
7477 {OO_Array_New, {}},
7478 {OO_Delete, {}},
7479 {OO_Array_New, {}}};
7480 for (auto *D : Record->decls()) {
7481 const FunctionDecl *FnDecl = D->getAsFunction();
7482 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7483 continue;
7484 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7485 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7486 }
7487 auto CheckMismatchedTypeAwareAllocators =
7488 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7489 OverloadedOperatorKind DeleteKind) {
7490 auto &NewDecls = TypeAwareDecls[NewKind];
7491 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7492 if (NewDecls.empty() == DeleteDecls.empty())
7493 return;
7494 DeclarationName FoundOperator =
7495 Context.DeclarationNames.getCXXOperatorName(
7496 Op: NewDecls.empty() ? DeleteKind : NewKind);
7497 DeclarationName MissingOperator =
7498 Context.DeclarationNames.getCXXOperatorName(
7499 Op: NewDecls.empty() ? NewKind : DeleteKind);
7500 Diag(Loc: Record->getLocation(),
7501 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7502 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7503 << MissingOperator;
7504 for (auto MD : NewDecls)
7505 Diag(Loc: MD->getLocation(),
7506 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7507 << MD;
7508 for (auto MD : DeleteDecls)
7509 Diag(Loc: MD->getLocation(),
7510 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7511 << MD;
7512 };
7513 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7514 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7515}
7516
7517/// Look up the special member function that would be called by a special
7518/// member function for a subobject of class type.
7519///
7520/// \param Class The class type of the subobject.
7521/// \param CSM The kind of special member function.
7522/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7523/// \param ConstRHS True if this is a copy operation with a const object
7524/// on its RHS, that is, if the argument to the outer special member
7525/// function is 'const' and this is not a field marked 'mutable'.
7526static Sema::SpecialMemberOverloadResult
7527lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7528 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7529 bool ConstRHS) {
7530 unsigned LHSQuals = 0;
7531 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7532 CSM == CXXSpecialMemberKind::MoveAssignment)
7533 LHSQuals = FieldQuals;
7534
7535 unsigned RHSQuals = FieldQuals;
7536 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7537 CSM == CXXSpecialMemberKind::Destructor)
7538 RHSQuals = 0;
7539 else if (ConstRHS)
7540 RHSQuals |= Qualifiers::Const;
7541
7542 return S.LookupSpecialMember(D: Class, SM: CSM,
7543 ConstArg: RHSQuals & Qualifiers::Const,
7544 VolatileArg: RHSQuals & Qualifiers::Volatile,
7545 RValueThis: false,
7546 ConstThis: LHSQuals & Qualifiers::Const,
7547 VolatileThis: LHSQuals & Qualifiers::Volatile);
7548}
7549
7550class Sema::InheritedConstructorInfo {
7551 Sema &S;
7552 SourceLocation UseLoc;
7553
7554 /// A mapping from the base classes through which the constructor was
7555 /// inherited to the using shadow declaration in that base class (or a null
7556 /// pointer if the constructor was declared in that base class).
7557 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7558 InheritedFromBases;
7559
7560public:
7561 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7562 ConstructorUsingShadowDecl *Shadow)
7563 : S(S), UseLoc(UseLoc) {
7564 bool DiagnosedMultipleConstructedBases = false;
7565 CXXRecordDecl *ConstructedBase = nullptr;
7566 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7567
7568 // Find the set of such base class subobjects and check that there's a
7569 // unique constructed subobject.
7570 for (auto *D : Shadow->redecls()) {
7571 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7572 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7573 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7574
7575 InheritedFromBases.insert(
7576 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7577 y: DShadow->getNominatedBaseClassShadowDecl()));
7578 if (DShadow->constructsVirtualBase())
7579 InheritedFromBases.insert(
7580 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7581 y: DShadow->getConstructedBaseClassShadowDecl()));
7582 else
7583 assert(DNominatedBase == DConstructedBase);
7584
7585 // [class.inhctor.init]p2:
7586 // If the constructor was inherited from multiple base class subobjects
7587 // of type B, the program is ill-formed.
7588 if (!ConstructedBase) {
7589 ConstructedBase = DConstructedBase;
7590 ConstructedBaseIntroducer = D->getIntroducer();
7591 } else if (ConstructedBase != DConstructedBase &&
7592 !Shadow->isInvalidDecl()) {
7593 if (!DiagnosedMultipleConstructedBases) {
7594 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7595 << Shadow->getTargetDecl();
7596 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7597 DiagID: diag::note_ambiguous_inherited_constructor_using)
7598 << ConstructedBase;
7599 DiagnosedMultipleConstructedBases = true;
7600 }
7601 S.Diag(Loc: D->getIntroducer()->getLocation(),
7602 DiagID: diag::note_ambiguous_inherited_constructor_using)
7603 << DConstructedBase;
7604 }
7605 }
7606
7607 if (DiagnosedMultipleConstructedBases)
7608 Shadow->setInvalidDecl();
7609 }
7610
7611 /// Find the constructor to use for inherited construction of a base class,
7612 /// and whether that base class constructor inherits the constructor from a
7613 /// virtual base class (in which case it won't actually invoke it).
7614 std::pair<CXXConstructorDecl *, bool>
7615 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7616 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7617 if (It == InheritedFromBases.end())
7618 return std::make_pair(x: nullptr, y: false);
7619
7620 // This is an intermediary class.
7621 if (It->second)
7622 return std::make_pair(
7623 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7624 y: It->second->constructsVirtualBase());
7625
7626 // This is the base class from which the constructor was inherited.
7627 return std::make_pair(x&: Ctor, y: false);
7628 }
7629};
7630
7631/// Is the special member function which would be selected to perform the
7632/// specified operation on the specified class type a constexpr constructor?
7633static bool specialMemberIsConstexpr(
7634 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7635 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7636 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7637 // Suppress duplicate constraint checking here, in case a constraint check
7638 // caused us to decide to do this. Any truely recursive checks will get
7639 // caught during these checks anyway.
7640 Sema::SatisfactionStackResetRAII SSRAII{S};
7641
7642 // If we're inheriting a constructor, see if we need to call it for this base
7643 // class.
7644 if (InheritedCtor) {
7645 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7646 auto BaseCtor =
7647 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7648 if (BaseCtor)
7649 return BaseCtor->isConstexpr();
7650 }
7651
7652 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7653 return ClassDecl->hasConstexprDefaultConstructor();
7654 if (CSM == CXXSpecialMemberKind::Destructor)
7655 return ClassDecl->hasConstexprDestructor();
7656
7657 Sema::SpecialMemberOverloadResult SMOR =
7658 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7659 if (!SMOR.getMethod())
7660 // A constructor we wouldn't select can't be "involved in initializing"
7661 // anything.
7662 return true;
7663 return SMOR.getMethod()->isConstexpr();
7664}
7665
7666/// Determine whether the specified special member function would be constexpr
7667/// if it were implicitly defined.
7668static bool defaultedSpecialMemberIsConstexpr(
7669 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7670 CXXConstructorDecl *InheritedCtor = nullptr,
7671 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7672 if (!S.getLangOpts().CPlusPlus11)
7673 return false;
7674
7675 // C++11 [dcl.constexpr]p4:
7676 // In the definition of a constexpr constructor [...]
7677 bool Ctor = true;
7678 switch (CSM) {
7679 case CXXSpecialMemberKind::DefaultConstructor:
7680 if (Inherited)
7681 break;
7682 // Since default constructor lookup is essentially trivial (and cannot
7683 // involve, for instance, template instantiation), we compute whether a
7684 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7685 //
7686 // This is important for performance; we need to know whether the default
7687 // constructor is constexpr to determine whether the type is a literal type.
7688 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7689
7690 case CXXSpecialMemberKind::CopyConstructor:
7691 case CXXSpecialMemberKind::MoveConstructor:
7692 // For copy or move constructors, we need to perform overload resolution.
7693 break;
7694
7695 case CXXSpecialMemberKind::CopyAssignment:
7696 case CXXSpecialMemberKind::MoveAssignment:
7697 if (!S.getLangOpts().CPlusPlus14)
7698 return false;
7699 // In C++1y, we need to perform overload resolution.
7700 Ctor = false;
7701 break;
7702
7703 case CXXSpecialMemberKind::Destructor:
7704 return ClassDecl->defaultedDestructorIsConstexpr();
7705
7706 case CXXSpecialMemberKind::Invalid:
7707 return false;
7708 }
7709
7710 // -- if the class is a non-empty union, or for each non-empty anonymous
7711 // union member of a non-union class, exactly one non-static data member
7712 // shall be initialized; [DR1359]
7713 //
7714 // If we squint, this is guaranteed, since exactly one non-static data member
7715 // will be initialized (if the constructor isn't deleted), we just don't know
7716 // which one.
7717 if (Ctor && ClassDecl->isUnion())
7718 return CSM == CXXSpecialMemberKind::DefaultConstructor
7719 ? ClassDecl->hasInClassInitializer() ||
7720 !ClassDecl->hasVariantMembers()
7721 : true;
7722
7723 // -- the class shall not have any virtual base classes;
7724 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7725 return false;
7726
7727 // C++1y [class.copy]p26:
7728 // -- [the class] is a literal type, and
7729 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7730 return false;
7731
7732 // -- every constructor involved in initializing [...] base class
7733 // sub-objects shall be a constexpr constructor;
7734 // -- the assignment operator selected to copy/move each direct base
7735 // class is a constexpr function, and
7736 if (!S.getLangOpts().CPlusPlus23) {
7737 for (const auto &B : ClassDecl->bases()) {
7738 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7739 if (!BaseClassDecl)
7740 continue;
7741 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7742 InheritedCtor, Inherited))
7743 return false;
7744 }
7745 }
7746
7747 // -- every constructor involved in initializing non-static data members
7748 // [...] shall be a constexpr constructor;
7749 // -- every non-static data member and base class sub-object shall be
7750 // initialized
7751 // -- for each non-static data member of X that is of class type (or array
7752 // thereof), the assignment operator selected to copy/move that member is
7753 // a constexpr function
7754 if (!S.getLangOpts().CPlusPlus23) {
7755 for (const auto *F : ClassDecl->fields()) {
7756 if (F->isInvalidDecl())
7757 continue;
7758 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7759 F->hasInClassInitializer())
7760 continue;
7761 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7762 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7763 auto *FieldRecDecl =
7764 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7765 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7766 Quals: BaseType.getCVRQualifiers(),
7767 ConstRHS: ConstArg && !F->isMutable()))
7768 return false;
7769 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7770 return false;
7771 }
7772 }
7773 }
7774
7775 // All OK, it's constexpr!
7776 return true;
7777}
7778
7779namespace {
7780/// RAII object to register a defaulted function as having its exception
7781/// specification computed.
7782struct ComputingExceptionSpec {
7783 Sema &S;
7784
7785 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7786 : S(S) {
7787 Sema::CodeSynthesisContext Ctx;
7788 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7789 Ctx.PointOfInstantiation = Loc;
7790 Ctx.Entity = FD;
7791 S.pushCodeSynthesisContext(Ctx);
7792 }
7793 ~ComputingExceptionSpec() {
7794 S.popCodeSynthesisContext();
7795 }
7796};
7797}
7798
7799static Sema::ImplicitExceptionSpecification
7800ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7801 CXXMethodDecl *MD,
7802 CXXSpecialMemberKind CSM,
7803 Sema::InheritedConstructorInfo *ICI);
7804
7805static Sema::ImplicitExceptionSpecification
7806ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7807 FunctionDecl *FD,
7808 Sema::DefaultedComparisonKind DCK);
7809
7810static Sema::ImplicitExceptionSpecification
7811computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7812 auto DFK = S.getDefaultedFunctionKind(FD);
7813 if (DFK.isSpecialMember())
7814 return ComputeDefaultedSpecialMemberExceptionSpec(
7815 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7816 if (DFK.isComparison())
7817 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7818 DCK: DFK.asComparison());
7819
7820 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7821 assert(CD->getInheritedConstructor() &&
7822 "only defaulted functions and inherited constructors have implicit "
7823 "exception specs");
7824 Sema::InheritedConstructorInfo ICI(
7825 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7826 return ComputeDefaultedSpecialMemberExceptionSpec(
7827 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7828}
7829
7830static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7831 CXXMethodDecl *MD) {
7832 FunctionProtoType::ExtProtoInfo EPI;
7833
7834 // Build an exception specification pointing back at this member.
7835 EPI.ExceptionSpec.Type = EST_Unevaluated;
7836 EPI.ExceptionSpec.SourceDecl = MD;
7837
7838 // Set the calling convention to the default for C++ instance methods.
7839 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7840 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7841 /*IsCXXMethod=*/true));
7842 return EPI;
7843}
7844
7845void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7846 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7847 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7848 return;
7849
7850 // Evaluate the exception specification.
7851 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7852 auto ESI = IES.getExceptionSpec();
7853
7854 // Update the type of the special member to use it.
7855 UpdateExceptionSpec(FD, ESI);
7856}
7857
7858void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7859 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7860
7861 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7862 if (!DefKind) {
7863 assert(FD->getDeclContext()->isDependentContext());
7864 return;
7865 }
7866
7867 if (DefKind.isComparison()) {
7868 auto PT = FD->getParamDecl(i: 0)->getType();
7869 if (const CXXRecordDecl *RD =
7870 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7871 for (FieldDecl *Field : RD->fields()) {
7872 UnusedPrivateFields.remove(X: Field);
7873 }
7874 }
7875 }
7876
7877 if (DefKind.isSpecialMember()
7878 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7879 CSM: DefKind.asSpecialMember(),
7880 DefaultLoc: FD->getDefaultLoc())
7881 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7882 FD->setInvalidDecl();
7883}
7884
7885bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7886 CXXSpecialMemberKind CSM,
7887 SourceLocation DefaultLoc) {
7888 CXXRecordDecl *RD = MD->getParent();
7889
7890 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7891 "not an explicitly-defaulted special member");
7892
7893 // Defer all checking for special members of a dependent type.
7894 if (RD->isDependentType())
7895 return false;
7896
7897 // Whether this was the first-declared instance of the constructor.
7898 // This affects whether we implicitly add an exception spec and constexpr.
7899 bool First = MD == MD->getCanonicalDecl();
7900
7901 bool HadError = false;
7902
7903 // C++11 [dcl.fct.def.default]p1:
7904 // A function that is explicitly defaulted shall
7905 // -- be a special member function [...] (checked elsewhere),
7906 // -- have the same type (except for ref-qualifiers, and except that a
7907 // copy operation can take a non-const reference) as an implicit
7908 // declaration, and
7909 // -- not have default arguments.
7910 // C++2a changes the second bullet to instead delete the function if it's
7911 // defaulted on its first declaration, unless it's "an assignment operator,
7912 // and its return type differs or its parameter type is not a reference".
7913 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7914 bool ShouldDeleteForTypeMismatch = false;
7915 unsigned ExpectedParams = 1;
7916 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7917 CSM == CXXSpecialMemberKind::Destructor)
7918 ExpectedParams = 0;
7919 if (MD->getNumExplicitParams() != ExpectedParams) {
7920 // This checks for default arguments: a copy or move constructor with a
7921 // default argument is classified as a default constructor, and assignment
7922 // operations and destructors can't have default arguments.
7923 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7924 << CSM << MD->getSourceRange();
7925 HadError = true;
7926 } else if (MD->isVariadic()) {
7927 if (DeleteOnTypeMismatch)
7928 ShouldDeleteForTypeMismatch = true;
7929 else {
7930 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7931 << CSM << MD->getSourceRange();
7932 HadError = true;
7933 }
7934 }
7935
7936 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7937
7938 bool CanHaveConstParam = false;
7939 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7940 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7941 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7942 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7943
7944 QualType ReturnType = Context.VoidTy;
7945 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7946 CSM == CXXSpecialMemberKind::MoveAssignment) {
7947 // Check for return type matching.
7948 ReturnType = Type->getReturnType();
7949 QualType ThisType = MD->getFunctionObjectParameterType();
7950
7951 QualType DeclType =
7952 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7953 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7954 DeclType = Context.getAddrSpaceQualType(
7955 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7956 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7957
7958 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7959 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7960 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7961 << ExpectedReturnType;
7962 HadError = true;
7963 }
7964
7965 // A defaulted special member cannot have cv-qualifiers.
7966 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7967 if (DeleteOnTypeMismatch)
7968 ShouldDeleteForTypeMismatch = true;
7969 else {
7970 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7971 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7972 << getLangOpts().CPlusPlus14;
7973 HadError = true;
7974 }
7975 }
7976 // [C++23][dcl.fct.def.default]/p2.2
7977 // if F2 has an implicit object parameter of type “reference to C”,
7978 // F1 may be an explicit object member function whose explicit object
7979 // parameter is of (possibly different) type “reference to C”,
7980 // in which case the type of F1 would differ from the type of F2
7981 // in that the type of F1 has an additional parameter;
7982 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7983 ? MD->getParamDecl(i: 0)->getType()
7984 : QualType();
7985 if (!ExplicitObjectParameter.isNull() &&
7986 (!ExplicitObjectParameter->isReferenceType() ||
7987 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7988 T2: Context.getCanonicalTagType(TD: RD)))) {
7989 if (DeleteOnTypeMismatch)
7990 ShouldDeleteForTypeMismatch = true;
7991 else {
7992 Diag(Loc: MD->getLocation(),
7993 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
7994 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7995 << MD->getSourceRange();
7996 HadError = true;
7997 }
7998 }
7999 }
8000
8001 // Check for parameter type matching.
8002 QualType ArgType =
8003 ExpectedParams
8004 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
8005 : QualType();
8006 bool HasConstParam = false;
8007 if (ExpectedParams && ArgType->isReferenceType()) {
8008 // Argument must be reference to possibly-const T.
8009 QualType ReferentType = ArgType->getPointeeType();
8010 HasConstParam = ReferentType.isConstQualified();
8011
8012 if (ReferentType.isVolatileQualified()) {
8013 if (DeleteOnTypeMismatch)
8014 ShouldDeleteForTypeMismatch = true;
8015 else {
8016 Diag(Loc: MD->getLocation(),
8017 DiagID: diag::err_defaulted_special_member_volatile_param)
8018 << CSM;
8019 HadError = true;
8020 }
8021 }
8022
8023 if (HasConstParam && !CanHaveConstParam) {
8024 if (DeleteOnTypeMismatch)
8025 ShouldDeleteForTypeMismatch = true;
8026 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8027 CSM == CXXSpecialMemberKind::CopyAssignment) {
8028 Diag(Loc: MD->getLocation(),
8029 DiagID: diag::err_defaulted_special_member_copy_const_param)
8030 << (CSM == CXXSpecialMemberKind::CopyAssignment);
8031 // FIXME: Explain why this special member can't be const.
8032 HadError = true;
8033 } else {
8034 Diag(Loc: MD->getLocation(),
8035 DiagID: diag::err_defaulted_special_member_move_const_param)
8036 << (CSM == CXXSpecialMemberKind::MoveAssignment);
8037 HadError = true;
8038 }
8039 }
8040 } else if (ExpectedParams) {
8041 // A copy assignment operator can take its argument by value, but a
8042 // defaulted one cannot.
8043 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
8044 "unexpected non-ref argument");
8045 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
8046 HadError = true;
8047 }
8048
8049 // C++11 [dcl.fct.def.default]p2:
8050 // An explicitly-defaulted function may be declared constexpr only if it
8051 // would have been implicitly declared as constexpr,
8052 // Do not apply this rule to members of class templates, since core issue 1358
8053 // makes such functions always instantiate to constexpr functions. For
8054 // functions which cannot be constexpr (for non-constructors in C++11 and for
8055 // destructors in C++14 and C++17), this is checked elsewhere.
8056 //
8057 // FIXME: This should not apply if the member is deleted.
8058 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8059 ConstArg: HasConstParam);
8060
8061 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8062 // If the instantiated template specialization of a constexpr function
8063 // template or member function of a class template would fail to satisfy
8064 // the requirements for a constexpr function or constexpr constructor, that
8065 // specialization is still a constexpr function or constexpr constructor,
8066 // even though a call to such a function cannot appear in a constant
8067 // expression.
8068 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8069 Constexpr = true;
8070
8071 if ((getLangOpts().CPlusPlus20 ||
8072 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8073 : isa<CXXConstructorDecl>(Val: MD))) &&
8074 MD->isConstexpr() && !Constexpr &&
8075 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8076 if (!MD->isConsteval() && RD->getNumVBases()) {
8077 Diag(Loc: MD->getBeginLoc(),
8078 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8079 << CSM;
8080 for (const auto &I : RD->vbases())
8081 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8082 } else {
8083 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8084 << CSM << MD->isConsteval();
8085 }
8086 HadError = true;
8087 // FIXME: Explain why the special member can't be constexpr.
8088 }
8089 if (First) {
8090 // C++2a [dcl.fct.def.default]p3:
8091 // If a function is explicitly defaulted on its first declaration, it is
8092 // implicitly considered to be constexpr if the implicit declaration
8093 // would be.
8094 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8095 ? ConstexprSpecKind::Consteval
8096 : ConstexprSpecKind::Constexpr)
8097 : ConstexprSpecKind::Unspecified);
8098
8099 if (!Type->hasExceptionSpec()) {
8100 // C++2a [except.spec]p3:
8101 // If a declaration of a function does not have a noexcept-specifier
8102 // [and] is defaulted on its first declaration, [...] the exception
8103 // specification is as specified below
8104 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8105 EPI.ExceptionSpec.Type = EST_Unevaluated;
8106 EPI.ExceptionSpec.SourceDecl = MD;
8107 MD->setType(
8108 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8109 }
8110 }
8111
8112 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8113 if (First) {
8114 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8115 if (!inTemplateInstantiation() && !HadError) {
8116 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8117 if (ShouldDeleteForTypeMismatch) {
8118 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8119 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8120 /*Diagnose*/ true) &&
8121 DefaultLoc.isValid()) {
8122 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8123 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8124 }
8125 }
8126 if (ShouldDeleteForTypeMismatch && !HadError) {
8127 Diag(Loc: MD->getLocation(),
8128 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8129 << CSM;
8130 }
8131 } else {
8132 // C++11 [dcl.fct.def.default]p4:
8133 // [For a] user-provided explicitly-defaulted function [...] if such a
8134 // function is implicitly defined as deleted, the program is ill-formed.
8135 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8136 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8137 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8138 HadError = true;
8139 }
8140 }
8141
8142 return HadError;
8143}
8144
8145namespace {
8146/// Helper class for building and checking a defaulted comparison.
8147///
8148/// Defaulted functions are built in two phases:
8149///
8150/// * First, the set of operations that the function will perform are
8151/// identified, and some of them are checked. If any of the checked
8152/// operations is invalid in certain ways, the comparison function is
8153/// defined as deleted and no body is built.
8154/// * Then, if the function is not defined as deleted, the body is built.
8155///
8156/// This is accomplished by performing two visitation steps over the eventual
8157/// body of the function.
8158template<typename Derived, typename ResultList, typename Result,
8159 typename Subobject>
8160class DefaultedComparisonVisitor {
8161public:
8162 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8163
8164 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8165 DefaultedComparisonKind DCK)
8166 : S(S), RD(RD), FD(FD), DCK(DCK) {
8167 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8168 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8169 // UnresolvedSet to avoid this copy.
8170 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8171 E: Info->getUnqualifiedLookups().end());
8172 }
8173 }
8174
8175 ResultList visit() {
8176 // The type of an lvalue naming a parameter of this function.
8177 QualType ParamLvalType =
8178 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8179
8180 ResultList Results;
8181
8182 switch (DCK) {
8183 case DefaultedComparisonKind::None:
8184 llvm_unreachable("not a defaulted comparison");
8185
8186 case DefaultedComparisonKind::Equal:
8187 case DefaultedComparisonKind::ThreeWay:
8188 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8189 return Results;
8190
8191 case DefaultedComparisonKind::NotEqual:
8192 case DefaultedComparisonKind::Relational:
8193 Results.add(getDerived().visitExpandedSubobject(
8194 ParamLvalType, getDerived().getCompleteObject()));
8195 return Results;
8196 }
8197 llvm_unreachable("");
8198 }
8199
8200protected:
8201 Derived &getDerived() { return static_cast<Derived&>(*this); }
8202
8203 /// Visit the expanded list of subobjects of the given type, as specified in
8204 /// C++2a [class.compare.default].
8205 ///
8206 /// \return \c true if the ResultList object said we're done, \c false if not.
8207 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8208 Qualifiers Quals) {
8209 // C++2a [class.compare.default]p4:
8210 // The direct base class subobjects of C
8211 for (CXXBaseSpecifier &Base : Record->bases())
8212 if (Results.add(getDerived().visitSubobject(
8213 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8214 getDerived().getBase(&Base))))
8215 return true;
8216
8217 // followed by the non-static data members of C
8218 for (FieldDecl *Field : Record->fields()) {
8219 // C++23 [class.bit]p2:
8220 // Unnamed bit-fields are not members ...
8221 if (Field->isUnnamedBitField())
8222 continue;
8223 // Recursively expand anonymous structs.
8224 if (Field->isAnonymousStructOrUnion()) {
8225 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8226 Quals))
8227 return true;
8228 continue;
8229 }
8230
8231 // Figure out the type of an lvalue denoting this field.
8232 Qualifiers FieldQuals = Quals;
8233 if (Field->isMutable())
8234 FieldQuals.removeConst();
8235 QualType FieldType =
8236 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8237
8238 if (Results.add(getDerived().visitSubobject(
8239 FieldType, getDerived().getField(Field))))
8240 return true;
8241 }
8242
8243 // form a list of subobjects.
8244 return false;
8245 }
8246
8247 Result visitSubobject(QualType Type, Subobject Subobj) {
8248 // In that list, any subobject of array type is recursively expanded
8249 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8250 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8251 return getDerived().visitSubobjectArray(CAT->getElementType(),
8252 CAT->getSize(), Subobj);
8253 return getDerived().visitExpandedSubobject(Type, Subobj);
8254 }
8255
8256 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8257 Subobject Subobj) {
8258 return getDerived().visitSubobject(Type, Subobj);
8259 }
8260
8261protected:
8262 Sema &S;
8263 CXXRecordDecl *RD;
8264 FunctionDecl *FD;
8265 DefaultedComparisonKind DCK;
8266 UnresolvedSet<16> Fns;
8267};
8268
8269/// Information about a defaulted comparison, as determined by
8270/// DefaultedComparisonAnalyzer.
8271struct DefaultedComparisonInfo {
8272 bool Deleted = false;
8273 bool Constexpr = true;
8274 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8275
8276 static DefaultedComparisonInfo deleted() {
8277 DefaultedComparisonInfo Deleted;
8278 Deleted.Deleted = true;
8279 return Deleted;
8280 }
8281
8282 bool add(const DefaultedComparisonInfo &R) {
8283 Deleted |= R.Deleted;
8284 Constexpr &= R.Constexpr;
8285 Category = commonComparisonType(A: Category, B: R.Category);
8286 return Deleted;
8287 }
8288};
8289
8290/// An element in the expanded list of subobjects of a defaulted comparison, as
8291/// specified in C++2a [class.compare.default]p4.
8292struct DefaultedComparisonSubobject {
8293 enum { CompleteObject, Member, Base } Kind;
8294 NamedDecl *Decl;
8295 SourceLocation Loc;
8296};
8297
8298/// A visitor over the notional body of a defaulted comparison that determines
8299/// whether that body would be deleted or constexpr.
8300class DefaultedComparisonAnalyzer
8301 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8302 DefaultedComparisonInfo,
8303 DefaultedComparisonInfo,
8304 DefaultedComparisonSubobject> {
8305public:
8306 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8307
8308private:
8309 DiagnosticKind Diagnose;
8310
8311public:
8312 using Base = DefaultedComparisonVisitor;
8313 using Result = DefaultedComparisonInfo;
8314 using Subobject = DefaultedComparisonSubobject;
8315
8316 friend Base;
8317
8318 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8319 DefaultedComparisonKind DCK,
8320 DiagnosticKind Diagnose = NoDiagnostics)
8321 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8322
8323 Result visit() {
8324 if ((DCK == DefaultedComparisonKind::Equal ||
8325 DCK == DefaultedComparisonKind::ThreeWay) &&
8326 RD->hasVariantMembers()) {
8327 // C++2a [class.compare.default]p2 [P2002R0]:
8328 // A defaulted comparison operator function for class C is defined as
8329 // deleted if [...] C has variant members.
8330 if (Diagnose == ExplainDeleted) {
8331 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8332 << FD << RD->isUnion() << RD;
8333 }
8334 return Result::deleted();
8335 }
8336
8337 return Base::visit();
8338 }
8339
8340private:
8341 Subobject getCompleteObject() {
8342 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8343 }
8344
8345 Subobject getBase(CXXBaseSpecifier *Base) {
8346 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8347 .Loc: Base->getBaseTypeLoc()};
8348 }
8349
8350 Subobject getField(FieldDecl *Field) {
8351 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8352 }
8353
8354 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8355 // C++2a [class.compare.default]p2 [P2002R0]:
8356 // A defaulted <=> or == operator function for class C is defined as
8357 // deleted if any non-static data member of C is of reference type
8358 if (Type->isReferenceType()) {
8359 if (Diagnose == ExplainDeleted) {
8360 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8361 << FD << RD;
8362 }
8363 return Result::deleted();
8364 }
8365
8366 // [...] Let xi be an lvalue denoting the ith element [...]
8367 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8368 Expr *Args[] = {&Xi, &Xi};
8369
8370 // All operators start by trying to apply that same operator recursively.
8371 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8372 assert(OO != OO_None && "not an overloaded operator!");
8373 return visitBinaryOperator(OO, Args, Subobj);
8374 }
8375
8376 Result
8377 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8378 Subobject Subobj,
8379 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8380 // Note that there is no need to consider rewritten candidates here if
8381 // we've already found there is no viable 'operator<=>' candidate (and are
8382 // considering synthesizing a '<=>' from '==' and '<').
8383 OverloadCandidateSet CandidateSet(
8384 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8385 OverloadCandidateSet::OperatorRewriteInfo(
8386 OO, FD->getLocation(),
8387 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8388
8389 /// C++2a [class.compare.default]p1 [P2002R0]:
8390 /// [...] the defaulted function itself is never a candidate for overload
8391 /// resolution [...]
8392 CandidateSet.exclude(F: FD);
8393
8394 if (Args[0]->getType()->isOverloadableType())
8395 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8396 else
8397 // FIXME: We determine whether this is a valid expression by checking to
8398 // see if there's a viable builtin operator candidate for it. That isn't
8399 // really what the rules ask us to do, but should give the right results.
8400 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8401
8402 Result R;
8403
8404 OverloadCandidateSet::iterator Best;
8405 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8406 case OR_Success: {
8407 // C++2a [class.compare.secondary]p2 [P2002R0]:
8408 // The operator function [...] is defined as deleted if [...] the
8409 // candidate selected by overload resolution is not a rewritten
8410 // candidate.
8411 if ((DCK == DefaultedComparisonKind::NotEqual ||
8412 DCK == DefaultedComparisonKind::Relational) &&
8413 !Best->RewriteKind) {
8414 if (Diagnose == ExplainDeleted) {
8415 if (Best->Function) {
8416 S.Diag(Loc: Best->Function->getLocation(),
8417 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8418 << FD;
8419 } else {
8420 assert(Best->Conversions.size() == 2 &&
8421 Best->Conversions[0].isUserDefined() &&
8422 "non-user-defined conversion from class to built-in "
8423 "comparison");
8424 S.Diag(Loc: Best->Conversions[0]
8425 .UserDefined.FoundConversionFunction.getDecl()
8426 ->getLocation(),
8427 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8428 << FD;
8429 }
8430 }
8431 return Result::deleted();
8432 }
8433
8434 // Throughout C++2a [class.compare]: if overload resolution does not
8435 // result in a usable function, the candidate function is defined as
8436 // deleted. This requires that we selected an accessible function.
8437 //
8438 // Note that this only considers the access of the function when named
8439 // within the type of the subobject, and not the access path for any
8440 // derived-to-base conversion.
8441 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8442 if (ArgClass && Best->FoundDecl.getDecl() &&
8443 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8444 QualType ObjectType = Subobj.Kind == Subobject::Member
8445 ? Args[0]->getType()
8446 : S.Context.getCanonicalTagType(TD: RD);
8447 if (!S.isMemberAccessibleForDeletion(
8448 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8449 Diag: Diagnose == ExplainDeleted
8450 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8451 << FD << Subobj.Kind << Subobj.Decl
8452 : S.PDiag()))
8453 return Result::deleted();
8454 }
8455
8456 bool NeedsDeducing =
8457 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8458
8459 if (FunctionDecl *BestFD = Best->Function) {
8460 // C++2a [class.compare.default]p3 [P2002R0]:
8461 // A defaulted comparison function is constexpr-compatible if
8462 // [...] no overlod resolution performed [...] results in a
8463 // non-constexpr function.
8464 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8465 // If it's not constexpr, explain why not.
8466 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8467 if (Subobj.Kind != Subobject::CompleteObject)
8468 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8469 << Subobj.Kind << Subobj.Decl;
8470 S.Diag(Loc: BestFD->getLocation(),
8471 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8472 // Bail out after explaining; we don't want any more notes.
8473 return Result::deleted();
8474 }
8475 R.Constexpr &= BestFD->isConstexpr();
8476
8477 if (NeedsDeducing) {
8478 // If any callee has an undeduced return type, deduce it now.
8479 // FIXME: It's not clear how a failure here should be handled. For
8480 // now, we produce an eager diagnostic, because that is forward
8481 // compatible with most (all?) other reasonable options.
8482 if (BestFD->getReturnType()->isUndeducedType() &&
8483 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8484 /*Diagnose=*/false)) {
8485 // Don't produce a duplicate error when asked to explain why the
8486 // comparison is deleted: we diagnosed that when initially checking
8487 // the defaulted operator.
8488 if (Diagnose == NoDiagnostics) {
8489 S.Diag(
8490 Loc: FD->getLocation(),
8491 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8492 << Subobj.Kind << Subobj.Decl;
8493 S.Diag(
8494 Loc: Subobj.Loc,
8495 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8496 << Subobj.Kind << Subobj.Decl;
8497 S.Diag(Loc: BestFD->getLocation(),
8498 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8499 << Subobj.Kind << Subobj.Decl;
8500 }
8501 return Result::deleted();
8502 }
8503 auto *Info = S.Context.CompCategories.lookupInfoForType(
8504 Ty: BestFD->getCallResultType());
8505 if (!Info) {
8506 if (Diagnose == ExplainDeleted) {
8507 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8508 << Subobj.Kind << Subobj.Decl
8509 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8510 S.Diag(Loc: BestFD->getLocation(),
8511 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8512 << Subobj.Kind << Subobj.Decl;
8513 }
8514 return Result::deleted();
8515 }
8516 R.Category = Info->Kind;
8517 }
8518 } else {
8519 QualType T = Best->BuiltinParamTypes[0];
8520 assert(T == Best->BuiltinParamTypes[1] &&
8521 "builtin comparison for different types?");
8522 assert(Best->BuiltinParamTypes[2].isNull() &&
8523 "invalid builtin comparison");
8524
8525 // FIXME: If the type we deduced is a vector type, we mark the
8526 // comparison as deleted because we don't yet support this.
8527 if (isa<VectorType>(Val: T)) {
8528 if (Diagnose == ExplainDeleted) {
8529 S.Diag(Loc: FD->getLocation(),
8530 DiagID: diag::note_defaulted_comparison_vector_types)
8531 << FD;
8532 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8533 }
8534 return Result::deleted();
8535 }
8536
8537 if (NeedsDeducing) {
8538 std::optional<ComparisonCategoryType> Cat =
8539 getComparisonCategoryForBuiltinCmp(T);
8540 assert(Cat && "no category for builtin comparison?");
8541 R.Category = *Cat;
8542 }
8543 }
8544
8545 // Note that we might be rewriting to a different operator. That call is
8546 // not considered until we come to actually build the comparison function.
8547 break;
8548 }
8549
8550 case OR_Ambiguous:
8551 if (Diagnose == ExplainDeleted) {
8552 unsigned Kind = 0;
8553 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8554 Kind = OO == OO_EqualEqual ? 1 : 2;
8555 CandidateSet.NoteCandidates(
8556 PA: PartialDiagnosticAt(
8557 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8558 << FD << Kind << Subobj.Kind << Subobj.Decl),
8559 S, OCD: OCD_AmbiguousCandidates, Args);
8560 }
8561 R = Result::deleted();
8562 break;
8563
8564 case OR_Deleted:
8565 if (Diagnose == ExplainDeleted) {
8566 if ((DCK == DefaultedComparisonKind::NotEqual ||
8567 DCK == DefaultedComparisonKind::Relational) &&
8568 !Best->RewriteKind) {
8569 S.Diag(Loc: Best->Function->getLocation(),
8570 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8571 << FD;
8572 } else {
8573 S.Diag(Loc: Subobj.Loc,
8574 DiagID: diag::note_defaulted_comparison_calls_deleted)
8575 << FD << Subobj.Kind << Subobj.Decl;
8576 S.NoteDeletedFunction(FD: Best->Function);
8577 }
8578 }
8579 R = Result::deleted();
8580 break;
8581
8582 case OR_No_Viable_Function:
8583 // If there's no usable candidate, we're done unless we can rewrite a
8584 // '<=>' in terms of '==' and '<'.
8585 if (OO == OO_Spaceship &&
8586 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8587 // For any kind of comparison category return type, we need a usable
8588 // '==' and a usable '<'.
8589 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8590 SpaceshipCandidates: &CandidateSet)))
8591 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8592 break;
8593 }
8594
8595 if (Diagnose == ExplainDeleted) {
8596 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8597 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8598 << Subobj.Kind << Subobj.Decl;
8599
8600 // For a three-way comparison, list both the candidates for the
8601 // original operator and the candidates for the synthesized operator.
8602 if (SpaceshipCandidates) {
8603 SpaceshipCandidates->NoteCandidates(
8604 S, Args,
8605 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8606 Args, OpLoc: FD->getLocation()));
8607 S.Diag(Loc: Subobj.Loc,
8608 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8609 << (OO == OO_EqualEqual ? 0 : 1);
8610 }
8611
8612 CandidateSet.NoteCandidates(
8613 S, Args,
8614 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8615 OpLoc: FD->getLocation()));
8616 }
8617 R = Result::deleted();
8618 break;
8619 }
8620
8621 return R;
8622 }
8623};
8624
8625/// A list of statements.
8626struct StmtListResult {
8627 bool IsInvalid = false;
8628 llvm::SmallVector<Stmt*, 16> Stmts;
8629
8630 bool add(const StmtResult &S) {
8631 IsInvalid |= S.isInvalid();
8632 if (IsInvalid)
8633 return true;
8634 Stmts.push_back(Elt: S.get());
8635 return false;
8636 }
8637};
8638
8639/// A visitor over the notional body of a defaulted comparison that synthesizes
8640/// the actual body.
8641class DefaultedComparisonSynthesizer
8642 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8643 StmtListResult, StmtResult,
8644 std::pair<ExprResult, ExprResult>> {
8645 SourceLocation Loc;
8646 unsigned ArrayDepth = 0;
8647
8648public:
8649 using Base = DefaultedComparisonVisitor;
8650 using ExprPair = std::pair<ExprResult, ExprResult>;
8651
8652 friend Base;
8653
8654 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8655 DefaultedComparisonKind DCK,
8656 SourceLocation BodyLoc)
8657 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8658
8659 /// Build a suitable function body for this defaulted comparison operator.
8660 StmtResult build() {
8661 Sema::CompoundScopeRAII CompoundScope(S);
8662
8663 StmtListResult Stmts = visit();
8664 if (Stmts.IsInvalid)
8665 return StmtError();
8666
8667 ExprResult RetVal;
8668 switch (DCK) {
8669 case DefaultedComparisonKind::None:
8670 llvm_unreachable("not a defaulted comparison");
8671
8672 case DefaultedComparisonKind::Equal: {
8673 // C++2a [class.eq]p3:
8674 // [...] compar[e] the corresponding elements [...] until the first
8675 // index i where xi == yi yields [...] false. If no such index exists,
8676 // V is true. Otherwise, V is false.
8677 //
8678 // Join the comparisons with '&&'s and return the result. Use a right
8679 // fold (traversing the conditions right-to-left), because that
8680 // short-circuits more naturally.
8681 auto OldStmts = std::move(Stmts.Stmts);
8682 Stmts.Stmts.clear();
8683 ExprResult CmpSoFar;
8684 // Finish a particular comparison chain.
8685 auto FinishCmp = [&] {
8686 if (Expr *Prior = CmpSoFar.get()) {
8687 // Convert the last expression to 'return ...;'
8688 if (RetVal.isUnset() && Stmts.Stmts.empty())
8689 RetVal = CmpSoFar;
8690 // Convert any prior comparison to 'if (!(...)) return false;'
8691 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8692 return true;
8693 CmpSoFar = ExprResult();
8694 }
8695 return false;
8696 };
8697 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8698 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8699 if (!E) {
8700 // Found an array comparison.
8701 if (FinishCmp() || Stmts.add(S: EAsStmt))
8702 return StmtError();
8703 continue;
8704 }
8705
8706 if (CmpSoFar.isUnset()) {
8707 CmpSoFar = E;
8708 continue;
8709 }
8710 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8711 if (CmpSoFar.isInvalid())
8712 return StmtError();
8713 }
8714 if (FinishCmp())
8715 return StmtError();
8716 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8717 // If no such index exists, V is true.
8718 if (RetVal.isUnset())
8719 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8720 break;
8721 }
8722
8723 case DefaultedComparisonKind::ThreeWay: {
8724 // Per C++2a [class.spaceship]p3, as a fallback add:
8725 // return static_cast<R>(std::strong_ordering::equal);
8726 QualType StrongOrdering = S.CheckComparisonCategoryType(
8727 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8728 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8729 if (StrongOrdering.isNull())
8730 return StmtError();
8731 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8732 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8733 ->VD;
8734 RetVal = getDecl(VD: EqualVD);
8735 if (RetVal.isInvalid())
8736 return StmtError();
8737 RetVal = buildStaticCastToR(E: RetVal.get());
8738 break;
8739 }
8740
8741 case DefaultedComparisonKind::NotEqual:
8742 case DefaultedComparisonKind::Relational:
8743 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8744 break;
8745 }
8746
8747 // Build the final return statement.
8748 if (RetVal.isInvalid())
8749 return StmtError();
8750 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8751 if (ReturnStmt.isInvalid())
8752 return StmtError();
8753 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8754
8755 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8756 }
8757
8758private:
8759 ExprResult getDecl(ValueDecl *VD) {
8760 return S.BuildDeclarationNameExpr(
8761 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8762 }
8763
8764 ExprResult getParam(unsigned I) {
8765 ParmVarDecl *PD = FD->getParamDecl(i: I);
8766 return getDecl(VD: PD);
8767 }
8768
8769 ExprPair getCompleteObject() {
8770 unsigned Param = 0;
8771 ExprResult LHS;
8772 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8773 MD && MD->isImplicitObjectMemberFunction()) {
8774 // LHS is '*this'.
8775 LHS = S.ActOnCXXThis(Loc);
8776 if (!LHS.isInvalid())
8777 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8778 } else {
8779 LHS = getParam(I: Param++);
8780 }
8781 ExprResult RHS = getParam(I: Param++);
8782 assert(Param == FD->getNumParams());
8783 return {LHS, RHS};
8784 }
8785
8786 ExprPair getBase(CXXBaseSpecifier *Base) {
8787 ExprPair Obj = getCompleteObject();
8788 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8789 return {ExprError(), ExprError()};
8790 CXXCastPath Path = {Base};
8791 const auto CastToBase = [&](Expr *E) {
8792 QualType ToType = S.Context.getQualifiedType(
8793 T: Base->getType(), Qs: E->getType().getQualifiers());
8794 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8795 };
8796 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8797 }
8798
8799 ExprPair getField(FieldDecl *Field) {
8800 ExprPair Obj = getCompleteObject();
8801 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8802 return {ExprError(), ExprError()};
8803
8804 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8805 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8806 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8807 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8808 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8809 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8810 }
8811
8812 // FIXME: When expanding a subobject, register a note in the code synthesis
8813 // stack to say which subobject we're comparing.
8814
8815 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8816 if (Cond.isInvalid())
8817 return StmtError();
8818
8819 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8820 if (NotCond.isInvalid())
8821 return StmtError();
8822
8823 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8824 assert(!False.isInvalid() && "should never fail");
8825 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8826 if (ReturnFalse.isInvalid())
8827 return StmtError();
8828
8829 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8830 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8831 CK: Sema::ConditionKind::Boolean),
8832 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8833 }
8834
8835 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8836 ExprPair Subobj) {
8837 QualType SizeType = S.Context.getSizeType();
8838 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8839
8840 // Build 'size_t i$n = 0'.
8841 IdentifierInfo *IterationVarName = nullptr;
8842 {
8843 SmallString<8> Str;
8844 llvm::raw_svector_ostream OS(Str);
8845 OS << "i" << ArrayDepth;
8846 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8847 }
8848 VarDecl *IterationVar = VarDecl::Create(
8849 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8850 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8851 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8852 IterationVar->setInit(
8853 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8854 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8855
8856 auto IterRef = [&] {
8857 ExprResult Ref = S.BuildDeclarationNameExpr(
8858 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8859 D: IterationVar);
8860 assert(!Ref.isInvalid() && "can't reference our own variable?");
8861 return Ref.get();
8862 };
8863
8864 // Build 'i$n != Size'.
8865 ExprResult Cond = S.CreateBuiltinBinOp(
8866 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8867 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8868 assert(!Cond.isInvalid() && "should never fail");
8869
8870 // Build '++i$n'.
8871 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8872 assert(!Inc.isInvalid() && "should never fail");
8873
8874 // Build 'a[i$n]' and 'b[i$n]'.
8875 auto Index = [&](ExprResult E) {
8876 if (E.isInvalid())
8877 return ExprError();
8878 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8879 };
8880 Subobj.first = Index(Subobj.first);
8881 Subobj.second = Index(Subobj.second);
8882
8883 // Compare the array elements.
8884 ++ArrayDepth;
8885 StmtResult Substmt = visitSubobject(Type, Subobj);
8886 --ArrayDepth;
8887
8888 if (Substmt.isInvalid())
8889 return StmtError();
8890
8891 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8892 // For outer levels or for an 'operator<=>' we already have a suitable
8893 // statement that returns as necessary.
8894 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8895 assert(DCK == DefaultedComparisonKind::Equal &&
8896 "should have non-expression statement");
8897 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8898 if (Substmt.isInvalid())
8899 return StmtError();
8900 }
8901
8902 // Build 'for (...) ...'
8903 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8904 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8905 CK: Sema::ConditionKind::Boolean),
8906 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8907 Body: Substmt.get());
8908 }
8909
8910 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8911 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8912 return StmtError();
8913
8914 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8915 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8916 ExprResult Op;
8917 if (Type->isOverloadableType())
8918 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8919 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8920 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8921 else
8922 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8923 if (Op.isInvalid())
8924 return StmtError();
8925
8926 switch (DCK) {
8927 case DefaultedComparisonKind::None:
8928 llvm_unreachable("not a defaulted comparison");
8929
8930 case DefaultedComparisonKind::Equal:
8931 // Per C++2a [class.eq]p2, each comparison is individually contextually
8932 // converted to bool.
8933 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8934 if (Op.isInvalid())
8935 return StmtError();
8936 return Op.get();
8937
8938 case DefaultedComparisonKind::ThreeWay: {
8939 // Per C++2a [class.spaceship]p3, form:
8940 // if (R cmp = static_cast<R>(op); cmp != 0)
8941 // return cmp;
8942 QualType R = FD->getReturnType();
8943 Op = buildStaticCastToR(E: Op.get());
8944 if (Op.isInvalid())
8945 return StmtError();
8946
8947 // R cmp = ...;
8948 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8949 VarDecl *VD =
8950 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8951 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8952 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8953 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8954
8955 // cmp != 0
8956 ExprResult VDRef = getDecl(VD);
8957 if (VDRef.isInvalid())
8958 return StmtError();
8959 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8960 Expr *Zero =
8961 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8962 ExprResult Comp;
8963 if (VDRef.get()->getType()->isOverloadableType())
8964 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8965 AllowRewrittenCandidates: true, DefaultedFn: FD);
8966 else
8967 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8968 if (Comp.isInvalid())
8969 return StmtError();
8970 Sema::ConditionResult Cond = S.ActOnCondition(
8971 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8972 if (Cond.isInvalid())
8973 return StmtError();
8974
8975 // return cmp;
8976 VDRef = getDecl(VD);
8977 if (VDRef.isInvalid())
8978 return StmtError();
8979 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8980 if (ReturnStmt.isInvalid())
8981 return StmtError();
8982
8983 // if (...)
8984 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8985 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8986 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8987 }
8988
8989 case DefaultedComparisonKind::NotEqual:
8990 case DefaultedComparisonKind::Relational:
8991 // C++2a [class.compare.secondary]p2:
8992 // Otherwise, the operator function yields x @ y.
8993 return Op.get();
8994 }
8995 llvm_unreachable("");
8996 }
8997
8998 /// Build "static_cast<R>(E)".
8999 ExprResult buildStaticCastToR(Expr *E) {
9000 QualType R = FD->getReturnType();
9001 assert(!R->isUndeducedType() && "type should have been deduced already");
9002
9003 // Don't bother forming a no-op cast in the common case.
9004 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
9005 return E;
9006 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
9007 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
9008 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
9009 }
9010};
9011}
9012
9013/// Perform the unqualified lookups that might be needed to form a defaulted
9014/// comparison function for the given operator.
9015static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
9016 UnresolvedSetImpl &Operators,
9017 OverloadedOperatorKind Op) {
9018 auto Lookup = [&](OverloadedOperatorKind OO) {
9019 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
9020 };
9021
9022 // Every defaulted operator looks up itself.
9023 Lookup(Op);
9024 // ... and the rewritten form of itself, if any.
9025 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
9026 Lookup(ExtraOp);
9027
9028 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9029 // synthesize a three-way comparison from '<' and '=='. In a dependent
9030 // context, we also need to look up '==' in case we implicitly declare a
9031 // defaulted 'operator=='.
9032 if (Op == OO_Spaceship) {
9033 Lookup(OO_ExclaimEqual);
9034 Lookup(OO_Less);
9035 Lookup(OO_EqualEqual);
9036 }
9037}
9038
9039bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
9040 DefaultedComparisonKind DCK) {
9041 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9042
9043 // Perform any unqualified lookups we're going to need to default this
9044 // function.
9045 if (S) {
9046 UnresolvedSet<32> Operators;
9047 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9048 Op: FD->getOverloadedOperator());
9049 FD->setDefaultedOrDeletedInfo(
9050 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9051 Context, Lookups: Operators.pairs(), FPFeatures: CurFPFeatureOverrides()));
9052 }
9053
9054 // C++2a [class.compare.default]p1:
9055 // A defaulted comparison operator function for some class C shall be a
9056 // non-template function declared in the member-specification of C that is
9057 // -- a non-static const non-volatile member of C having one parameter of
9058 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9059 // -- a friend of C having two parameters of type const C& or two
9060 // parameters of type C.
9061
9062 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9063 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9064 if (IsMethod) {
9065 auto *MD = cast<CXXMethodDecl>(Val: FD);
9066 assert(!MD->isStatic() && "comparison function cannot be a static member");
9067
9068 if (MD->getRefQualifier() == RQ_RValue) {
9069 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9070
9071 // Remove the ref qualifier to recover.
9072 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9073 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9074 EPI.RefQualifier = RQ_None;
9075 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9076 Args: FPT->getParamTypes(), EPI));
9077 }
9078
9079 // If we're out-of-class, this is the class we're comparing.
9080 if (!RD)
9081 RD = MD->getParent();
9082 QualType T = MD->getFunctionObjectParameterReferenceType();
9083 if (!T.getNonReferenceType().isConstQualified() &&
9084 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9085 SourceLocation Loc, InsertLoc;
9086 if (MD->isExplicitObjectMemberFunction()) {
9087 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9088 InsertLoc = getLocForEndOfToken(
9089 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9090 } else {
9091 Loc = MD->getLocation();
9092 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9093 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9094 }
9095 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9096 // corresponding defaulted 'operator<=>' already.
9097 if (!MD->isImplicit()) {
9098 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9099 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9100 }
9101
9102 // Add the 'const' to the type to recover.
9103 if (MD->isExplicitObjectMemberFunction()) {
9104 assert(T->isLValueReferenceType());
9105 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9106 T: T.getNonReferenceType().withConst()));
9107 } else {
9108 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9109 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9110 EPI.TypeQuals.addConst();
9111 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9112 Args: FPT->getParamTypes(), EPI));
9113 }
9114 }
9115
9116 if (MD->isVolatile()) {
9117 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9118
9119 // Remove the 'volatile' from the type to recover.
9120 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9121 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9122 EPI.TypeQuals.removeVolatile();
9123 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9124 Args: FPT->getParamTypes(), EPI));
9125 }
9126 }
9127
9128 if ((FD->getNumParams() -
9129 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9130 (IsMethod ? 1 : 2)) {
9131 // Let's not worry about using a variadic template pack here -- who would do
9132 // such a thing?
9133 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9134 << int(IsMethod) << int(DCK);
9135 return true;
9136 }
9137
9138 const ParmVarDecl *KnownParm = nullptr;
9139 for (const ParmVarDecl *Param : FD->parameters()) {
9140 QualType ParmTy = Param->getType();
9141 if (!KnownParm) {
9142 auto CTy = ParmTy;
9143 // Is it `T const &`?
9144 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9145 QualType ExpectedTy;
9146 if (RD)
9147 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9148 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9149 CTy = Ref->getPointeeType();
9150 if (RD)
9151 ExpectedTy.addConst();
9152 Ok = true;
9153 }
9154
9155 // Is T a class?
9156 if (RD) {
9157 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9158 } else {
9159 RD = CTy->getAsCXXRecordDecl();
9160 Ok &= RD != nullptr;
9161 }
9162
9163 if (Ok) {
9164 KnownParm = Param;
9165 } else {
9166 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9167 // corresponding defaulted 'operator<=>' already.
9168 if (!FD->isImplicit()) {
9169 if (RD) {
9170 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9171 QualType RefTy =
9172 Context.getLValueReferenceType(T: PlainTy.withConst());
9173 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9174 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9175 << Param->getSourceRange();
9176 } else {
9177 assert(!IsMethod && "should know expected type for method");
9178 Diag(Loc: FD->getLocation(),
9179 DiagID: diag::err_defaulted_comparison_param_unknown)
9180 << int(DCK) << ParmTy << Param->getSourceRange();
9181 }
9182 }
9183 return true;
9184 }
9185 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9186 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9187 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9188 << ParmTy << Param->getSourceRange();
9189 return true;
9190 }
9191 }
9192
9193 assert(RD && "must have determined class");
9194 if (IsMethod) {
9195 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9196 // In-class, must be a friend decl.
9197 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9198 } else {
9199 // Out of class, require the defaulted comparison to be a friend (of a
9200 // complete type, per CWG2547).
9201 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9202 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9203 Args: int(1)))
9204 return true;
9205
9206 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9207 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9208 })) {
9209 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9210 << int(DCK) << int(0) << RD;
9211 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9212 return true;
9213 }
9214 }
9215
9216 // C++2a [class.eq]p1, [class.rel]p1:
9217 // A [defaulted comparison other than <=>] shall have a declared return
9218 // type bool.
9219 if (DCK != DefaultedComparisonKind::ThreeWay &&
9220 !FD->getDeclaredReturnType()->isDependentType() &&
9221 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9222 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9223 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9224 << FD->getReturnTypeSourceRange();
9225 return true;
9226 }
9227 // C++2a [class.spaceship]p2 [P2002R0]:
9228 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9229 // R shall not contain a placeholder type.
9230 if (QualType RT = FD->getDeclaredReturnType();
9231 DCK == DefaultedComparisonKind::ThreeWay &&
9232 RT->getContainedDeducedType() &&
9233 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9234 RT->getContainedAutoType()->isConstrained())) {
9235 Diag(Loc: FD->getLocation(),
9236 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9237 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9238 << FD->getReturnTypeSourceRange();
9239 return true;
9240 }
9241
9242 // For a defaulted function in a dependent class, defer all remaining checks
9243 // until instantiation.
9244 if (RD->isDependentType())
9245 return false;
9246
9247 // Determine whether the function should be defined as deleted.
9248 DefaultedComparisonInfo Info =
9249 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9250
9251 bool First = FD == FD->getCanonicalDecl();
9252
9253 if (!First) {
9254 if (Info.Deleted) {
9255 // C++11 [dcl.fct.def.default]p4:
9256 // [For a] user-provided explicitly-defaulted function [...] if such a
9257 // function is implicitly defined as deleted, the program is ill-formed.
9258 //
9259 // This is really just a consequence of the general rule that you can
9260 // only delete a function on its first declaration.
9261 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9262 << FD->isImplicit() << (int)DCK;
9263 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9264 DefaultedComparisonAnalyzer::ExplainDeleted)
9265 .visit();
9266 return true;
9267 }
9268 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9269 // C++20 [class.compare.default]p1:
9270 // [...] A definition of a comparison operator as defaulted that appears
9271 // in a class shall be the first declaration of that function.
9272 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9273 << (int)DCK;
9274 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9275 DiagID: diag::note_previous_declaration);
9276 return true;
9277 }
9278 }
9279
9280 // If we want to delete the function, then do so; there's nothing else to
9281 // check in that case.
9282 if (Info.Deleted) {
9283 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9284 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9285 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9286 << (int)DCK;
9287 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9288 DefaultedComparisonAnalyzer::ExplainDeleted)
9289 .visit();
9290 if (FD->getDefaultLoc().isValid())
9291 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9292 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9293 }
9294 return false;
9295 }
9296
9297 // C++2a [class.spaceship]p2:
9298 // The return type is deduced as the common comparison type of R0, R1, ...
9299 if (DCK == DefaultedComparisonKind::ThreeWay &&
9300 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9301 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9302 if (RetLoc.isInvalid())
9303 RetLoc = FD->getBeginLoc();
9304 // FIXME: Should we really care whether we have the complete type and the
9305 // 'enumerator' constants here? A forward declaration seems sufficient.
9306 QualType Cat = CheckComparisonCategoryType(
9307 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9308 if (Cat.isNull())
9309 return true;
9310 Context.adjustDeducedFunctionResultType(
9311 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9312 }
9313
9314 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9315 // An explicitly-defaulted function that is not defined as deleted may be
9316 // declared constexpr or consteval only if it is constexpr-compatible.
9317 // C++2a [class.compare.default]p3 [P2002R0]:
9318 // A defaulted comparison function is constexpr-compatible if it satisfies
9319 // the requirements for a constexpr function [...]
9320 // The only relevant requirements are that the parameter and return types are
9321 // literal types. The remaining conditions are checked by the analyzer.
9322 //
9323 // We support P2448R2 in language modes earlier than C++23 as an extension.
9324 // The concept of constexpr-compatible was removed.
9325 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9326 // A function explicitly defaulted on its first declaration is implicitly
9327 // inline, and is implicitly constexpr if it is constexpr-suitable.
9328 // C++23 [dcl.constexpr]p3
9329 // A function is constexpr-suitable if
9330 // - it is not a coroutine, and
9331 // - if the function is a constructor or destructor, its class does not
9332 // have any virtual base classes.
9333 if (FD->isConstexpr()) {
9334 if (!getLangOpts().CPlusPlus23 &&
9335 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9336 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9337 !Info.Constexpr) {
9338 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9339 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9340 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9341 DefaultedComparisonAnalyzer::ExplainConstexpr)
9342 .visit();
9343 }
9344 }
9345
9346 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9347 // If a constexpr-compatible function is explicitly defaulted on its first
9348 // declaration, it is implicitly considered to be constexpr.
9349 // FIXME: Only applying this to the first declaration seems problematic, as
9350 // simple reorderings can affect the meaning of the program.
9351 if (First && !FD->isConstexpr() && Info.Constexpr)
9352 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9353
9354 // C++2a [except.spec]p3:
9355 // If a declaration of a function does not have a noexcept-specifier
9356 // [and] is defaulted on its first declaration, [...] the exception
9357 // specification is as specified below
9358 if (FD->getExceptionSpecType() == EST_None) {
9359 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9360 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9361 EPI.ExceptionSpec.Type = EST_Unevaluated;
9362 EPI.ExceptionSpec.SourceDecl = FD;
9363 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9364 Args: FPT->getParamTypes(), EPI));
9365 }
9366
9367 return false;
9368}
9369
9370void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9371 FunctionDecl *Spaceship) {
9372 Sema::CodeSynthesisContext Ctx;
9373 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9374 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9375 Ctx.Entity = Spaceship;
9376 pushCodeSynthesisContext(Ctx);
9377
9378 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9379 EqualEqual->setImplicit();
9380
9381 popCodeSynthesisContext();
9382}
9383
9384void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9385 DefaultedComparisonKind DCK) {
9386 assert(FD->isDefaulted() && !FD->isDeleted() &&
9387 !FD->doesThisDeclarationHaveABody());
9388 if (FD->willHaveBody() || FD->isInvalidDecl())
9389 return;
9390
9391 SynthesizedFunctionScope Scope(*this, FD);
9392
9393 // Add a context note for diagnostics produced after this point.
9394 Scope.addContextNote(UseLoc);
9395
9396 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9397
9398 {
9399 // Build and set up the function body.
9400 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9401 // the type of the class being compared.
9402 auto PT = FD->getParamDecl(i: 0)->getType();
9403 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9404 SourceLocation BodyLoc =
9405 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9406 StmtResult Body =
9407 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9408 if (Body.isInvalid()) {
9409 FD->setInvalidDecl();
9410 return;
9411 }
9412 FD->setBody(Body.get());
9413 FD->markUsed(C&: Context);
9414 }
9415
9416 // The exception specification is needed because we are defining the
9417 // function. Note that this will reuse the body we just built.
9418 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9419
9420 if (ASTMutationListener *L = getASTMutationListener())
9421 L->CompletedImplicitDefinition(D: FD);
9422}
9423
9424static Sema::ImplicitExceptionSpecification
9425ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9426 FunctionDecl *FD,
9427 Sema::DefaultedComparisonKind DCK) {
9428 ComputingExceptionSpec CES(S, FD, Loc);
9429 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9430
9431 if (FD->isInvalidDecl())
9432 return ExceptSpec;
9433
9434 // The common case is that we just defined the comparison function. In that
9435 // case, just look at whether the body can throw.
9436 if (FD->hasBody()) {
9437 ExceptSpec.CalledStmt(S: FD->getBody());
9438 } else {
9439 // Otherwise, build a body so we can check it. This should ideally only
9440 // happen when we're not actually marking the function referenced. (This is
9441 // only really important for efficiency: we don't want to build and throw
9442 // away bodies for comparison functions more than we strictly need to.)
9443
9444 // Pretend to synthesize the function body in an unevaluated context.
9445 // Note that we can't actually just go ahead and define the function here:
9446 // we are not permitted to mark its callees as referenced.
9447 Sema::SynthesizedFunctionScope Scope(S, FD);
9448 EnterExpressionEvaluationContext Context(
9449 S, Sema::ExpressionEvaluationContext::Unevaluated);
9450
9451 CXXRecordDecl *RD =
9452 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9453 ? FD->getDeclContext()
9454 : FD->getLexicalDeclContext());
9455 SourceLocation BodyLoc =
9456 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9457 StmtResult Body =
9458 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9459 if (!Body.isInvalid())
9460 ExceptSpec.CalledStmt(S: Body.get());
9461
9462 // FIXME: Can we hold onto this body and just transform it to potentially
9463 // evaluated when we're asked to define the function rather than rebuilding
9464 // it? Either that, or we should only build the bits of the body that we
9465 // need (the expressions, not the statements).
9466 }
9467
9468 return ExceptSpec;
9469}
9470
9471void Sema::CheckDelayedMemberExceptionSpecs() {
9472 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9473 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9474
9475 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9476 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9477
9478 // Perform any deferred checking of exception specifications for virtual
9479 // destructors.
9480 for (auto &Check : Overriding)
9481 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9482
9483 // Perform any deferred checking of exception specifications for befriended
9484 // special members.
9485 for (auto &Check : Equivalent)
9486 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9487}
9488
9489namespace {
9490/// CRTP base class for visiting operations performed by a special member
9491/// function (or inherited constructor).
9492template<typename Derived>
9493struct SpecialMemberVisitor {
9494 Sema &S;
9495 CXXMethodDecl *MD;
9496 CXXSpecialMemberKind CSM;
9497 Sema::InheritedConstructorInfo *ICI;
9498
9499 // Properties of the special member, computed for convenience.
9500 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9501
9502 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9503 Sema::InheritedConstructorInfo *ICI)
9504 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9505 switch (CSM) {
9506 case CXXSpecialMemberKind::DefaultConstructor:
9507 case CXXSpecialMemberKind::CopyConstructor:
9508 case CXXSpecialMemberKind::MoveConstructor:
9509 IsConstructor = true;
9510 break;
9511 case CXXSpecialMemberKind::CopyAssignment:
9512 case CXXSpecialMemberKind::MoveAssignment:
9513 IsAssignment = true;
9514 break;
9515 case CXXSpecialMemberKind::Destructor:
9516 break;
9517 case CXXSpecialMemberKind::Invalid:
9518 llvm_unreachable("invalid special member kind");
9519 }
9520
9521 if (MD->getNumExplicitParams()) {
9522 if (const ReferenceType *RT =
9523 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9524 ConstArg = RT->getPointeeType().isConstQualified();
9525 }
9526 }
9527
9528 Derived &getDerived() { return static_cast<Derived&>(*this); }
9529
9530 /// Is this a "move" special member?
9531 bool isMove() const {
9532 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9533 CSM == CXXSpecialMemberKind::MoveAssignment;
9534 }
9535
9536 /// Look up the corresponding special member in the given class.
9537 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9538 unsigned Quals, bool IsMutable) {
9539 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9540 ConstRHS: ConstArg && !IsMutable);
9541 }
9542
9543 /// Look up the constructor for the specified base class to see if it's
9544 /// overridden due to this being an inherited constructor.
9545 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9546 if (!ICI)
9547 return {};
9548 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9549 auto *BaseCtor =
9550 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9551 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9552 return MD;
9553 return {};
9554 }
9555
9556 /// A base or member subobject.
9557 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9558
9559 /// Get the location to use for a subobject in diagnostics.
9560 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9561 // FIXME: For an indirect virtual base, the direct base leading to
9562 // the indirect virtual base would be a more useful choice.
9563 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9564 return B->getBaseTypeLoc();
9565 else
9566 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9567 }
9568
9569 enum BasesToVisit {
9570 /// Visit all non-virtual (direct) bases.
9571 VisitNonVirtualBases,
9572 /// Visit all direct bases, virtual or not.
9573 VisitDirectBases,
9574 /// Visit all non-virtual bases, and all virtual bases if the class
9575 /// is not abstract.
9576 VisitPotentiallyConstructedBases,
9577 /// Visit all direct or virtual bases.
9578 VisitAllBases
9579 };
9580
9581 // Visit the bases and members of the class.
9582 bool visit(BasesToVisit Bases) {
9583 CXXRecordDecl *RD = MD->getParent();
9584
9585 if (Bases == VisitPotentiallyConstructedBases)
9586 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9587
9588 for (auto &B : RD->bases())
9589 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9590 getDerived().visitBase(&B))
9591 return true;
9592
9593 if (Bases == VisitAllBases)
9594 for (auto &B : RD->vbases())
9595 if (getDerived().visitBase(&B))
9596 return true;
9597
9598 for (auto *F : RD->fields())
9599 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9600 getDerived().visitField(F))
9601 return true;
9602
9603 return false;
9604 }
9605};
9606}
9607
9608namespace {
9609struct SpecialMemberDeletionInfo
9610 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9611 bool Diagnose;
9612
9613 SourceLocation Loc;
9614
9615 bool AllFieldsAreConst;
9616
9617 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9618 CXXSpecialMemberKind CSM,
9619 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9620 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9621 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9622
9623 bool inUnion() const { return MD->getParent()->isUnion(); }
9624
9625 CXXSpecialMemberKind getEffectiveCSM() {
9626 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9627 }
9628
9629 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9630
9631 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9632
9633 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9634 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9635
9636 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9637 bool shouldDeleteForField(FieldDecl *FD);
9638 bool shouldDeleteForAllConstMembers();
9639
9640 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9641 unsigned Quals);
9642 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9643 Sema::SpecialMemberOverloadResult SMOR,
9644 bool IsDtorCallInCtor);
9645
9646 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9647};
9648}
9649
9650/// Is the given special member inaccessible when used on the given
9651/// sub-object.
9652bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9653 CXXMethodDecl *target) {
9654 /// If we're operating on a base class, the object type is the
9655 /// type of this special member.
9656 CanQualType objectTy;
9657 AccessSpecifier access = target->getAccess();
9658 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9659 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9660 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9661
9662 // If we're operating on a field, the object type is the type of the field.
9663 } else {
9664 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9665 }
9666
9667 return S.isMemberAccessibleForDeletion(
9668 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9669}
9670
9671/// Check whether we should delete a special member due to the implicit
9672/// definition containing a call to a special member of a subobject.
9673bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9674 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9675 bool IsDtorCallInCtor) {
9676 CXXMethodDecl *Decl = SMOR.getMethod();
9677 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9678
9679 enum {
9680 NotSet = -1,
9681 NoDecl,
9682 DeletedDecl,
9683 MultipleDecl,
9684 InaccessibleDecl,
9685 NonTrivialDecl
9686 } DiagKind = NotSet;
9687
9688 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9689 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9690 Field->getParent()->isUnion()) {
9691 // [class.default.ctor]p2:
9692 // A defaulted default constructor for class X is defined as deleted if
9693 // - X is a union that has a variant member with a non-trivial default
9694 // constructor and no variant member of X has a default member
9695 // initializer
9696 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9697 if (RD->hasInClassInitializer())
9698 return false;
9699 }
9700 DiagKind = !Decl ? NoDecl : DeletedDecl;
9701 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9702 DiagKind = MultipleDecl;
9703 else if (!isAccessible(Subobj, target: Decl))
9704 DiagKind = InaccessibleDecl;
9705 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9706 !Decl->isTrivial()) {
9707 // A member of a union must have a trivial corresponding special member.
9708 // As a weird special case, a destructor call from a union's constructor
9709 // must be accessible and non-deleted, but need not be trivial. Such a
9710 // destructor is never actually called, but is semantically checked as
9711 // if it were.
9712 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9713 // [class.default.ctor]p2:
9714 // A defaulted default constructor for class X is defined as deleted if
9715 // - X is a union that has a variant member with a non-trivial default
9716 // constructor and no variant member of X has a default member
9717 // initializer
9718 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9719 if (!RD->hasInClassInitializer())
9720 DiagKind = NonTrivialDecl;
9721 } else {
9722 DiagKind = NonTrivialDecl;
9723 }
9724 }
9725
9726 if (DiagKind == NotSet)
9727 return false;
9728
9729 if (Diagnose) {
9730 if (Field) {
9731 S.Diag(Loc: Field->getLocation(),
9732 DiagID: diag::note_deleted_special_member_class_subobject)
9733 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9734 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9735 } else {
9736 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9737 S.Diag(Loc: Base->getBeginLoc(),
9738 DiagID: diag::note_deleted_special_member_class_subobject)
9739 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9740 << Base->getType() << DiagKind << IsDtorCallInCtor
9741 << /*IsObjCPtr*/ false;
9742 }
9743
9744 if (DiagKind == DeletedDecl)
9745 S.NoteDeletedFunction(FD: Decl);
9746 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9747 }
9748
9749 return true;
9750}
9751
9752/// Check whether we should delete a special member function due to having a
9753/// direct or virtual base class or non-static data member of class type M.
9754bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9755 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9756 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9757 bool IsMutable = Field && Field->isMutable();
9758
9759 // C++11 [class.ctor]p5:
9760 // -- any direct or virtual base class, or non-static data member with no
9761 // brace-or-equal-initializer, has class type M (or array thereof) and
9762 // either M has no default constructor or overload resolution as applied
9763 // to M's default constructor results in an ambiguity or in a function
9764 // that is deleted or inaccessible
9765 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9766 // -- a direct or virtual base class B that cannot be copied/moved because
9767 // overload resolution, as applied to B's corresponding special member,
9768 // results in an ambiguity or a function that is deleted or inaccessible
9769 // from the defaulted special member
9770 // C++11 [class.dtor]p5:
9771 // -- any direct or virtual base class [...] has a type with a destructor
9772 // that is deleted or inaccessible
9773 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9774 Field->hasInClassInitializer()) &&
9775 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9776 IsDtorCallInCtor: false))
9777 return true;
9778
9779 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9780 // -- any direct or virtual base class or non-static data member has a
9781 // type with a destructor that is deleted or inaccessible
9782 if (IsConstructor) {
9783 Sema::SpecialMemberOverloadResult SMOR =
9784 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9785 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9786 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9787 return true;
9788 }
9789
9790 return false;
9791}
9792
9793bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9794 FieldDecl *FD, QualType FieldType) {
9795 // The defaulted special functions are defined as deleted if this is a variant
9796 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9797 // type under ARC.
9798 if (!FieldType.hasNonTrivialObjCLifetime())
9799 return false;
9800
9801 // Don't make the defaulted default constructor defined as deleted if the
9802 // member has an in-class initializer.
9803 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9804 FD->hasInClassInitializer())
9805 return false;
9806
9807 if (Diagnose) {
9808 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9809 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9810 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9811 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9812 }
9813
9814 return true;
9815}
9816
9817bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9818 const FieldDecl *FD) {
9819 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9820 // Copy/move constructors/assignment operators are deleted if the field has an
9821 // address-discriminated ptrauth qualifier.
9822 PointerAuthQualifier Q = FieldType.getPointerAuth();
9823
9824 if (!Q || !Q.isAddressDiscriminated())
9825 return false;
9826
9827 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9828 CSM == CXXSpecialMemberKind::Destructor)
9829 return false;
9830
9831 if (Diagnose) {
9832 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9833 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9834 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9835 << /*IsDtorCallInCtor*/ false << 2;
9836 }
9837
9838 return true;
9839}
9840
9841/// Check whether we should delete a special member function due to the class
9842/// having a particular direct or virtual base class.
9843bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9844 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9845 // If program is correct, BaseClass cannot be null, but if it is, the error
9846 // must be reported elsewhere.
9847 if (!BaseClass)
9848 return false;
9849 // If we have an inheriting constructor, check whether we're calling an
9850 // inherited constructor instead of a default constructor.
9851 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9852 if (auto *BaseCtor = SMOR.getMethod()) {
9853 // Note that we do not check access along this path; other than that,
9854 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9855 // FIXME: Check that the base has a usable destructor! Sink this into
9856 // shouldDeleteForClassSubobject.
9857 if (BaseCtor->isDeleted() && Diagnose) {
9858 S.Diag(Loc: Base->getBeginLoc(),
9859 DiagID: diag::note_deleted_special_member_class_subobject)
9860 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9861 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9862 << /*IsObjCPtr*/ false;
9863 S.NoteDeletedFunction(FD: BaseCtor);
9864 }
9865 return BaseCtor->isDeleted();
9866 }
9867 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9868}
9869
9870/// Check whether we should delete a special member function due to the class
9871/// having a particular non-static data member.
9872bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9873 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9874 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9875
9876 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9877 return true;
9878
9879 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9880 return true;
9881
9882 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9883 // For a default constructor, all references must be initialized in-class
9884 // and, if a union, it must have a non-const member.
9885 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9886 if (Diagnose)
9887 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9888 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9889 return true;
9890 }
9891 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9892 // data member of const-qualified type (or array thereof) with no
9893 // brace-or-equal-initializer is not const-default-constructible.
9894 if (!inUnion() && FieldType.isConstQualified() &&
9895 !FD->hasInClassInitializer() &&
9896 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9897 if (Diagnose)
9898 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9899 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9900 return true;
9901 }
9902
9903 if (inUnion() && !FieldType.isConstQualified())
9904 AllFieldsAreConst = false;
9905 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9906 // For a copy constructor, data members must not be of rvalue reference
9907 // type.
9908 if (FieldType->isRValueReferenceType()) {
9909 if (Diagnose)
9910 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9911 << MD->getParent() << FD << FieldType;
9912 return true;
9913 }
9914 } else if (IsAssignment) {
9915 // For an assignment operator, data members must not be of reference type.
9916 if (FieldType->isReferenceType()) {
9917 if (Diagnose)
9918 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9919 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9920 return true;
9921 }
9922 if (!FieldRecord && FieldType.isConstQualified()) {
9923 // C++11 [class.copy]p23:
9924 // -- a non-static data member of const non-class type (or array thereof)
9925 if (Diagnose)
9926 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9927 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9928 return true;
9929 }
9930 }
9931
9932 if (FieldRecord) {
9933 // Some additional restrictions exist on the variant members.
9934 if (!inUnion() && FieldRecord->isUnion() &&
9935 FieldRecord->isAnonymousStructOrUnion()) {
9936 bool AllVariantFieldsAreConst = true;
9937
9938 // FIXME: Handle anonymous unions declared within anonymous unions.
9939 for (auto *UI : FieldRecord->fields()) {
9940 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9941
9942 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9943 return true;
9944
9945 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9946 return true;
9947
9948 if (!UnionFieldType.isConstQualified())
9949 AllVariantFieldsAreConst = false;
9950
9951 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9952 if (UnionFieldRecord &&
9953 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9954 Quals: UnionFieldType.getCVRQualifiers()))
9955 return true;
9956 }
9957
9958 // At least one member in each anonymous union must be non-const
9959 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9960 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9961 if (Diagnose)
9962 S.Diag(Loc: FieldRecord->getLocation(),
9963 DiagID: diag::note_deleted_default_ctor_all_const)
9964 << !!ICI << MD->getParent() << /*anonymous union*/1;
9965 return true;
9966 }
9967
9968 // Don't check the implicit member of the anonymous union type.
9969 // This is technically non-conformant but supported, and we have a
9970 // diagnostic for this elsewhere.
9971 return false;
9972 }
9973
9974 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9975 Quals: FieldType.getCVRQualifiers()))
9976 return true;
9977 }
9978
9979 return false;
9980}
9981
9982/// C++11 [class.ctor] p5:
9983/// A defaulted default constructor for a class X is defined as deleted if
9984/// X is a union and all of its variant members are of const-qualified type.
9985bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9986 // This is a silly definition, because it gives an empty union a deleted
9987 // default constructor. Don't do that.
9988 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9989 AllFieldsAreConst) {
9990 bool AnyFields = false;
9991 for (auto *F : MD->getParent()->fields())
9992 if ((AnyFields = !F->isUnnamedBitField()))
9993 break;
9994 if (!AnyFields)
9995 return false;
9996 if (Diagnose)
9997 S.Diag(Loc: MD->getParent()->getLocation(),
9998 DiagID: diag::note_deleted_default_ctor_all_const)
9999 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10000 return true;
10001 }
10002 return false;
10003}
10004
10005/// Determine whether a defaulted special member function should be defined as
10006/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10007/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10008bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
10009 CXXSpecialMemberKind CSM,
10010 InheritedConstructorInfo *ICI,
10011 bool Diagnose) {
10012 if (MD->isInvalidDecl())
10013 return false;
10014 CXXRecordDecl *RD = MD->getParent();
10015 assert(!RD->isDependentType() && "do deletion after instantiation");
10016 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10017 RD->isInvalidDecl())
10018 return false;
10019
10020 // C++11 [expr.lambda.prim]p19:
10021 // The closure type associated with a lambda-expression has a
10022 // deleted (8.4.3) default constructor and a deleted copy
10023 // assignment operator.
10024 // C++2a adds back these operators if the lambda has no lambda-capture.
10025 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
10026 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10027 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10028 if (Diagnose)
10029 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
10030 return true;
10031 }
10032
10033 // C++11 [class.copy]p7, p18:
10034 // If the class definition declares a move constructor or move assignment
10035 // operator, an implicitly declared copy constructor or copy assignment
10036 // operator is defined as deleted.
10037 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
10038 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10039 CXXMethodDecl *UserDeclaredMove = nullptr;
10040
10041 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10042 // deletion of the corresponding copy operation, not both copy operations.
10043 // MSVC 2015 has adopted the standards conforming behavior.
10044 bool DeletesOnlyMatchingCopy =
10045 getLangOpts().MSVCCompat &&
10046 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
10047
10048 if (RD->hasUserDeclaredMoveConstructor() &&
10049 (!DeletesOnlyMatchingCopy ||
10050 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10051 if (!Diagnose) return true;
10052
10053 // Find any user-declared move constructor.
10054 for (auto *I : RD->ctors()) {
10055 if (I->isMoveConstructor()) {
10056 UserDeclaredMove = I;
10057 break;
10058 }
10059 }
10060 assert(UserDeclaredMove);
10061 } else if (RD->hasUserDeclaredMoveAssignment() &&
10062 (!DeletesOnlyMatchingCopy ||
10063 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10064 if (!Diagnose) return true;
10065
10066 // Find any user-declared move assignment operator.
10067 for (auto *I : RD->methods()) {
10068 if (I->isMoveAssignmentOperator()) {
10069 UserDeclaredMove = I;
10070 break;
10071 }
10072 }
10073 assert(UserDeclaredMove);
10074 }
10075
10076 if (UserDeclaredMove) {
10077 Diag(Loc: UserDeclaredMove->getLocation(),
10078 DiagID: diag::note_deleted_copy_user_declared_move)
10079 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10080 << UserDeclaredMove->isMoveAssignmentOperator();
10081 return true;
10082 }
10083 }
10084
10085 // Do access control from the special member function
10086 ContextRAII MethodContext(*this, MD);
10087
10088 // C++11 [class.dtor]p5:
10089 // -- for a virtual destructor, lookup of the non-array deallocation function
10090 // results in an ambiguity or in a function that is deleted or inaccessible
10091 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10092 FunctionDecl *OperatorDelete = nullptr;
10093 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10094 DeclarationName Name =
10095 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10096 ImplicitDeallocationParameters IDP = {
10097 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10098 AlignedAllocationMode::No, SizedDeallocationMode::No};
10099 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10100 Operator&: OperatorDelete, IDP,
10101 /*Diagnose=*/false)) {
10102 if (Diagnose)
10103 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10104 return true;
10105 }
10106 }
10107
10108 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10109
10110 // Per DR1611, do not consider virtual bases of constructors of abstract
10111 // classes, since we are not going to construct them.
10112 // Per DR1658, do not consider virtual bases of destructors of abstract
10113 // classes either.
10114 // Per DR2180, for assignment operators we only assign (and thus only
10115 // consider) direct bases.
10116 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10117 : SMI.VisitPotentiallyConstructedBases))
10118 return true;
10119
10120 if (SMI.shouldDeleteForAllConstMembers())
10121 return true;
10122
10123 if (getLangOpts().CUDA) {
10124 // We should delete the special member in CUDA mode if target inference
10125 // failed.
10126 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10127 // is treated as certain special member, which may not reflect what special
10128 // member MD really is. However inferTargetForImplicitSpecialMember
10129 // expects CSM to match MD, therefore recalculate CSM.
10130 assert(ICI || CSM == getSpecialMember(MD));
10131 auto RealCSM = CSM;
10132 if (ICI)
10133 RealCSM = getSpecialMember(MD);
10134
10135 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10136 ConstRHS: SMI.ConstArg, Diagnose);
10137 }
10138
10139 return false;
10140}
10141
10142void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10143 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
10144 assert(DFK && "not a defaultable function");
10145 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10146
10147 if (DFK.isSpecialMember()) {
10148 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10149 ICI: nullptr, /*Diagnose=*/true);
10150 } else {
10151 DefaultedComparisonAnalyzer(
10152 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10153 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10154 .visit();
10155 }
10156}
10157
10158/// Perform lookup for a special member of the specified kind, and determine
10159/// whether it is trivial. If the triviality can be determined without the
10160/// lookup, skip it. This is intended for use when determining whether a
10161/// special member of a containing object is trivial, and thus does not ever
10162/// perform overload resolution for default constructors.
10163///
10164/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10165/// member that was most likely to be intended to be trivial, if any.
10166///
10167/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10168/// determine whether the special member is trivial.
10169static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10170 CXXSpecialMemberKind CSM, unsigned Quals,
10171 bool ConstRHS, TrivialABIHandling TAH,
10172 CXXMethodDecl **Selected) {
10173 if (Selected)
10174 *Selected = nullptr;
10175
10176 switch (CSM) {
10177 case CXXSpecialMemberKind::Invalid:
10178 llvm_unreachable("not a special member");
10179
10180 case CXXSpecialMemberKind::DefaultConstructor:
10181 // C++11 [class.ctor]p5:
10182 // A default constructor is trivial if:
10183 // - all the [direct subobjects] have trivial default constructors
10184 //
10185 // Note, no overload resolution is performed in this case.
10186 if (RD->hasTrivialDefaultConstructor())
10187 return true;
10188
10189 if (Selected) {
10190 // If there's a default constructor which could have been trivial, dig it
10191 // out. Otherwise, if there's any user-provided default constructor, point
10192 // to that as an example of why there's not a trivial one.
10193 CXXConstructorDecl *DefCtor = nullptr;
10194 if (RD->needsImplicitDefaultConstructor())
10195 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10196 for (auto *CI : RD->ctors()) {
10197 if (!CI->isDefaultConstructor())
10198 continue;
10199 DefCtor = CI;
10200 if (!DefCtor->isUserProvided())
10201 break;
10202 }
10203
10204 *Selected = DefCtor;
10205 }
10206
10207 return false;
10208
10209 case CXXSpecialMemberKind::Destructor:
10210 // C++11 [class.dtor]p5:
10211 // A destructor is trivial if:
10212 // - all the direct [subobjects] have trivial destructors
10213 if (RD->hasTrivialDestructor() ||
10214 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10215 RD->hasTrivialDestructorForCall()))
10216 return true;
10217
10218 if (Selected) {
10219 if (RD->needsImplicitDestructor())
10220 S.DeclareImplicitDestructor(ClassDecl: RD);
10221 *Selected = RD->getDestructor();
10222 }
10223
10224 return false;
10225
10226 case CXXSpecialMemberKind::CopyConstructor:
10227 // C++11 [class.copy]p12:
10228 // A copy constructor is trivial if:
10229 // - the constructor selected to copy each direct [subobject] is trivial
10230 if (RD->hasTrivialCopyConstructor() ||
10231 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10232 RD->hasTrivialCopyConstructorForCall())) {
10233 if (Quals == Qualifiers::Const)
10234 // We must either select the trivial copy constructor or reach an
10235 // ambiguity; no need to actually perform overload resolution.
10236 return true;
10237 } else if (!Selected) {
10238 return false;
10239 }
10240 // In C++98, we are not supposed to perform overload resolution here, but we
10241 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10242 // cases like B as having a non-trivial copy constructor:
10243 // struct A { template<typename T> A(T&); };
10244 // struct B { mutable A a; };
10245 goto NeedOverloadResolution;
10246
10247 case CXXSpecialMemberKind::CopyAssignment:
10248 // C++11 [class.copy]p25:
10249 // A copy assignment operator is trivial if:
10250 // - the assignment operator selected to copy each direct [subobject] is
10251 // trivial
10252 if (RD->hasTrivialCopyAssignment()) {
10253 if (Quals == Qualifiers::Const)
10254 return true;
10255 } else if (!Selected) {
10256 return false;
10257 }
10258 // In C++98, we are not supposed to perform overload resolution here, but we
10259 // treat that as a language defect.
10260 goto NeedOverloadResolution;
10261
10262 case CXXSpecialMemberKind::MoveConstructor:
10263 case CXXSpecialMemberKind::MoveAssignment:
10264 NeedOverloadResolution:
10265 Sema::SpecialMemberOverloadResult SMOR =
10266 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10267
10268 // The standard doesn't describe how to behave if the lookup is ambiguous.
10269 // We treat it as not making the member non-trivial, just like the standard
10270 // mandates for the default constructor. This should rarely matter, because
10271 // the member will also be deleted.
10272 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10273 return true;
10274
10275 if (!SMOR.getMethod()) {
10276 assert(SMOR.getKind() ==
10277 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10278 return false;
10279 }
10280
10281 // We deliberately don't check if we found a deleted special member. We're
10282 // not supposed to!
10283 if (Selected)
10284 *Selected = SMOR.getMethod();
10285
10286 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10287 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10288 CSM == CXXSpecialMemberKind::MoveConstructor))
10289 return SMOR.getMethod()->isTrivialForCall();
10290 return SMOR.getMethod()->isTrivial();
10291 }
10292
10293 llvm_unreachable("unknown special method kind");
10294}
10295
10296static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10297 for (auto *CI : RD->ctors())
10298 if (!CI->isImplicit())
10299 return CI;
10300
10301 // Look for constructor templates.
10302 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10303 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10304 if (CXXConstructorDecl *CD =
10305 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10306 return CD;
10307 }
10308
10309 return nullptr;
10310}
10311
10312/// The kind of subobject we are checking for triviality. The values of this
10313/// enumeration are used in diagnostics.
10314enum TrivialSubobjectKind {
10315 /// The subobject is a base class.
10316 TSK_BaseClass,
10317 /// The subobject is a non-static data member.
10318 TSK_Field,
10319 /// The object is actually the complete object.
10320 TSK_CompleteObject
10321};
10322
10323/// Check whether the special member selected for a given type would be trivial.
10324static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10325 QualType SubType, bool ConstRHS,
10326 CXXSpecialMemberKind CSM,
10327 TrivialSubobjectKind Kind,
10328 TrivialABIHandling TAH, bool Diagnose) {
10329 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10330 if (!SubRD)
10331 return true;
10332
10333 CXXMethodDecl *Selected;
10334 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10335 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10336 return true;
10337
10338 if (Diagnose) {
10339 if (ConstRHS)
10340 SubType.addConst();
10341
10342 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10343 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10344 << Kind << SubType.getUnqualifiedType();
10345 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10346 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10347 } else if (!Selected)
10348 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10349 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10350 else if (Selected->isUserProvided()) {
10351 if (Kind == TSK_CompleteObject)
10352 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10353 << Kind << SubType.getUnqualifiedType() << CSM;
10354 else {
10355 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10356 << Kind << SubType.getUnqualifiedType() << CSM;
10357 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10358 }
10359 } else {
10360 if (Kind != TSK_CompleteObject)
10361 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10362 << Kind << SubType.getUnqualifiedType() << CSM;
10363
10364 // Explain why the defaulted or deleted special member isn't trivial.
10365 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10366 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10367 }
10368 }
10369
10370 return false;
10371}
10372
10373/// Check whether the members of a class type allow a special member to be
10374/// trivial.
10375static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10376 CXXSpecialMemberKind CSM, bool ConstArg,
10377 TrivialABIHandling TAH, bool Diagnose) {
10378 for (const auto *FI : RD->fields()) {
10379 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10380 continue;
10381
10382 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10383
10384 // Pretend anonymous struct or union members are members of this class.
10385 if (FI->isAnonymousStructOrUnion()) {
10386 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10387 CSM, ConstArg, TAH, Diagnose))
10388 return false;
10389 continue;
10390 }
10391
10392 // C++11 [class.ctor]p5:
10393 // A default constructor is trivial if [...]
10394 // -- no non-static data member of its class has a
10395 // brace-or-equal-initializer
10396 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10397 FI->hasInClassInitializer()) {
10398 if (Diagnose)
10399 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10400 << FI;
10401 return false;
10402 }
10403
10404 // Objective C ARC 4.3.5:
10405 // [...] nontrivally ownership-qualified types are [...] not trivially
10406 // default constructible, copy constructible, move constructible, copy
10407 // assignable, move assignable, or destructible [...]
10408 if (FieldType.hasNonTrivialObjCLifetime()) {
10409 if (Diagnose)
10410 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10411 << RD << FieldType.getObjCLifetime();
10412 return false;
10413 }
10414
10415 bool ConstRHS = ConstArg && !FI->isMutable();
10416 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10417 CSM, Kind: TSK_Field, TAH, Diagnose))
10418 return false;
10419 }
10420
10421 return true;
10422}
10423
10424void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10425 CXXSpecialMemberKind CSM) {
10426 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10427
10428 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10429 CSM == CXXSpecialMemberKind::CopyAssignment);
10430 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10431 Kind: TSK_CompleteObject,
10432 TAH: TrivialABIHandling::IgnoreTrivialABI,
10433 /*Diagnose*/ true);
10434}
10435
10436bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10437 TrivialABIHandling TAH, bool Diagnose) {
10438 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10439 "not special enough");
10440
10441 CXXRecordDecl *RD = MD->getParent();
10442
10443 bool ConstArg = false;
10444
10445 // C++11 [class.copy]p12, p25: [DR1593]
10446 // A [special member] is trivial if [...] its parameter-type-list is
10447 // equivalent to the parameter-type-list of an implicit declaration [...]
10448 switch (CSM) {
10449 case CXXSpecialMemberKind::DefaultConstructor:
10450 case CXXSpecialMemberKind::Destructor:
10451 // Trivial default constructors and destructors cannot have parameters.
10452 break;
10453
10454 case CXXSpecialMemberKind::CopyConstructor:
10455 case CXXSpecialMemberKind::CopyAssignment: {
10456 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10457 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10458
10459 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10460 // if they are not user-provided and their parameter-type-list is equivalent
10461 // to the parameter-type-list of an implicit declaration. This maintains the
10462 // behavior before dr2171 was implemented.
10463 //
10464 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10465 // trivial, if they are not user-provided, regardless of the qualifiers on
10466 // the reference type.
10467 const bool ClangABICompat14 =
10468 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver14);
10469 if (!RT ||
10470 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10471 ClangABICompat14)) {
10472 if (Diagnose)
10473 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10474 << Param0->getSourceRange() << Param0->getType()
10475 << Context.getLValueReferenceType(
10476 T: Context.getCanonicalTagType(TD: RD).withConst());
10477 return false;
10478 }
10479
10480 ConstArg = RT->getPointeeType().isConstQualified();
10481 break;
10482 }
10483
10484 case CXXSpecialMemberKind::MoveConstructor:
10485 case CXXSpecialMemberKind::MoveAssignment: {
10486 // Trivial move operations always have non-cv-qualified parameters.
10487 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10488 const RValueReferenceType *RT =
10489 Param0->getType()->getAs<RValueReferenceType>();
10490 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10491 if (Diagnose)
10492 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10493 << Param0->getSourceRange() << Param0->getType()
10494 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10495 return false;
10496 }
10497 break;
10498 }
10499
10500 case CXXSpecialMemberKind::Invalid:
10501 llvm_unreachable("not a special member");
10502 }
10503
10504 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10505 if (Diagnose)
10506 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10507 DiagID: diag::note_nontrivial_default_arg)
10508 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10509 return false;
10510 }
10511 if (MD->isVariadic()) {
10512 if (Diagnose)
10513 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10514 return false;
10515 }
10516
10517 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10518 // A copy/move [constructor or assignment operator] is trivial if
10519 // -- the [member] selected to copy/move each direct base class subobject
10520 // is trivial
10521 //
10522 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10523 // A [default constructor or destructor] is trivial if
10524 // -- all the direct base classes have trivial [default constructors or
10525 // destructors]
10526 for (const auto &BI : RD->bases())
10527 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10528 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10529 return false;
10530
10531 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10532 // A copy/move [constructor or assignment operator] for a class X is
10533 // trivial if
10534 // -- for each non-static data member of X that is of class type (or array
10535 // thereof), the constructor selected to copy/move that member is
10536 // trivial
10537 //
10538 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10539 // A [default constructor or destructor] is trivial if
10540 // -- for all of the non-static data members of its class that are of class
10541 // type (or array thereof), each such class has a trivial [default
10542 // constructor or destructor]
10543 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10544 return false;
10545
10546 // C++11 [class.dtor]p5:
10547 // A destructor is trivial if [...]
10548 // -- the destructor is not virtual
10549 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10550 if (Diagnose)
10551 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10552 return false;
10553 }
10554
10555 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10556 // A [special member] for class X is trivial if [...]
10557 // -- class X has no virtual functions and no virtual base classes
10558 if (CSM != CXXSpecialMemberKind::Destructor &&
10559 MD->getParent()->isDynamicClass()) {
10560 if (!Diagnose)
10561 return false;
10562
10563 if (RD->getNumVBases()) {
10564 // Check for virtual bases. We already know that the corresponding
10565 // member in all bases is trivial, so vbases must all be direct.
10566 CXXBaseSpecifier &BS = *RD->vbases_begin();
10567 assert(BS.isVirtual());
10568 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10569 return false;
10570 }
10571
10572 // Must have a virtual method.
10573 for (const auto *MI : RD->methods()) {
10574 if (MI->isVirtual()) {
10575 SourceLocation MLoc = MI->getBeginLoc();
10576 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10577 return false;
10578 }
10579 }
10580
10581 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10582 }
10583
10584 // Looks like it's trivial!
10585 return true;
10586}
10587
10588namespace {
10589struct FindHiddenVirtualMethod {
10590 Sema *S;
10591 CXXMethodDecl *Method;
10592 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10593 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10594
10595private:
10596 /// Check whether any most overridden method from MD in Methods
10597 static bool CheckMostOverridenMethods(
10598 const CXXMethodDecl *MD,
10599 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10600 if (MD->size_overridden_methods() == 0)
10601 return Methods.count(Ptr: MD->getCanonicalDecl());
10602 for (const CXXMethodDecl *O : MD->overridden_methods())
10603 if (CheckMostOverridenMethods(MD: O, Methods))
10604 return true;
10605 return false;
10606 }
10607
10608public:
10609 /// Member lookup function that determines whether a given C++
10610 /// method overloads virtual methods in a base class without overriding any,
10611 /// to be used with CXXRecordDecl::lookupInBases().
10612 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10613 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10614 DeclarationName Name = Method->getDeclName();
10615 assert(Name.getNameKind() == DeclarationName::Identifier);
10616
10617 bool foundSameNameMethod = false;
10618 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10619 for (Path.Decls = BaseRecord->lookup(Name).begin();
10620 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10621 NamedDecl *D = *Path.Decls;
10622 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10623 MD = MD->getCanonicalDecl();
10624 foundSameNameMethod = true;
10625 // Interested only in hidden virtual methods.
10626 if (!MD->isVirtual())
10627 continue;
10628 // If the method we are checking overrides a method from its base
10629 // don't warn about the other overloaded methods. Clang deviates from
10630 // GCC by only diagnosing overloads of inherited virtual functions that
10631 // do not override any other virtual functions in the base. GCC's
10632 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10633 // function from a base class. These cases may be better served by a
10634 // warning (not specific to virtual functions) on call sites when the
10635 // call would select a different function from the base class, were it
10636 // visible.
10637 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10638 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10639 return true;
10640 // Collect the overload only if its hidden.
10641 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10642 overloadedMethods.push_back(Elt: MD);
10643 }
10644 }
10645
10646 if (foundSameNameMethod)
10647 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10648 in_end: overloadedMethods.end());
10649 return foundSameNameMethod;
10650 }
10651};
10652} // end anonymous namespace
10653
10654/// Add the most overridden methods from MD to Methods
10655static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10656 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10657 if (MD->size_overridden_methods() == 0)
10658 Methods.insert(Ptr: MD->getCanonicalDecl());
10659 else
10660 for (const CXXMethodDecl *O : MD->overridden_methods())
10661 AddMostOverridenMethods(MD: O, Methods);
10662}
10663
10664void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10665 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10666 if (!MD->getDeclName().isIdentifier())
10667 return;
10668
10669 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10670 /*bool RecordPaths=*/false,
10671 /*bool DetectVirtual=*/false);
10672 FindHiddenVirtualMethod FHVM;
10673 FHVM.Method = MD;
10674 FHVM.S = this;
10675
10676 // Keep the base methods that were overridden or introduced in the subclass
10677 // by 'using' in a set. A base method not in this set is hidden.
10678 CXXRecordDecl *DC = MD->getParent();
10679 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10680 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10681 ND = shad->getTargetDecl();
10682 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10683 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10684 }
10685
10686 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10687 OverloadedMethods = FHVM.OverloadedMethods;
10688}
10689
10690void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10691 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10692 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10693 PartialDiagnostic PD = PDiag(
10694 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10695 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10696 Diag(Loc: overloadedMD->getLocation(), PD);
10697 }
10698}
10699
10700void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10701 if (MD->isInvalidDecl())
10702 return;
10703
10704 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10705 return;
10706
10707 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10708 FindHiddenVirtualMethods(MD, OverloadedMethods);
10709 if (!OverloadedMethods.empty()) {
10710 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10711 << MD << (OverloadedMethods.size() > 1);
10712
10713 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10714 }
10715}
10716
10717void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10718 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10719 // No diagnostics if this is a template instantiation.
10720 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10721 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10722 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10723 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10724 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10725 }
10726 RD.dropAttr<TrivialABIAttr>();
10727 };
10728
10729 // Ill-formed if the struct has virtual functions.
10730 if (RD.isPolymorphic()) {
10731 PrintDiagAndRemoveAttr(1);
10732 return;
10733 }
10734
10735 for (const auto &B : RD.bases()) {
10736 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10737 // virtual base.
10738 if (!B.getType()->isDependentType() &&
10739 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10740 PrintDiagAndRemoveAttr(2);
10741 return;
10742 }
10743
10744 if (B.isVirtual()) {
10745 PrintDiagAndRemoveAttr(3);
10746 return;
10747 }
10748 }
10749
10750 for (const auto *FD : RD.fields()) {
10751 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10752 // non-trivial for the purpose of calls.
10753 QualType FT = FD->getType();
10754 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10755 PrintDiagAndRemoveAttr(4);
10756 return;
10757 }
10758
10759 // Ill-formed if the field is an address-discriminated value.
10760 if (FT.hasAddressDiscriminatedPointerAuth()) {
10761 PrintDiagAndRemoveAttr(6);
10762 return;
10763 }
10764
10765 if (const auto *RT =
10766 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10767 if (!RT->isDependentType() &&
10768 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10769 ->canPassInRegisters()) {
10770 PrintDiagAndRemoveAttr(5);
10771 return;
10772 }
10773 }
10774
10775 if (IsCXXTriviallyRelocatableType(RD))
10776 return;
10777
10778 // Ill-formed if the copy and move constructors are deleted.
10779 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10780 // If the type is dependent, then assume it might have
10781 // implicit copy or move ctor because we won't know yet at this point.
10782 if (RD.isDependentType())
10783 return true;
10784 if (RD.needsImplicitCopyConstructor() &&
10785 !RD.defaultedCopyConstructorIsDeleted())
10786 return true;
10787 if (RD.needsImplicitMoveConstructor() &&
10788 !RD.defaultedMoveConstructorIsDeleted())
10789 return true;
10790 for (const CXXConstructorDecl *CD : RD.ctors())
10791 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10792 return true;
10793 return false;
10794 };
10795
10796 if (!HasNonDeletedCopyOrMoveConstructor()) {
10797 PrintDiagAndRemoveAttr(0);
10798 return;
10799 }
10800}
10801
10802void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10803 CXXRecordDecl &RD) {
10804 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10805 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10806 return;
10807
10808 const CXXRecordDecl *PrimaryBase = &RD;
10809 if (PrimaryBase->hasAnyDependentBases())
10810 return;
10811
10812 while (1) {
10813 assert(PrimaryBase);
10814 const CXXRecordDecl *Base = nullptr;
10815 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10816 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10817 continue;
10818 Base = BasePtr.getType()->getAsCXXRecordDecl();
10819 break;
10820 }
10821 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10822 break;
10823 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10824 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10825 << &RD << Base;
10826 PrimaryBase = Base;
10827 }
10828
10829 if (!RD.isPolymorphic())
10830 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10831 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10832 << &RD;
10833}
10834
10835void Sema::ActOnFinishCXXMemberSpecification(
10836 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10837 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10838 if (!TagDecl)
10839 return;
10840
10841 AdjustDeclIfTemplate(Decl&: TagDecl);
10842
10843 for (const ParsedAttr &AL : AttrList) {
10844 if (AL.getKind() != ParsedAttr::AT_Visibility)
10845 continue;
10846 AL.setInvalid();
10847 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10848 }
10849
10850 ActOnFields(S, RecLoc: RLoc, TagDecl,
10851 Fields: llvm::ArrayRef(
10852 // strict aliasing violation!
10853 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10854 FieldCollector->getCurNumFields()),
10855 LBrac, RBrac, AttrList);
10856
10857 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10858}
10859
10860/// Find the equality comparison functions that should be implicitly declared
10861/// in a given class definition, per C++2a [class.compare.default]p3.
10862static void findImplicitlyDeclaredEqualityComparisons(
10863 ASTContext &Ctx, CXXRecordDecl *RD,
10864 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10865 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10866 if (!RD->lookup(Name: EqEq).empty())
10867 // Member operator== explicitly declared: no implicit operator==s.
10868 return;
10869
10870 // Traverse friends looking for an '==' or a '<=>'.
10871 for (FriendDecl *Friend : RD->friends()) {
10872 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10873 if (!FD) continue;
10874
10875 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10876 // Friend operator== explicitly declared: no implicit operator==s.
10877 Spaceships.clear();
10878 return;
10879 }
10880
10881 if (FD->getOverloadedOperator() == OO_Spaceship &&
10882 FD->isExplicitlyDefaulted())
10883 Spaceships.push_back(Elt: FD);
10884 }
10885
10886 // Look for members named 'operator<=>'.
10887 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10888 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10889 // Note that we could find a non-function here (either a function template
10890 // or a using-declaration). Neither case results in an implicit
10891 // 'operator=='.
10892 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10893 if (FD->isExplicitlyDefaulted())
10894 Spaceships.push_back(Elt: FD);
10895 }
10896}
10897
10898void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10899 // Don't add implicit special members to templated classes.
10900 // FIXME: This means unqualified lookups for 'operator=' within a class
10901 // template don't work properly.
10902 if (!ClassDecl->isDependentType()) {
10903 if (ClassDecl->needsImplicitDefaultConstructor()) {
10904 ++getASTContext().NumImplicitDefaultConstructors;
10905
10906 if (ClassDecl->hasInheritedConstructor())
10907 DeclareImplicitDefaultConstructor(ClassDecl);
10908 }
10909
10910 if (ClassDecl->needsImplicitCopyConstructor()) {
10911 ++getASTContext().NumImplicitCopyConstructors;
10912
10913 // If the properties or semantics of the copy constructor couldn't be
10914 // determined while the class was being declared, force a declaration
10915 // of it now.
10916 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10917 ClassDecl->hasInheritedConstructor())
10918 DeclareImplicitCopyConstructor(ClassDecl);
10919 // For the MS ABI we need to know whether the copy ctor is deleted. A
10920 // prerequisite for deleting the implicit copy ctor is that the class has
10921 // a move ctor or move assignment that is either user-declared or whose
10922 // semantics are inherited from a subobject. FIXME: We should provide a
10923 // more direct way for CodeGen to ask whether the constructor was deleted.
10924 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10925 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10926 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10927 ClassDecl->hasUserDeclaredMoveAssignment() ||
10928 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10929 DeclareImplicitCopyConstructor(ClassDecl);
10930 }
10931
10932 if (getLangOpts().CPlusPlus11 &&
10933 ClassDecl->needsImplicitMoveConstructor()) {
10934 ++getASTContext().NumImplicitMoveConstructors;
10935
10936 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10937 ClassDecl->hasInheritedConstructor())
10938 DeclareImplicitMoveConstructor(ClassDecl);
10939 }
10940
10941 if (ClassDecl->needsImplicitCopyAssignment()) {
10942 ++getASTContext().NumImplicitCopyAssignmentOperators;
10943
10944 // If we have a dynamic class, then the copy assignment operator may be
10945 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10946 // it shows up in the right place in the vtable and that we diagnose
10947 // problems with the implicit exception specification.
10948 if (ClassDecl->isDynamicClass() ||
10949 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10950 ClassDecl->hasInheritedAssignment())
10951 DeclareImplicitCopyAssignment(ClassDecl);
10952 }
10953
10954 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10955 ++getASTContext().NumImplicitMoveAssignmentOperators;
10956
10957 // Likewise for the move assignment operator.
10958 if (ClassDecl->isDynamicClass() ||
10959 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10960 ClassDecl->hasInheritedAssignment())
10961 DeclareImplicitMoveAssignment(ClassDecl);
10962 }
10963
10964 if (ClassDecl->needsImplicitDestructor()) {
10965 ++getASTContext().NumImplicitDestructors;
10966
10967 // If we have a dynamic class, then the destructor may be virtual, so we
10968 // have to declare the destructor immediately. This ensures that, e.g., it
10969 // shows up in the right place in the vtable and that we diagnose problems
10970 // with the implicit exception specification.
10971 if (ClassDecl->isDynamicClass() ||
10972 ClassDecl->needsOverloadResolutionForDestructor())
10973 DeclareImplicitDestructor(ClassDecl);
10974 }
10975 }
10976
10977 // C++2a [class.compare.default]p3:
10978 // If the member-specification does not explicitly declare any member or
10979 // friend named operator==, an == operator function is declared implicitly
10980 // for each defaulted three-way comparison operator function defined in
10981 // the member-specification
10982 // FIXME: Consider doing this lazily.
10983 // We do this during the initial parse for a class template, not during
10984 // instantiation, so that we can handle unqualified lookups for 'operator=='
10985 // when parsing the template.
10986 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10987 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10988 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10989 Spaceships&: DefaultedSpaceships);
10990 for (auto *FD : DefaultedSpaceships)
10991 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10992 }
10993}
10994
10995unsigned
10996Sema::ActOnReenterTemplateScope(Decl *D,
10997 llvm::function_ref<Scope *()> EnterScope) {
10998 if (!D)
10999 return 0;
11000 AdjustDeclIfTemplate(Decl&: D);
11001
11002 // In order to get name lookup right, reenter template scopes in order from
11003 // outermost to innermost.
11004 SmallVector<TemplateParameterList *, 4> ParameterLists;
11005 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
11006
11007 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11008 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11009 ParameterLists.push_back(Elt: TPL);
11010
11011 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
11012 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11013 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
11014 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
11015 LookupDC = VD->getDeclContext();
11016
11017 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
11018 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
11019 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
11020 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11021 }
11022 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
11023 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11024 ParameterLists.push_back(Elt: TPL);
11025
11026 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
11027 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
11028 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
11029 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
11030 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11031 }
11032 }
11033 // FIXME: Alias declarations and concepts.
11034
11035 unsigned Count = 0;
11036 Scope *InnermostTemplateScope = nullptr;
11037 for (TemplateParameterList *Params : ParameterLists) {
11038 // Ignore explicit specializations; they don't contribute to the template
11039 // depth.
11040 if (Params->size() == 0)
11041 continue;
11042
11043 InnermostTemplateScope = EnterScope();
11044 for (NamedDecl *Param : *Params) {
11045 if (Param->getDeclName()) {
11046 InnermostTemplateScope->AddDecl(D: Param);
11047 IdResolver.AddDecl(D: Param);
11048 }
11049 }
11050 ++Count;
11051 }
11052
11053 // Associate the new template scopes with the corresponding entities.
11054 if (InnermostTemplateScope) {
11055 assert(LookupDC && "no enclosing DeclContext for template lookup");
11056 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11057 }
11058
11059 return Count;
11060}
11061
11062void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11063 if (!RecordD) return;
11064 AdjustDeclIfTemplate(Decl&: RecordD);
11065 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11066 PushDeclContext(S, DC: Record);
11067}
11068
11069void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11070 if (!RecordD) return;
11071 PopDeclContext();
11072}
11073
11074void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11075 if (!Param)
11076 return;
11077
11078 S->AddDecl(D: Param);
11079 if (Param->getDeclName())
11080 IdResolver.AddDecl(D: Param);
11081}
11082
11083void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11084}
11085
11086/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11087/// C++ method declaration. We're (re-)introducing the given
11088/// function parameter into scope for use in parsing later parts of
11089/// the method declaration. For example, we could see an
11090/// ActOnParamDefaultArgument event for this parameter.
11091void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11092 if (!ParamD)
11093 return;
11094
11095 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11096
11097 S->AddDecl(D: Param);
11098 if (Param->getDeclName())
11099 IdResolver.AddDecl(D: Param);
11100}
11101
11102void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11103 if (!MethodD)
11104 return;
11105
11106 AdjustDeclIfTemplate(Decl&: MethodD);
11107
11108 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11109
11110 // Now that we have our default arguments, check the constructor
11111 // again. It could produce additional diagnostics or affect whether
11112 // the class has implicitly-declared destructors, among other
11113 // things.
11114 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11115 CheckConstructor(Constructor);
11116
11117 // Check the default arguments, which we may have added.
11118 if (!Method->isInvalidDecl())
11119 CheckCXXDefaultArguments(FD: Method);
11120}
11121
11122// Emit the given diagnostic for each non-address-space qualifier.
11123// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11124static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11125 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11126 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11127 bool DiagOccurred = false;
11128 FTI.MethodQualifiers->forEachQualifier(
11129 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11130 SourceLocation SL) {
11131 // This diagnostic should be emitted on any qualifier except an addr
11132 // space qualifier. However, forEachQualifier currently doesn't visit
11133 // addr space qualifiers, so there's no way to write this condition
11134 // right now; we just diagnose on everything.
11135 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11136 DiagOccurred = true;
11137 });
11138 if (DiagOccurred)
11139 D.setInvalidType();
11140 }
11141}
11142
11143static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11144 unsigned Kind) {
11145 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11146 return;
11147
11148 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11149 if (Chunk.Kind == DeclaratorChunk::Paren ||
11150 Chunk.Kind == DeclaratorChunk::Function)
11151 return;
11152
11153 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11154 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11155 << Kind << Chunk.getSourceRange();
11156 D.setInvalidType();
11157}
11158
11159QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11160 StorageClass &SC) {
11161 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11162
11163 // C++ [class.ctor]p3:
11164 // A constructor shall not be virtual (10.3) or static (9.4). A
11165 // constructor can be invoked for a const, volatile or const
11166 // volatile object. A constructor shall not be declared const,
11167 // volatile, or const volatile (9.3.2).
11168 if (isVirtual) {
11169 if (!D.isInvalidType())
11170 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11171 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11172 << SourceRange(D.getIdentifierLoc());
11173 D.setInvalidType();
11174 }
11175 if (SC == SC_Static) {
11176 if (!D.isInvalidType())
11177 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11178 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11179 << SourceRange(D.getIdentifierLoc());
11180 D.setInvalidType();
11181 SC = SC_None;
11182 }
11183
11184 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11185 diagnoseIgnoredQualifiers(
11186 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11187 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11188 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11189 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11190 D.setInvalidType();
11191 }
11192
11193 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11194 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11195
11196 // C++0x [class.ctor]p4:
11197 // A constructor shall not be declared with a ref-qualifier.
11198 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11199 if (FTI.hasRefQualifier()) {
11200 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11201 << FTI.RefQualifierIsLValueRef
11202 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11203 D.setInvalidType();
11204 }
11205
11206 // Rebuild the function type "R" without any type qualifiers (in
11207 // case any of the errors above fired) and with "void" as the
11208 // return type, since constructors don't have return types.
11209 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11210 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11211 return R;
11212
11213 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11214 EPI.TypeQuals = Qualifiers();
11215 EPI.RefQualifier = RQ_None;
11216
11217 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11218}
11219
11220void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11221 CXXRecordDecl *ClassDecl
11222 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11223 if (!ClassDecl)
11224 return Constructor->setInvalidDecl();
11225
11226 // C++ [class.copy]p3:
11227 // A declaration of a constructor for a class X is ill-formed if
11228 // its first parameter is of type (optionally cv-qualified) X and
11229 // either there are no other parameters or else all other
11230 // parameters have default arguments.
11231 if (!Constructor->isInvalidDecl() &&
11232 Constructor->hasOneParamOrDefaultArgs() &&
11233 !Constructor->isFunctionTemplateSpecialization()) {
11234 CanQualType ParamType =
11235 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11236 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11237 if (ParamType == ClassTy) {
11238 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11239 const char *ConstRef
11240 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11241 : " const &";
11242 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11243 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11244
11245 // FIXME: Rather that making the constructor invalid, we should endeavor
11246 // to fix the type.
11247 Constructor->setInvalidDecl();
11248 }
11249 }
11250}
11251
11252bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11253 CXXRecordDecl *RD = Destructor->getParent();
11254
11255 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11256 SourceLocation Loc;
11257
11258 if (!Destructor->isImplicit())
11259 Loc = Destructor->getLocation();
11260 else
11261 Loc = RD->getLocation();
11262
11263 DeclarationName Name =
11264 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11265 // If we have a virtual destructor, look up the deallocation function
11266 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11267 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11268 Expr *ThisArg = nullptr;
11269
11270 // If the notional 'delete this' expression requires a non-trivial
11271 // conversion from 'this' to the type of a destroying operator delete's
11272 // first parameter, perform that conversion now.
11273 if (OperatorDelete->isDestroyingOperatorDelete()) {
11274 unsigned AddressParamIndex = 0;
11275 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11276 ++AddressParamIndex;
11277 QualType ParamType =
11278 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11279 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11280 // C++ [class.dtor]p13:
11281 // ... as if for the expression 'delete this' appearing in a
11282 // non-virtual destructor of the destructor's class.
11283 ContextRAII SwitchContext(*this, Destructor);
11284 ExprResult This = ActOnCXXThis(
11285 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11286 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11287 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11288 Action: AssignmentAction::Passing);
11289 if (This.isInvalid()) {
11290 // FIXME: Register this as a context note so that it comes out
11291 // in the right order.
11292 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11293 return true;
11294 }
11295 ThisArg = This.get();
11296 }
11297 }
11298
11299 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11300 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11301 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11302
11303 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11304 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11305 Context.getLangOpts())) {
11306 // In Microsoft ABI whenever a class has a defined operator delete,
11307 // scalar deleting destructors check the 3rd bit of the implicit
11308 // parameter and if it is set, then, global operator delete must be
11309 // called instead of the class-specific one. Find and save the global
11310 // operator delete for that case. Do not diagnose at this point because
11311 // the lack of a global operator delete is not an error if there are no
11312 // delete calls that require it.
11313 FunctionDecl *GlobalOperatorDelete =
11314 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11315 /*LookForGlobal*/ true, Name);
11316 if (GlobalOperatorDelete) {
11317 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11318 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11319 }
11320 }
11321
11322 if (Context.getTargetInfo().emitVectorDeletingDtors(
11323 Context.getLangOpts())) {
11324 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11325 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11326 DeclarationName VDeleteName =
11327 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11328 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11329 StartLoc: Loc, RD, /*Diagnose*/ false,
11330 /*LookForGlobal*/ false, Name: VDeleteName);
11331 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11332 FunctionDecl *GlobalArrOperatorDelete =
11333 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11334 /*LookForGlobal*/ true,
11335 Name: VDeleteName);
11336 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11337 if (GlobalArrOperatorDelete &&
11338 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11339 DestructorIsExported))
11340 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11341 } else if (!ArrOperatorDelete) {
11342 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11343 StartLoc: Loc, RD, /*Diagnose*/ false,
11344 /*LookForGlobal*/ true, Name: VDeleteName);
11345 }
11346 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11347 if (ArrOperatorDelete &&
11348 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11349 DestructorIsExported))
11350 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11351 }
11352 }
11353 }
11354
11355 return false;
11356}
11357
11358QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11359 StorageClass& SC) {
11360 // C++ [class.dtor]p1:
11361 // [...] A typedef-name that names a class is a class-name
11362 // (7.1.3); however, a typedef-name that names a class shall not
11363 // be used as the identifier in the declarator for a destructor
11364 // declaration.
11365 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11366 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11367 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11368 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11369 else if (const TemplateSpecializationType *TST =
11370 DeclaratorType->getAs<TemplateSpecializationType>())
11371 if (TST->isTypeAlias())
11372 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11373 << DeclaratorType << 1;
11374
11375 // C++ [class.dtor]p2:
11376 // A destructor is used to destroy objects of its class type. A
11377 // destructor takes no parameters, and no return type can be
11378 // specified for it (not even void). The address of a destructor
11379 // shall not be taken. A destructor shall not be static. A
11380 // destructor can be invoked for a const, volatile or const
11381 // volatile object. A destructor shall not be declared const,
11382 // volatile or const volatile (9.3.2).
11383 if (SC == SC_Static) {
11384 if (!D.isInvalidType())
11385 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11386 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11387 << SourceRange(D.getIdentifierLoc())
11388 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11389
11390 SC = SC_None;
11391 }
11392 if (!D.isInvalidType()) {
11393 // Destructors don't have return types, but the parser will
11394 // happily parse something like:
11395 //
11396 // class X {
11397 // float ~X();
11398 // };
11399 //
11400 // The return type will be eliminated later.
11401 if (D.getDeclSpec().hasTypeSpecifier())
11402 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11403 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11404 << SourceRange(D.getIdentifierLoc());
11405 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11406 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11407 FallbackLoc: SourceLocation(),
11408 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11409 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11410 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11411 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11412 D.setInvalidType();
11413 }
11414 }
11415
11416 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11417 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11418
11419 // C++0x [class.dtor]p2:
11420 // A destructor shall not be declared with a ref-qualifier.
11421 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11422 if (FTI.hasRefQualifier()) {
11423 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11424 << FTI.RefQualifierIsLValueRef
11425 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11426 D.setInvalidType();
11427 }
11428
11429 // Make sure we don't have any parameters.
11430 if (FTIHasNonVoidParameters(FTI)) {
11431 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11432
11433 // Delete the parameters.
11434 FTI.freeParams();
11435 D.setInvalidType();
11436 }
11437
11438 // Make sure the destructor isn't variadic.
11439 if (FTI.isVariadic) {
11440 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11441 D.setInvalidType();
11442 }
11443
11444 // Rebuild the function type "R" without any type qualifiers or
11445 // parameters (in case any of the errors above fired) and with
11446 // "void" as the return type, since destructors don't have return
11447 // types.
11448 if (!D.isInvalidType())
11449 return R;
11450
11451 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11452 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11453 EPI.Variadic = false;
11454 EPI.TypeQuals = Qualifiers();
11455 EPI.RefQualifier = RQ_None;
11456 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11457}
11458
11459static void extendLeft(SourceRange &R, SourceRange Before) {
11460 if (Before.isInvalid())
11461 return;
11462 R.setBegin(Before.getBegin());
11463 if (R.getEnd().isInvalid())
11464 R.setEnd(Before.getEnd());
11465}
11466
11467static void extendRight(SourceRange &R, SourceRange After) {
11468 if (After.isInvalid())
11469 return;
11470 if (R.getBegin().isInvalid())
11471 R.setBegin(After.getBegin());
11472 R.setEnd(After.getEnd());
11473}
11474
11475void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11476 StorageClass& SC) {
11477 // C++ [class.conv.fct]p1:
11478 // Neither parameter types nor return type can be specified. The
11479 // type of a conversion function (8.3.5) is "function taking no
11480 // parameter returning conversion-type-id."
11481 if (SC == SC_Static) {
11482 if (!D.isInvalidType())
11483 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11484 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11485 << D.getName().getSourceRange();
11486 D.setInvalidType();
11487 SC = SC_None;
11488 }
11489
11490 TypeSourceInfo *ConvTSI = nullptr;
11491 QualType ConvType =
11492 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11493
11494 const DeclSpec &DS = D.getDeclSpec();
11495 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11496 // Conversion functions don't have return types, but the parser will
11497 // happily parse something like:
11498 //
11499 // class X {
11500 // float operator bool();
11501 // };
11502 //
11503 // The return type will be changed later anyway.
11504 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11505 << SourceRange(DS.getTypeSpecTypeLoc())
11506 << SourceRange(D.getIdentifierLoc());
11507 D.setInvalidType();
11508 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11509 // It's also plausible that the user writes type qualifiers in the wrong
11510 // place, such as:
11511 // struct S { const operator int(); };
11512 // FIXME: we could provide a fixit to move the qualifiers onto the
11513 // conversion type.
11514 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11515 << SourceRange(D.getIdentifierLoc()) << 0;
11516 D.setInvalidType();
11517 }
11518 const auto *Proto = R->castAs<FunctionProtoType>();
11519 // Make sure we don't have any parameters.
11520 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11521 unsigned NumParam = Proto->getNumParams();
11522
11523 // [C++2b]
11524 // A conversion function shall have no non-object parameters.
11525 if (NumParam == 1) {
11526 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11527 if (const auto *First =
11528 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11529 First && First->isExplicitObjectParameter())
11530 NumParam--;
11531 }
11532
11533 if (NumParam != 0) {
11534 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11535 // Delete the parameters.
11536 FTI.freeParams();
11537 D.setInvalidType();
11538 } else if (Proto->isVariadic()) {
11539 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11540 D.setInvalidType();
11541 }
11542
11543 // Diagnose "&operator bool()" and other such nonsense. This
11544 // is actually a gcc extension which we don't support.
11545 if (Proto->getReturnType() != ConvType) {
11546 bool NeedsTypedef = false;
11547 SourceRange Before, After;
11548
11549 // Walk the chunks and extract information on them for our diagnostic.
11550 bool PastFunctionChunk = false;
11551 for (auto &Chunk : D.type_objects()) {
11552 switch (Chunk.Kind) {
11553 case DeclaratorChunk::Function:
11554 if (!PastFunctionChunk) {
11555 if (Chunk.Fun.HasTrailingReturnType) {
11556 TypeSourceInfo *TRT = nullptr;
11557 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11558 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11559 }
11560 PastFunctionChunk = true;
11561 break;
11562 }
11563 [[fallthrough]];
11564 case DeclaratorChunk::Array:
11565 NeedsTypedef = true;
11566 extendRight(R&: After, After: Chunk.getSourceRange());
11567 break;
11568
11569 case DeclaratorChunk::Pointer:
11570 case DeclaratorChunk::BlockPointer:
11571 case DeclaratorChunk::Reference:
11572 case DeclaratorChunk::MemberPointer:
11573 case DeclaratorChunk::Pipe:
11574 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11575 break;
11576
11577 case DeclaratorChunk::Paren:
11578 extendLeft(R&: Before, Before: Chunk.Loc);
11579 extendRight(R&: After, After: Chunk.EndLoc);
11580 break;
11581 }
11582 }
11583
11584 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11585 After.isValid() ? After.getBegin() :
11586 D.getIdentifierLoc();
11587 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11588 DB << Before << After;
11589
11590 if (!NeedsTypedef) {
11591 DB << /*don't need a typedef*/0;
11592
11593 // If we can provide a correct fix-it hint, do so.
11594 if (After.isInvalid() && ConvTSI) {
11595 SourceLocation InsertLoc =
11596 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11597 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11598 << FixItHint::CreateInsertionFromRange(
11599 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11600 << FixItHint::CreateRemoval(RemoveRange: Before);
11601 }
11602 } else if (!Proto->getReturnType()->isDependentType()) {
11603 DB << /*typedef*/1 << Proto->getReturnType();
11604 } else if (getLangOpts().CPlusPlus11) {
11605 DB << /*alias template*/2 << Proto->getReturnType();
11606 } else {
11607 DB << /*might not be fixable*/3;
11608 }
11609
11610 // Recover by incorporating the other type chunks into the result type.
11611 // Note, this does *not* change the name of the function. This is compatible
11612 // with the GCC extension:
11613 // struct S { &operator int(); } s;
11614 // int &r = s.operator int(); // ok in GCC
11615 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11616 ConvType = Proto->getReturnType();
11617 }
11618
11619 // C++ [class.conv.fct]p4:
11620 // The conversion-type-id shall not represent a function type nor
11621 // an array type.
11622 if (ConvType->isArrayType()) {
11623 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11624 ConvType = Context.getPointerType(T: ConvType);
11625 D.setInvalidType();
11626 } else if (ConvType->isFunctionType()) {
11627 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11628 ConvType = Context.getPointerType(T: ConvType);
11629 D.setInvalidType();
11630 }
11631
11632 // Rebuild the function type "R" without any parameters (in case any
11633 // of the errors above fired) and with the conversion type as the
11634 // return type.
11635 if (D.isInvalidType())
11636 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11637
11638 // C++0x explicit conversion operators.
11639 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11640 Diag(Loc: DS.getExplicitSpecLoc(),
11641 DiagID: getLangOpts().CPlusPlus11
11642 ? diag::warn_cxx98_compat_explicit_conversion_functions
11643 : diag::ext_explicit_conversion_functions)
11644 << SourceRange(DS.getExplicitSpecRange());
11645}
11646
11647Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11648 assert(Conversion && "Expected to receive a conversion function declaration");
11649
11650 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11651
11652 // Make sure we aren't redeclaring the conversion function.
11653 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11654 // C++ [class.conv.fct]p1:
11655 // [...] A conversion function is never used to convert a
11656 // (possibly cv-qualified) object to the (possibly cv-qualified)
11657 // same object type (or a reference to it), to a (possibly
11658 // cv-qualified) base class of that type (or a reference to it),
11659 // or to (possibly cv-qualified) void.
11660 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11661 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11662 ConvType = ConvTypeRef->getPointeeType();
11663 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11664 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11665 /* Suppress diagnostics for instantiations. */;
11666 else if (Conversion->size_overridden_methods() != 0)
11667 /* Suppress diagnostics for overriding virtual function in a base class. */;
11668 else if (ConvType->isRecordType()) {
11669 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11670 if (ConvType == ClassType)
11671 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11672 << ClassType;
11673 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11674 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11675 << ClassType << ConvType;
11676 } else if (ConvType->isVoidType()) {
11677 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11678 << ClassType << ConvType;
11679 }
11680
11681 if (FunctionTemplateDecl *ConversionTemplate =
11682 Conversion->getDescribedFunctionTemplate()) {
11683 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11684 ConvType = ConvTypePtr->getPointeeType();
11685 }
11686 if (ConvType->isUndeducedAutoType()) {
11687 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11688 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11689 << ConvType->castAs<AutoType>()->getKeyword()
11690 << /* in declaration of conversion function template= */ 24;
11691 }
11692
11693 return ConversionTemplate;
11694 }
11695
11696 return Conversion;
11697}
11698
11699void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11700 DeclarationName Name, QualType R) {
11701 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11702}
11703
11704void Sema::CheckExplicitObjectLambda(Declarator &D) {
11705 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11706}
11707
11708void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11709 DeclarationName Name, QualType R,
11710 bool IsLambda, DeclContext *DC) {
11711 if (!D.isFunctionDeclarator())
11712 return;
11713
11714 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11715 if (FTI.NumParams == 0)
11716 return;
11717 ParmVarDecl *ExplicitObjectParam = nullptr;
11718 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11719 const auto &ParamInfo = FTI.Params[Idx];
11720 if (!ParamInfo.Param)
11721 continue;
11722 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11723 if (!Param->isExplicitObjectParameter())
11724 continue;
11725 if (Idx == 0) {
11726 ExplicitObjectParam = Param;
11727 continue;
11728 } else {
11729 Diag(Loc: Param->getLocation(),
11730 DiagID: diag::err_explicit_object_parameter_must_be_first)
11731 << IsLambda << Param->getSourceRange();
11732 }
11733 }
11734 if (!ExplicitObjectParam)
11735 return;
11736
11737 if (ExplicitObjectParam->hasDefaultArg()) {
11738 Diag(Loc: ExplicitObjectParam->getLocation(),
11739 DiagID: diag::err_explicit_object_default_arg)
11740 << ExplicitObjectParam->getSourceRange();
11741 D.setInvalidType();
11742 }
11743
11744 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11745 (D.getContext() == clang::DeclaratorContext::Member &&
11746 D.isStaticMember())) {
11747 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11748 DiagID: diag::err_explicit_object_parameter_nonmember)
11749 << D.getSourceRange() << /*static=*/0 << IsLambda;
11750 D.setInvalidType();
11751 }
11752
11753 if (D.getDeclSpec().isVirtualSpecified()) {
11754 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11755 DiagID: diag::err_explicit_object_parameter_nonmember)
11756 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11757 D.setInvalidType();
11758 }
11759
11760 // Friend declarations require some care. Consider:
11761 //
11762 // namespace N {
11763 // struct A{};
11764 // int f(A);
11765 // }
11766 //
11767 // struct S {
11768 // struct T {
11769 // int f(this T);
11770 // };
11771 //
11772 // friend int T::f(this T); // Allow this.
11773 // friend int f(this S); // But disallow this.
11774 // friend int N::f(this A); // And disallow this.
11775 // };
11776 //
11777 // Here, it seems to suffice to check whether the scope
11778 // specifier designates a class type.
11779 if (D.getDeclSpec().isFriendSpecified() &&
11780 !isa_and_present<CXXRecordDecl>(
11781 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11782 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11783 DiagID: diag::err_explicit_object_parameter_nonmember)
11784 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11785 D.setInvalidType();
11786 }
11787
11788 if (IsLambda && FTI.hasMutableQualifier()) {
11789 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11790 DiagID: diag::err_explicit_object_parameter_mutable)
11791 << D.getSourceRange();
11792 }
11793
11794 if (IsLambda)
11795 return;
11796
11797 if (!DC || !DC->isRecord()) {
11798 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11799 "should have been diagnosed already");
11800 return;
11801 }
11802
11803 // CWG2674: constructors and destructors cannot have explicit parameters.
11804 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11805 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11806 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11807 DiagID: diag::err_explicit_object_parameter_constructor)
11808 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11809 << D.getSourceRange();
11810 D.setInvalidType();
11811 }
11812}
11813
11814namespace {
11815/// Utility class to accumulate and print a diagnostic listing the invalid
11816/// specifier(s) on a declaration.
11817struct BadSpecifierDiagnoser {
11818 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11819 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11820 ~BadSpecifierDiagnoser() {
11821 Diagnostic << Specifiers;
11822 }
11823
11824 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11825 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11826 }
11827 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11828 return check(SpecLoc,
11829 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11830 }
11831 void check(SourceLocation SpecLoc, const char *Spec) {
11832 if (SpecLoc.isInvalid()) return;
11833 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11834 if (!Specifiers.empty()) Specifiers += " ";
11835 Specifiers += Spec;
11836 }
11837
11838 Sema &S;
11839 Sema::SemaDiagnosticBuilder Diagnostic;
11840 std::string Specifiers;
11841};
11842}
11843
11844bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11845 StorageClass &SC) {
11846 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11847 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11848 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11849
11850 // C++ [temp.deduct.guide]p3:
11851 // A deduction-gide shall be declared in the same scope as the
11852 // corresponding class template.
11853 if (!CurContext->getRedeclContext()->Equals(
11854 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11855 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11856 << GuidedTemplateDecl;
11857 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11858 }
11859
11860 auto &DS = D.getMutableDeclSpec();
11861 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11862 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11863 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11864 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11865 BadSpecifierDiagnoser Diagnoser(
11866 *this, D.getIdentifierLoc(),
11867 diag::err_deduction_guide_invalid_specifier);
11868
11869 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11870 DS.ClearStorageClassSpecs();
11871 SC = SC_None;
11872
11873 // 'explicit' is permitted.
11874 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11875 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11876 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11877 DS.ClearConstexprSpec();
11878
11879 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11880 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11881 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11882 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11883 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11884 DS.ClearTypeQualifiers();
11885
11886 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11887 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11888 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11889 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11890 DS.ClearTypeSpecType();
11891 }
11892
11893 if (D.isInvalidType())
11894 return true;
11895
11896 // Check the declarator is simple enough.
11897 bool FoundFunction = false;
11898 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11899 if (Chunk.Kind == DeclaratorChunk::Paren)
11900 continue;
11901 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11902 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11903 DiagID: diag::err_deduction_guide_with_complex_decl)
11904 << D.getSourceRange();
11905 break;
11906 }
11907 if (!Chunk.Fun.hasTrailingReturnType())
11908 return Diag(Loc: D.getName().getBeginLoc(),
11909 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11910
11911 // Check that the return type is written as a specialization of
11912 // the template specified as the deduction-guide's name.
11913 // The template name may not be qualified. [temp.deduct.guide]
11914 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11915 TypeSourceInfo *TSI = nullptr;
11916 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11917 assert(TSI && "deduction guide has valid type but invalid return type?");
11918 bool AcceptableReturnType = false;
11919 bool MightInstantiateToSpecialization = false;
11920 if (auto RetTST =
11921 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11922 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11923 bool TemplateMatches = Context.hasSameTemplateName(
11924 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11925
11926 const QualifiedTemplateName *Qualifiers =
11927 SpecifiedName.getAsQualifiedTemplateName();
11928 // A Template template parameter is never wrapped in a
11929 // QualifiedTemplateName, but it's always simply-written.
11930 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11931 !Qualifiers->getQualifier());
11932 if (SimplyWritten && TemplateMatches)
11933 AcceptableReturnType = true;
11934 else {
11935 // This could still instantiate to the right type, unless we know it
11936 // names the wrong class template.
11937 auto *TD = SpecifiedName.getAsTemplateDecl();
11938 MightInstantiateToSpecialization =
11939 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11940 }
11941 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11942 MightInstantiateToSpecialization = true;
11943 }
11944
11945 if (!AcceptableReturnType)
11946 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11947 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11948 << GuidedTemplate << TSI->getType()
11949 << MightInstantiateToSpecialization
11950 << TSI->getTypeLoc().getSourceRange();
11951
11952 // Keep going to check that we don't have any inner declarator pieces (we
11953 // could still have a function returning a pointer to a function).
11954 FoundFunction = true;
11955 }
11956
11957 if (D.isFunctionDefinition())
11958 // we can still create a valid deduction guide here.
11959 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11960 return false;
11961}
11962
11963//===----------------------------------------------------------------------===//
11964// Namespace Handling
11965//===----------------------------------------------------------------------===//
11966
11967/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11968/// reopened.
11969static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11970 SourceLocation Loc,
11971 IdentifierInfo *II, bool *IsInline,
11972 NamespaceDecl *PrevNS) {
11973 assert(*IsInline != PrevNS->isInline());
11974
11975 // 'inline' must appear on the original definition, but not necessarily
11976 // on all extension definitions, so the note should point to the first
11977 // definition to avoid confusion.
11978 PrevNS = PrevNS->getFirstDecl();
11979
11980 if (PrevNS->isInline())
11981 // The user probably just forgot the 'inline', so suggest that it
11982 // be added back.
11983 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11984 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11985 else
11986 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11987
11988 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11989 *IsInline = PrevNS->isInline();
11990}
11991
11992/// ActOnStartNamespaceDef - This is called at the start of a namespace
11993/// definition.
11994Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11995 SourceLocation InlineLoc,
11996 SourceLocation NamespaceLoc,
11997 SourceLocation IdentLoc, IdentifierInfo *II,
11998 SourceLocation LBrace,
11999 const ParsedAttributesView &AttrList,
12000 UsingDirectiveDecl *&UD, bool IsNested) {
12001 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12002 // For anonymous namespace, take the location of the left brace.
12003 SourceLocation Loc = II ? IdentLoc : LBrace;
12004 bool IsInline = InlineLoc.isValid();
12005 bool IsInvalid = false;
12006 bool IsStd = false;
12007 bool AddToKnown = false;
12008 Scope *DeclRegionScope = NamespcScope->getParent();
12009
12010 NamespaceDecl *PrevNS = nullptr;
12011 if (II) {
12012 // C++ [namespace.std]p7:
12013 // A translation unit shall not declare namespace std to be an inline
12014 // namespace (9.8.2).
12015 //
12016 // Precondition: the std namespace is in the file scope and is declared to
12017 // be inline
12018 auto DiagnoseInlineStdNS = [&]() {
12019 assert(IsInline && II->isStr("std") &&
12020 CurContext->getRedeclContext()->isTranslationUnit() &&
12021 "Precondition of DiagnoseInlineStdNS not met");
12022 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
12023 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
12024 IsInline = false;
12025 };
12026 // C++ [namespace.def]p2:
12027 // The identifier in an original-namespace-definition shall not
12028 // have been previously defined in the declarative region in
12029 // which the original-namespace-definition appears. The
12030 // identifier in an original-namespace-definition is the name of
12031 // the namespace. Subsequently in that declarative region, it is
12032 // treated as an original-namespace-name.
12033 //
12034 // Since namespace names are unique in their scope, and we don't
12035 // look through using directives, just look for any ordinary names
12036 // as if by qualified name lookup.
12037 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12038 RedeclarationKind::ForExternalRedeclaration);
12039 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
12040 NamedDecl *PrevDecl =
12041 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12042 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
12043
12044 if (PrevNS) {
12045 // This is an extended namespace definition.
12046 if (IsInline && II->isStr(Str: "std") &&
12047 CurContext->getRedeclContext()->isTranslationUnit())
12048 DiagnoseInlineStdNS();
12049 else if (IsInline != PrevNS->isInline())
12050 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12051 IsInline: &IsInline, PrevNS);
12052 } else if (PrevDecl) {
12053 // This is an invalid name redefinition.
12054 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12055 << II;
12056 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12057 IsInvalid = true;
12058 // Continue on to push Namespc as current DeclContext and return it.
12059 } else if (II->isStr(Str: "std") &&
12060 CurContext->getRedeclContext()->isTranslationUnit()) {
12061 if (IsInline)
12062 DiagnoseInlineStdNS();
12063 // This is the first "real" definition of the namespace "std", so update
12064 // our cache of the "std" namespace to point at this definition.
12065 PrevNS = getStdNamespace();
12066 IsStd = true;
12067 AddToKnown = !IsInline;
12068 } else {
12069 // We've seen this namespace for the first time.
12070 AddToKnown = !IsInline;
12071 }
12072 } else {
12073 // Anonymous namespaces.
12074
12075 // Determine whether the parent already has an anonymous namespace.
12076 DeclContext *Parent = CurContext->getRedeclContext();
12077 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12078 PrevNS = TU->getAnonymousNamespace();
12079 } else {
12080 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12081 PrevNS = ND->getAnonymousNamespace();
12082 }
12083
12084 if (PrevNS && IsInline != PrevNS->isInline())
12085 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12086 IsInline: &IsInline, PrevNS);
12087 }
12088
12089 NamespaceDecl *Namespc = NamespaceDecl::Create(
12090 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12091 if (IsInvalid)
12092 Namespc->setInvalidDecl();
12093
12094 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12095 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12096 ProcessAPINotes(D: Namespc);
12097
12098 // FIXME: Should we be merging attributes?
12099 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12100 PushNamespaceVisibilityAttr(Attr, Loc);
12101
12102 if (IsStd)
12103 StdNamespace = Namespc;
12104 if (AddToKnown)
12105 KnownNamespaces[Namespc] = false;
12106
12107 if (II) {
12108 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12109 } else {
12110 // Link the anonymous namespace into its parent.
12111 DeclContext *Parent = CurContext->getRedeclContext();
12112 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12113 TU->setAnonymousNamespace(Namespc);
12114 } else {
12115 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12116 }
12117
12118 CurContext->addDecl(D: Namespc);
12119
12120 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12121 // behaves as if it were replaced by
12122 // namespace unique { /* empty body */ }
12123 // using namespace unique;
12124 // namespace unique { namespace-body }
12125 // where all occurrences of 'unique' in a translation unit are
12126 // replaced by the same identifier and this identifier differs
12127 // from all other identifiers in the entire program.
12128
12129 // We just create the namespace with an empty name and then add an
12130 // implicit using declaration, just like the standard suggests.
12131 //
12132 // CodeGen enforces the "universally unique" aspect by giving all
12133 // declarations semantically contained within an anonymous
12134 // namespace internal linkage.
12135
12136 if (!PrevNS) {
12137 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12138 /* 'using' */ UsingLoc: LBrace,
12139 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12140 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12141 /* identifier */ IdentLoc: SourceLocation(),
12142 Nominated: Namespc,
12143 /* Ancestor */ CommonAncestor: Parent);
12144 UD->setImplicit();
12145 Parent->addDecl(D: UD);
12146 }
12147 }
12148
12149 ActOnDocumentableDecl(D: Namespc);
12150
12151 // Although we could have an invalid decl (i.e. the namespace name is a
12152 // redefinition), push it as current DeclContext and try to continue parsing.
12153 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12154 // for the namespace has the declarations that showed up in that particular
12155 // namespace definition.
12156 PushDeclContext(S: NamespcScope, DC: Namespc);
12157 return Namespc;
12158}
12159
12160/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12161/// is a namespace alias, returns the namespace it points to.
12162static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12163 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12164 return AD->getNamespace();
12165 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12166}
12167
12168void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12169 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12170 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12171 Namespc->setRBraceLoc(RBrace);
12172 PopDeclContext();
12173 if (Namespc->hasAttr<VisibilityAttr>())
12174 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12175 // If this namespace contains an export-declaration, export it now.
12176 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12177 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12178}
12179
12180CXXRecordDecl *Sema::getStdBadAlloc() const {
12181 return cast_or_null<CXXRecordDecl>(
12182 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12183}
12184
12185EnumDecl *Sema::getStdAlignValT() const {
12186 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12187}
12188
12189NamespaceDecl *Sema::getStdNamespace() const {
12190 return cast_or_null<NamespaceDecl>(
12191 Val: StdNamespace.get(Source: Context.getExternalSource()));
12192}
12193
12194namespace {
12195
12196enum UnsupportedSTLSelect {
12197 USS_InvalidMember,
12198 USS_MissingMember,
12199 USS_NonTrivial,
12200 USS_Other
12201};
12202
12203struct InvalidSTLDiagnoser {
12204 Sema &S;
12205 SourceLocation Loc;
12206 QualType TyForDiags;
12207
12208 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12209 const VarDecl *VD = nullptr) {
12210 {
12211 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12212 << TyForDiags << ((int)Sel);
12213 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12214 assert(!Name.empty());
12215 D << Name;
12216 }
12217 }
12218 if (Sel == USS_InvalidMember) {
12219 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12220 << VD << VD->getSourceRange();
12221 }
12222 return QualType();
12223 }
12224};
12225} // namespace
12226
12227QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12228 SourceLocation Loc,
12229 ComparisonCategoryUsage Usage) {
12230 assert(getLangOpts().CPlusPlus &&
12231 "Looking for comparison category type outside of C++.");
12232
12233 // Use an elaborated type for diagnostics which has a name containing the
12234 // prepended 'std' namespace but not any inline namespace names.
12235 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12236 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12237 /*Prefix=*/std::nullopt);
12238 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12239 TD: Info->Record,
12240 /*OwnsTag=*/false);
12241 };
12242
12243 // Check if we've already successfully checked the comparison category type
12244 // before. If so, skip checking it again.
12245 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12246 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12247 // The only thing we need to check is that the type has a reachable
12248 // definition in the current context.
12249 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12250 return QualType();
12251
12252 return Info->getType();
12253 }
12254
12255 // If lookup failed
12256 if (!Info) {
12257 std::string NameForDiags = "std::";
12258 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12259 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12260 << NameForDiags << (int)Usage;
12261 return QualType();
12262 }
12263
12264 assert(Info->Kind == Kind);
12265 assert(Info->Record);
12266
12267 // Update the Record decl in case we encountered a forward declaration on our
12268 // first pass. FIXME: This is a bit of a hack.
12269 if (Info->Record->hasDefinition())
12270 Info->Record = Info->Record->getDefinition();
12271
12272 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12273 return QualType();
12274
12275 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12276
12277 if (!Info->Record->isTriviallyCopyable())
12278 return UnsupportedSTLError(USS_NonTrivial);
12279
12280 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12281 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12282 // Tolerate empty base classes.
12283 if (Base->isEmpty())
12284 continue;
12285 // Reject STL implementations which have at least one non-empty base.
12286 return UnsupportedSTLError();
12287 }
12288
12289 // Check that the STL has implemented the types using a single integer field.
12290 // This expectation allows better codegen for builtin operators. We require:
12291 // (1) The class has exactly one field.
12292 // (2) The field is an integral or enumeration type.
12293 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12294 if (std::distance(first: FIt, last: FEnd) != 1 ||
12295 !FIt->getType()->isIntegralOrEnumerationType()) {
12296 return UnsupportedSTLError();
12297 }
12298
12299 // Build each of the require values and store them in Info.
12300 for (ComparisonCategoryResult CCR :
12301 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12302 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12303 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12304
12305 if (!ValInfo)
12306 return UnsupportedSTLError(USS_MissingMember, MemName);
12307
12308 VarDecl *VD = ValInfo->VD;
12309 assert(VD && "should not be null!");
12310
12311 // Attempt to diagnose reasons why the STL definition of this type
12312 // might be foobar, including it failing to be a constant expression.
12313 // TODO Handle more ways the lookup or result can be invalid.
12314 if (!VD->isStaticDataMember() ||
12315 !VD->isUsableInConstantExpressions(C: Context))
12316 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12317
12318 // Attempt to evaluate the var decl as a constant expression and extract
12319 // the value of its first field as a ICE. If this fails, the STL
12320 // implementation is not supported.
12321 if (!ValInfo->hasValidIntValue())
12322 return UnsupportedSTLError();
12323
12324 MarkVariableReferenced(Loc, Var: VD);
12325 }
12326
12327 // We've successfully built the required types and expressions. Update
12328 // the cache and return the newly cached value.
12329 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12330 return Info->getType();
12331}
12332
12333NamespaceDecl *Sema::getOrCreateStdNamespace() {
12334 if (!StdNamespace) {
12335 // The "std" namespace has not yet been defined, so build one implicitly.
12336 StdNamespace = NamespaceDecl::Create(
12337 C&: Context, DC: Context.getTranslationUnitDecl(),
12338 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12339 Id: &PP.getIdentifierTable().get(Name: "std"),
12340 /*PrevDecl=*/nullptr, /*Nested=*/false);
12341 getStdNamespace()->setImplicit(true);
12342 // We want the created NamespaceDecl to be available for redeclaration
12343 // lookups, but not for regular name lookups.
12344 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12345 getStdNamespace()->clearIdentifierNamespace();
12346 }
12347
12348 return getStdNamespace();
12349}
12350
12351static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12352 const char *ClassName,
12353 ClassTemplateDecl **CachedDecl,
12354 const Decl **MalformedDecl) {
12355 // We're looking for implicit instantiations of
12356 // template <typename U> class std::{ClassName}.
12357
12358 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12359 // it.
12360 return false;
12361
12362 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12363 if (!MalformedDecl)
12364 return;
12365 if (!D)
12366 D = SugaredType->getAsTagDecl();
12367 if (!D || !D->isInStdNamespace())
12368 return;
12369 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12370 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12371 *MalformedDecl = D;
12372 };
12373
12374 ClassTemplateDecl *Template = nullptr;
12375 ArrayRef<TemplateArgument> Arguments;
12376 if (const TemplateSpecializationType *TST =
12377 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12378 Template = dyn_cast_or_null<ClassTemplateDecl>(
12379 Val: TST->getTemplateName().getAsTemplateDecl());
12380 Arguments = TST->template_arguments();
12381 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12382 Template = TT->getTemplateDecl();
12383 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12384 }
12385
12386 if (!Template) {
12387 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12388 return false;
12389 }
12390
12391 if (!*CachedDecl) {
12392 // Haven't recognized std::{ClassName} yet, maybe this is it.
12393 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12394 // semantics of this are slightly different, most notably the existing
12395 // "lookup" semantics explicitly diagnose an invalid definition as an
12396 // error.
12397 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12398 if (TemplateClass->getIdentifier() !=
12399 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12400 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12401 NS: TemplateClass->getNonTransparentDeclContext()))
12402 return false;
12403 // This is a template called std::{ClassName}, but is it the right
12404 // template?
12405 TemplateParameterList *Params = Template->getTemplateParameters();
12406 if (Params->getMinRequiredArguments() != 1 ||
12407 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12408 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12409 if (MalformedDecl)
12410 *MalformedDecl = TemplateClass;
12411 return false;
12412 }
12413
12414 // It's the right template.
12415 *CachedDecl = Template;
12416 }
12417
12418 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12419 return false;
12420
12421 // This is an instance of std::{ClassName}. Find the argument type.
12422 if (TypeArg) {
12423 QualType ArgType = Arguments[0].getAsType();
12424 // FIXME: Since TST only has as-written arguments, we have to perform the
12425 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12426 // - If an explicitly-specified template argument type is a lifetime type
12427 // with no lifetime qualifier, the __strong lifetime qualifier is
12428 // inferred.
12429 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12430 !ArgType.getObjCLifetime()) {
12431 Qualifiers Qs;
12432 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12433 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12434 }
12435 *TypeArg = ArgType;
12436 }
12437
12438 return true;
12439}
12440
12441bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12442 assert(getLangOpts().CPlusPlus &&
12443 "Looking for std::initializer_list outside of C++.");
12444
12445 // We're looking for implicit instantiations of
12446 // template <typename E> class std::initializer_list.
12447
12448 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12449 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12450}
12451
12452bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12453 const Decl **MalformedDecl) {
12454 assert(getLangOpts().CPlusPlus &&
12455 "Looking for std::type_identity outside of C++.");
12456
12457 // We're looking for implicit instantiations of
12458 // template <typename T> struct std::type_identity.
12459
12460 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12461 CachedDecl: &StdTypeIdentity, MalformedDecl);
12462}
12463
12464static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12465 const char *ClassName,
12466 bool *WasMalformed) {
12467 if (!S.StdNamespace)
12468 return nullptr;
12469
12470 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12471 Sema::LookupOrdinaryName);
12472 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12473 return nullptr;
12474
12475 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12476 if (!Template) {
12477 Result.suppressDiagnostics();
12478 // We found something weird. Complain about the first thing we found.
12479 NamedDecl *Found = *Result.begin();
12480 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12481 << ClassName;
12482 if (WasMalformed)
12483 *WasMalformed = true;
12484 return nullptr;
12485 }
12486
12487 // We found some template with the correct name. Now verify that it's
12488 // correct.
12489 TemplateParameterList *Params = Template->getTemplateParameters();
12490 if (Params->getMinRequiredArguments() != 1 ||
12491 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12492 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12493 << ClassName;
12494 if (WasMalformed)
12495 *WasMalformed = true;
12496 return nullptr;
12497 }
12498
12499 return Template;
12500}
12501
12502static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12503 QualType TypeParam, SourceLocation Loc) {
12504 assert(S.getStdNamespace());
12505 TemplateArgumentListInfo Args(Loc, Loc);
12506 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12507 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12508
12509 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12510 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12511 /*ForNestedNameSpecifier=*/false);
12512}
12513
12514QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12515 if (!StdInitializerList) {
12516 bool WasMalformed = false;
12517 StdInitializerList =
12518 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12519 if (!StdInitializerList) {
12520 if (!WasMalformed)
12521 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12522 return QualType();
12523 }
12524 }
12525 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12526}
12527
12528QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12529 if (!StdTypeIdentity) {
12530 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12531 /*WasMalformed=*/nullptr);
12532 if (!StdTypeIdentity)
12533 return QualType();
12534 }
12535 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12536}
12537
12538bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12539 // C++ [dcl.init.list]p2:
12540 // A constructor is an initializer-list constructor if its first parameter
12541 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12542 // std::initializer_list<E> for some type E, and either there are no other
12543 // parameters or else all other parameters have default arguments.
12544 if (!Ctor->hasOneParamOrDefaultArgs())
12545 return false;
12546
12547 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12548 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12549 ArgType = RT->getPointeeType().getUnqualifiedType();
12550
12551 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12552}
12553
12554/// Determine whether a using statement is in a context where it will be
12555/// apply in all contexts.
12556static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12557 switch (CurContext->getDeclKind()) {
12558 case Decl::TranslationUnit:
12559 return true;
12560 case Decl::LinkageSpec:
12561 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12562 default:
12563 return false;
12564 }
12565}
12566
12567namespace {
12568
12569// Callback to only accept typo corrections that are namespaces.
12570class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12571public:
12572 bool ValidateCandidate(const TypoCorrection &candidate) override {
12573 if (NamedDecl *ND = candidate.getCorrectionDecl())
12574 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12575 return false;
12576 }
12577
12578 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12579 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12580 }
12581};
12582
12583}
12584
12585static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12586 Sema &S) {
12587 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12588 Module *M = ND->getOwningModule();
12589 assert(M && "hidden namespace definition not in a module?");
12590
12591 if (M->isExplicitGlobalModule())
12592 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12593 DiagID: diag::err_module_unimported_use_header)
12594 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12595 << /*Header Name*/ false;
12596 else
12597 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12598 DiagID: diag::err_module_unimported_use)
12599 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12600 << M->getTopLevelModuleName();
12601}
12602
12603static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12604 CXXScopeSpec &SS,
12605 SourceLocation IdentLoc,
12606 IdentifierInfo *Ident) {
12607 R.clear();
12608 NamespaceValidatorCCC CCC{};
12609 if (TypoCorrection Corrected =
12610 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12611 Mode: CorrectTypoKind::ErrorRecovery)) {
12612 // Generally we find it is confusing more than helpful to diagnose the
12613 // invisible namespace.
12614 // See https://github.com/llvm/llvm-project/issues/73893.
12615 //
12616 // However, we should diagnose when the users are trying to using an
12617 // invisible namespace. So we handle the case specially here.
12618 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12619 Corrected.requiresImport()) {
12620 DiagnoseInvisibleNamespace(Corrected, S);
12621 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12622 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12623 bool DroppedSpecifier =
12624 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12625 S.diagnoseTypo(Correction: Corrected,
12626 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12627 << Ident << DC << DroppedSpecifier << SS.getRange(),
12628 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12629 } else {
12630 S.diagnoseTypo(Correction: Corrected,
12631 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12632 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12633 }
12634 R.addDecl(D: Corrected.getFoundDecl());
12635 return true;
12636 }
12637 return false;
12638}
12639
12640Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12641 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12642 SourceLocation IdentLoc,
12643 IdentifierInfo *NamespcName,
12644 const ParsedAttributesView &AttrList) {
12645 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12646 assert(NamespcName && "Invalid NamespcName.");
12647 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12648
12649 // Get the innermost enclosing declaration scope.
12650 S = S->getDeclParent();
12651
12652 UsingDirectiveDecl *UDir = nullptr;
12653 NestedNameSpecifier Qualifier = SS.getScopeRep();
12654
12655 // Lookup namespace name.
12656 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12657 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12658 if (R.isAmbiguous())
12659 return nullptr;
12660
12661 if (R.empty()) {
12662 R.clear();
12663 // Allow "using namespace std;" or "using namespace ::std;" even if
12664 // "std" hasn't been defined yet, for GCC compatibility.
12665 if ((!Qualifier ||
12666 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12667 NamespcName->isStr(Str: "std")) {
12668 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12669 R.addDecl(D: getOrCreateStdNamespace());
12670 R.resolveKind();
12671 }
12672 // Otherwise, attempt typo correction.
12673 else
12674 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12675 }
12676
12677 if (!R.empty()) {
12678 NamedDecl *Named = R.getRepresentativeDecl();
12679 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12680 assert(NS && "expected namespace decl");
12681
12682 // The use of a nested name specifier may trigger deprecation warnings.
12683 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12684
12685 // C++ [namespace.udir]p1:
12686 // A using-directive specifies that the names in the nominated
12687 // namespace can be used in the scope in which the
12688 // using-directive appears after the using-directive. During
12689 // unqualified name lookup (3.4.1), the names appear as if they
12690 // were declared in the nearest enclosing namespace which
12691 // contains both the using-directive and the nominated
12692 // namespace. [Note: in this context, "contains" means "contains
12693 // directly or indirectly". ]
12694
12695 // Find enclosing context containing both using-directive and
12696 // nominated namespace.
12697 DeclContext *CommonAncestor = NS;
12698 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12699 CommonAncestor = CommonAncestor->getParent();
12700
12701 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12702 QualifierLoc: SS.getWithLocInContext(Context),
12703 IdentLoc, Nominated: Named, CommonAncestor);
12704
12705 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12706 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12707 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12708 }
12709
12710 PushUsingDirective(S, UDir);
12711 } else {
12712 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12713 }
12714
12715 if (UDir) {
12716 ProcessDeclAttributeList(S, D: UDir, AttrList);
12717 ProcessAPINotes(D: UDir);
12718 }
12719
12720 return UDir;
12721}
12722
12723void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12724 // If the scope has an associated entity and the using directive is at
12725 // namespace or translation unit scope, add the UsingDirectiveDecl into
12726 // its lookup structure so qualified name lookup can find it.
12727 DeclContext *Ctx = S->getEntity();
12728 if (Ctx && !Ctx->isFunctionOrMethod())
12729 Ctx->addDecl(D: UDir);
12730 else
12731 // Otherwise, it is at block scope. The using-directives will affect lookup
12732 // only to the end of the scope.
12733 S->PushUsingDirective(UDir);
12734}
12735
12736Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12737 SourceLocation UsingLoc,
12738 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12739 UnqualifiedId &Name,
12740 SourceLocation EllipsisLoc,
12741 const ParsedAttributesView &AttrList) {
12742 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12743
12744 if (SS.isEmpty()) {
12745 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12746 return nullptr;
12747 }
12748
12749 switch (Name.getKind()) {
12750 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12751 case UnqualifiedIdKind::IK_Identifier:
12752 case UnqualifiedIdKind::IK_OperatorFunctionId:
12753 case UnqualifiedIdKind::IK_LiteralOperatorId:
12754 case UnqualifiedIdKind::IK_ConversionFunctionId:
12755 break;
12756
12757 case UnqualifiedIdKind::IK_ConstructorName:
12758 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12759 // C++11 inheriting constructors.
12760 Diag(Loc: Name.getBeginLoc(),
12761 DiagID: getLangOpts().CPlusPlus11
12762 ? diag::warn_cxx98_compat_using_decl_constructor
12763 : diag::err_using_decl_constructor)
12764 << SS.getRange();
12765
12766 if (getLangOpts().CPlusPlus11) break;
12767
12768 return nullptr;
12769
12770 case UnqualifiedIdKind::IK_DestructorName:
12771 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12772 return nullptr;
12773
12774 case UnqualifiedIdKind::IK_TemplateId:
12775 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12776 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12777 return nullptr;
12778
12779 case UnqualifiedIdKind::IK_DeductionGuideName:
12780 llvm_unreachable("cannot parse qualified deduction guide name");
12781 }
12782
12783 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12784 DeclarationName TargetName = TargetNameInfo.getName();
12785 if (!TargetName)
12786 return nullptr;
12787
12788 // Warn about access declarations.
12789 if (UsingLoc.isInvalid()) {
12790 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12791 ? diag::err_access_decl
12792 : diag::warn_access_decl_deprecated)
12793 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12794 }
12795
12796 if (EllipsisLoc.isInvalid()) {
12797 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12798 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12799 return nullptr;
12800 } else {
12801 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12802 !TargetNameInfo.containsUnexpandedParameterPack()) {
12803 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12804 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12805 EllipsisLoc = SourceLocation();
12806 }
12807 }
12808
12809 NamedDecl *UD =
12810 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12811 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12812 /*IsInstantiation*/ false,
12813 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12814 if (UD)
12815 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12816
12817 return UD;
12818}
12819
12820Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12821 SourceLocation UsingLoc,
12822 SourceLocation EnumLoc, SourceRange TyLoc,
12823 const IdentifierInfo &II, ParsedType Ty,
12824 const CXXScopeSpec &SS) {
12825 TypeSourceInfo *TSI = nullptr;
12826 SourceLocation IdentLoc = TyLoc.getBegin();
12827 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12828 if (EnumTy.isNull()) {
12829 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12830 ? diag::err_using_enum_is_dependent
12831 : diag::err_unknown_typename)
12832 << II.getName()
12833 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12834 TyLoc.getEnd());
12835 return nullptr;
12836 }
12837
12838 if (EnumTy->isDependentType()) {
12839 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12840 return nullptr;
12841 }
12842
12843 auto *Enum = EnumTy->getAsEnumDecl();
12844 if (!Enum) {
12845 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12846 return nullptr;
12847 }
12848
12849 if (TSI == nullptr)
12850 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12851
12852 auto *UD =
12853 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12854
12855 if (UD)
12856 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12857
12858 return UD;
12859}
12860
12861/// Determine whether a using declaration considers the given
12862/// declarations as "equivalent", e.g., if they are redeclarations of
12863/// the same entity or are both typedefs of the same type.
12864static bool
12865IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12866 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12867 return true;
12868
12869 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12870 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12871 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12872 T2: TD2->getUnderlyingType());
12873
12874 // Two using_if_exists using-declarations are equivalent if both are
12875 // unresolved.
12876 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12877 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12878 return true;
12879
12880 return false;
12881}
12882
12883bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12884 const LookupResult &Previous,
12885 UsingShadowDecl *&PrevShadow) {
12886 // Diagnose finding a decl which is not from a base class of the
12887 // current class. We do this now because there are cases where this
12888 // function will silently decide not to build a shadow decl, which
12889 // will pre-empt further diagnostics.
12890 //
12891 // We don't need to do this in C++11 because we do the check once on
12892 // the qualifier.
12893 //
12894 // FIXME: diagnose the following if we care enough:
12895 // struct A { int foo; };
12896 // struct B : A { using A::foo; };
12897 // template <class T> struct C : A {};
12898 // template <class T> struct D : C<T> { using B::foo; } // <---
12899 // This is invalid (during instantiation) in C++03 because B::foo
12900 // resolves to the using decl in B, which is not a base class of D<T>.
12901 // We can't diagnose it immediately because C<T> is an unknown
12902 // specialization. The UsingShadowDecl in D<T> then points directly
12903 // to A::foo, which will look well-formed when we instantiate.
12904 // The right solution is to not collapse the shadow-decl chain.
12905 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12906 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12907 DeclContext *OrigDC = Orig->getDeclContext();
12908
12909 // Handle enums and anonymous structs.
12910 if (isa<EnumDecl>(Val: OrigDC))
12911 OrigDC = OrigDC->getParent();
12912 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12913 while (OrigRec->isAnonymousStructOrUnion())
12914 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12915
12916 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12917 if (OrigDC == CurContext) {
12918 Diag(Loc: Using->getLocation(),
12919 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12920 << Using->getQualifierLoc().getSourceRange();
12921 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12922 Using->setInvalidDecl();
12923 return true;
12924 }
12925
12926 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12927 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12928 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12929 << Using->getQualifierLoc().getSourceRange();
12930 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12931 Using->setInvalidDecl();
12932 return true;
12933 }
12934 }
12935
12936 if (Previous.empty()) return false;
12937
12938 NamedDecl *Target = Orig;
12939 if (isa<UsingShadowDecl>(Val: Target))
12940 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12941
12942 // If the target happens to be one of the previous declarations, we
12943 // don't have a conflict.
12944 //
12945 // FIXME: but we might be increasing its access, in which case we
12946 // should redeclare it.
12947 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12948 bool FoundEquivalentDecl = false;
12949 for (NamedDecl *Element : Previous) {
12950 NamedDecl *D = Element->getUnderlyingDecl();
12951 // We can have UsingDecls in our Previous results because we use the same
12952 // LookupResult for checking whether the UsingDecl itself is a valid
12953 // redeclaration.
12954 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12955 continue;
12956
12957 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12958 // C++ [class.mem]p19:
12959 // If T is the name of a class, then [every named member other than
12960 // a non-static data member] shall have a name different from T
12961 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12962 !isa<IndirectFieldDecl>(Val: Target) &&
12963 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12964 DiagnoseClassNameShadow(
12965 DC: CurContext,
12966 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12967 return true;
12968 }
12969
12970 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12971 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12972 PrevShadow = Shadow;
12973 FoundEquivalentDecl = true;
12974 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12975 // We don't conflict with an existing using shadow decl of an equivalent
12976 // declaration, but we're not a redeclaration of it.
12977 FoundEquivalentDecl = true;
12978 }
12979
12980 if (isVisible(D))
12981 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12982 }
12983
12984 if (FoundEquivalentDecl)
12985 return false;
12986
12987 // Always emit a diagnostic for a mismatch between an unresolved
12988 // using_if_exists and a resolved using declaration in either direction.
12989 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12990 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12991 if (!NonTag && !Tag)
12992 return false;
12993 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12994 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12995 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
12996 DiagID: diag::note_using_decl_conflict);
12997 BUD->setInvalidDecl();
12998 return true;
12999 }
13000
13001 if (FunctionDecl *FD = Target->getAsFunction()) {
13002 NamedDecl *OldDecl = nullptr;
13003 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
13004 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
13005 case OverloadKind::Overload:
13006 return false;
13007
13008 case OverloadKind::NonFunction:
13009 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13010 break;
13011
13012 // We found a decl with the exact signature.
13013 case OverloadKind::Match:
13014 // If we're in a record, we want to hide the target, so we
13015 // return true (without a diagnostic) to tell the caller not to
13016 // build a shadow decl.
13017 if (CurContext->isRecord())
13018 return true;
13019
13020 // If we're not in a record, this is an error.
13021 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13022 break;
13023 }
13024
13025 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13026 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
13027 BUD->setInvalidDecl();
13028 return true;
13029 }
13030
13031 // Target is not a function.
13032
13033 if (isa<TagDecl>(Val: Target)) {
13034 // No conflict between a tag and a non-tag.
13035 if (!Tag) return false;
13036
13037 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13038 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13039 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
13040 BUD->setInvalidDecl();
13041 return true;
13042 }
13043
13044 // No conflict between a tag and a non-tag.
13045 if (!NonTag) return false;
13046
13047 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13048 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13049 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13050 BUD->setInvalidDecl();
13051 return true;
13052}
13053
13054/// Determine whether a direct base class is a virtual base class.
13055static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13056 if (!Derived->getNumVBases())
13057 return false;
13058 for (auto &B : Derived->bases())
13059 if (B.getType()->getAsCXXRecordDecl() == Base)
13060 return B.isVirtual();
13061 llvm_unreachable("not a direct base class");
13062}
13063
13064UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13065 NamedDecl *Orig,
13066 UsingShadowDecl *PrevDecl) {
13067 // If we resolved to another shadow declaration, just coalesce them.
13068 NamedDecl *Target = Orig;
13069 if (isa<UsingShadowDecl>(Val: Target)) {
13070 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13071 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13072 }
13073
13074 NamedDecl *NonTemplateTarget = Target;
13075 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13076 NonTemplateTarget = TargetTD->getTemplatedDecl();
13077
13078 UsingShadowDecl *Shadow;
13079 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13080 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13081 bool IsVirtualBase =
13082 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13083 Base: Using->getQualifier().getAsRecordDecl());
13084 Shadow = ConstructorUsingShadowDecl::Create(
13085 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13086 } else {
13087 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13088 Name: Target->getDeclName(), Introducer: BUD, Target);
13089 }
13090 BUD->addShadowDecl(S: Shadow);
13091
13092 Shadow->setAccess(BUD->getAccess());
13093 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13094 Shadow->setInvalidDecl();
13095
13096 Shadow->setPreviousDecl(PrevDecl);
13097
13098 if (S)
13099 PushOnScopeChains(D: Shadow, S);
13100 else
13101 CurContext->addDecl(D: Shadow);
13102
13103
13104 return Shadow;
13105}
13106
13107void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13108 if (Shadow->getDeclName().getNameKind() ==
13109 DeclarationName::CXXConversionFunctionName)
13110 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13111
13112 // Remove it from the DeclContext...
13113 Shadow->getDeclContext()->removeDecl(D: Shadow);
13114
13115 // ...and the scope, if applicable...
13116 if (S) {
13117 S->RemoveDecl(D: Shadow);
13118 IdResolver.RemoveDecl(D: Shadow);
13119 }
13120
13121 // ...and the using decl.
13122 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13123
13124 // TODO: complain somehow if Shadow was used. It shouldn't
13125 // be possible for this to happen, because...?
13126}
13127
13128/// Find the base specifier for a base class with the given type.
13129static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13130 QualType DesiredBase,
13131 bool &AnyDependentBases) {
13132 // Check whether the named type is a direct base class.
13133 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13134 for (auto &Base : Derived->bases()) {
13135 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13136 if (CanonicalDesiredBase == BaseType)
13137 return &Base;
13138 if (BaseType->isDependentType())
13139 AnyDependentBases = true;
13140 }
13141 return nullptr;
13142}
13143
13144namespace {
13145class UsingValidatorCCC final : public CorrectionCandidateCallback {
13146public:
13147 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13148 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13149 : HasTypenameKeyword(HasTypenameKeyword),
13150 IsInstantiation(IsInstantiation), OldNNS(NNS),
13151 RequireMemberOf(RequireMemberOf) {}
13152
13153 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13154 NamedDecl *ND = Candidate.getCorrectionDecl();
13155
13156 // Keywords are not valid here.
13157 if (!ND || isa<NamespaceDecl>(Val: ND))
13158 return false;
13159
13160 // Completely unqualified names are invalid for a 'using' declaration.
13161 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13162 return false;
13163
13164 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13165 // reject.
13166
13167 if (RequireMemberOf) {
13168 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13169 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13170 // No-one ever wants a using-declaration to name an injected-class-name
13171 // of a base class, unless they're declaring an inheriting constructor.
13172 ASTContext &Ctx = ND->getASTContext();
13173 if (!Ctx.getLangOpts().CPlusPlus11)
13174 return false;
13175 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13176
13177 // Check that the injected-class-name is named as a member of its own
13178 // type; we don't want to suggest 'using Derived::Base;', since that
13179 // means something else.
13180 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13181 ? Candidate.getCorrectionSpecifier()
13182 : OldNNS;
13183 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13184 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13185 return false;
13186
13187 // Check that this inheriting constructor declaration actually names a
13188 // direct base class of the current class.
13189 bool AnyDependentBases = false;
13190 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13191 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13192 AnyDependentBases) &&
13193 !AnyDependentBases)
13194 return false;
13195 } else {
13196 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13197 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13198 return false;
13199
13200 // FIXME: Check that the base class member is accessible?
13201 }
13202 } else {
13203 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13204 if (FoundRecord && FoundRecord->isInjectedClassName())
13205 return false;
13206 }
13207
13208 if (isa<TypeDecl>(Val: ND))
13209 return HasTypenameKeyword || !IsInstantiation;
13210
13211 return !HasTypenameKeyword;
13212 }
13213
13214 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13215 return std::make_unique<UsingValidatorCCC>(args&: *this);
13216 }
13217
13218private:
13219 bool HasTypenameKeyword;
13220 bool IsInstantiation;
13221 NestedNameSpecifier OldNNS;
13222 CXXRecordDecl *RequireMemberOf;
13223};
13224} // end anonymous namespace
13225
13226void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13227 // It is really dumb that we have to do this.
13228 LookupResult::Filter F = Previous.makeFilter();
13229 while (F.hasNext()) {
13230 NamedDecl *D = F.next();
13231 if (!isDeclInScope(D, Ctx: CurContext, S))
13232 F.erase();
13233 // If we found a local extern declaration that's not ordinarily visible,
13234 // and this declaration is being added to a non-block scope, ignore it.
13235 // We're only checking for scope conflicts here, not also for violations
13236 // of the linkage rules.
13237 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13238 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13239 F.erase();
13240 }
13241 F.done();
13242}
13243
13244NamedDecl *Sema::BuildUsingDeclaration(
13245 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13246 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13247 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13248 const ParsedAttributesView &AttrList, bool IsInstantiation,
13249 bool IsUsingIfExists) {
13250 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13251 SourceLocation IdentLoc = NameInfo.getLoc();
13252 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13253
13254 // FIXME: We ignore attributes for now.
13255
13256 // For an inheriting constructor declaration, the name of the using
13257 // declaration is the name of a constructor in this class, not in the
13258 // base class.
13259 DeclarationNameInfo UsingName = NameInfo;
13260 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13261 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13262 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13263 Ty: Context.getCanonicalTagType(TD: RD)));
13264
13265 // Do the redeclaration lookup in the current scope.
13266 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13267 RedeclarationKind::ForVisibleRedeclaration);
13268 Previous.setHideTags(false);
13269 if (S) {
13270 LookupName(R&: Previous, S);
13271
13272 FilterUsingLookup(S, Previous);
13273 } else {
13274 assert(IsInstantiation && "no scope in non-instantiation");
13275 if (CurContext->isRecord())
13276 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13277 else {
13278 // No redeclaration check is needed here; in non-member contexts we
13279 // diagnosed all possible conflicts with other using-declarations when
13280 // building the template:
13281 //
13282 // For a dependent non-type using declaration, the only valid case is
13283 // if we instantiate to a single enumerator. We check for conflicts
13284 // between shadow declarations we introduce, and we check in the template
13285 // definition for conflicts between a non-type using declaration and any
13286 // other declaration, which together covers all cases.
13287 //
13288 // A dependent typename using declaration will never successfully
13289 // instantiate, since it will always name a class member, so we reject
13290 // that in the template definition.
13291 }
13292 }
13293
13294 // Check for invalid redeclarations.
13295 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13296 SS, NameLoc: IdentLoc, Previous))
13297 return nullptr;
13298
13299 // 'using_if_exists' doesn't make sense on an inherited constructor.
13300 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13301 DeclarationName::CXXConstructorName) {
13302 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13303 return nullptr;
13304 }
13305
13306 DeclContext *LookupContext = computeDeclContext(SS);
13307 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13308 if (!LookupContext || EllipsisLoc.isValid()) {
13309 NamedDecl *D;
13310 // Dependent scope, or an unexpanded pack
13311 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13312 SS, NameInfo, NameLoc: IdentLoc))
13313 return nullptr;
13314
13315 if (Previous.isSingleResult() &&
13316 Previous.getFoundDecl()->isTemplateParameter())
13317 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13318
13319 if (HasTypenameKeyword) {
13320 // FIXME: not all declaration name kinds are legal here
13321 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13322 UsingLoc, TypenameLoc,
13323 QualifierLoc,
13324 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13325 EllipsisLoc);
13326 } else {
13327 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13328 QualifierLoc, NameInfo, EllipsisLoc);
13329 }
13330 D->setAccess(AS);
13331 CurContext->addDecl(D);
13332 ProcessDeclAttributeList(S, D, AttrList);
13333 return D;
13334 }
13335
13336 auto Build = [&](bool Invalid) {
13337 UsingDecl *UD =
13338 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13339 NameInfo: UsingName, HasTypenameKeyword);
13340 UD->setAccess(AS);
13341 CurContext->addDecl(D: UD);
13342 ProcessDeclAttributeList(S, D: UD, AttrList);
13343 UD->setInvalidDecl(Invalid);
13344 return UD;
13345 };
13346 auto BuildInvalid = [&]{ return Build(true); };
13347 auto BuildValid = [&]{ return Build(false); };
13348
13349 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13350 return BuildInvalid();
13351
13352 // Look up the target name.
13353 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13354
13355 // Unlike most lookups, we don't always want to hide tag
13356 // declarations: tag names are visible through the using declaration
13357 // even if hidden by ordinary names, *except* in a dependent context
13358 // where they may be used by two-phase lookup.
13359 if (!IsInstantiation)
13360 R.setHideTags(false);
13361
13362 // For the purposes of this lookup, we have a base object type
13363 // equal to that of the current context.
13364 if (CurContext->isRecord()) {
13365 R.setBaseObjectType(
13366 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13367 }
13368
13369 LookupQualifiedName(R, LookupCtx: LookupContext);
13370
13371 // Validate the context, now we have a lookup
13372 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13373 NameLoc: IdentLoc, R: &R))
13374 return nullptr;
13375
13376 if (R.empty() && IsUsingIfExists)
13377 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13378 Name: UsingName.getName()),
13379 AS: AS_public);
13380
13381 // Try to correct typos if possible. If constructor name lookup finds no
13382 // results, that means the named class has no explicit constructors, and we
13383 // suppressed declaring implicit ones (probably because it's dependent or
13384 // invalid).
13385 if (R.empty() &&
13386 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13387 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13388 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13389 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13390 auto *II = NameInfo.getName().getAsIdentifierInfo();
13391 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13392 CurContext->isStdNamespace() &&
13393 isa<TranslationUnitDecl>(Val: LookupContext) &&
13394 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13395 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13396 return nullptr;
13397 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13398 dyn_cast<CXXRecordDecl>(Val: CurContext));
13399 if (TypoCorrection Corrected =
13400 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13401 Mode: CorrectTypoKind::ErrorRecovery)) {
13402 // We reject candidates where DroppedSpecifier == true, hence the
13403 // literal '0' below.
13404 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13405 << NameInfo.getName() << LookupContext << 0
13406 << SS.getRange());
13407
13408 // If we picked a correction with no attached Decl we can't do anything
13409 // useful with it, bail out.
13410 NamedDecl *ND = Corrected.getCorrectionDecl();
13411 if (!ND)
13412 return BuildInvalid();
13413
13414 // If we corrected to an inheriting constructor, handle it as one.
13415 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13416 if (RD && RD->isInjectedClassName()) {
13417 // The parent of the injected class name is the class itself.
13418 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13419
13420 // Fix up the information we'll use to build the using declaration.
13421 if (Corrected.WillReplaceSpecifier()) {
13422 NestedNameSpecifierLocBuilder Builder;
13423 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13424 R: QualifierLoc.getSourceRange());
13425 QualifierLoc = Builder.getWithLocInContext(Context);
13426 }
13427
13428 // In this case, the name we introduce is the name of a derived class
13429 // constructor.
13430 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13431 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13432 Ty: Context.getCanonicalTagType(TD: CurClass)));
13433 UsingName.setNamedTypeInfo(nullptr);
13434 for (auto *Ctor : LookupConstructors(Class: RD))
13435 R.addDecl(D: Ctor);
13436 R.resolveKind();
13437 } else {
13438 // FIXME: Pick up all the declarations if we found an overloaded
13439 // function.
13440 UsingName.setName(ND->getDeclName());
13441 R.addDecl(D: ND);
13442 }
13443 } else {
13444 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13445 << NameInfo.getName() << LookupContext << SS.getRange();
13446 return BuildInvalid();
13447 }
13448 }
13449
13450 if (R.isAmbiguous())
13451 return BuildInvalid();
13452
13453 if (HasTypenameKeyword) {
13454 // If we asked for a typename and got a non-type decl, error out.
13455 if (!R.getAsSingle<TypeDecl>() &&
13456 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13457 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13458 for (const NamedDecl *D : R)
13459 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13460 DiagID: diag::note_using_decl_target);
13461 return BuildInvalid();
13462 }
13463 } else {
13464 // If we asked for a non-typename and we got a type, error out,
13465 // but only if this is an instantiation of an unresolved using
13466 // decl. Otherwise just silently find the type name.
13467 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13468 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13469 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13470 return BuildInvalid();
13471 }
13472 }
13473
13474 // C++14 [namespace.udecl]p6:
13475 // A using-declaration shall not name a namespace.
13476 if (R.getAsSingle<NamespaceDecl>()) {
13477 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13478 << SS.getRange();
13479 // Suggest using 'using namespace ...' instead.
13480 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13481 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13482 return BuildInvalid();
13483 }
13484
13485 UsingDecl *UD = BuildValid();
13486
13487 // Some additional rules apply to inheriting constructors.
13488 if (UsingName.getName().getNameKind() ==
13489 DeclarationName::CXXConstructorName) {
13490 // Suppress access diagnostics; the access check is instead performed at the
13491 // point of use for an inheriting constructor.
13492 R.suppressDiagnostics();
13493 if (CheckInheritingConstructorUsingDecl(UD))
13494 return UD;
13495 }
13496
13497 for (NamedDecl *D : R) {
13498 UsingShadowDecl *PrevDecl = nullptr;
13499 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13500 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13501 }
13502
13503 return UD;
13504}
13505
13506NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13507 SourceLocation UsingLoc,
13508 SourceLocation EnumLoc,
13509 SourceLocation NameLoc,
13510 TypeSourceInfo *EnumType,
13511 EnumDecl *ED) {
13512 bool Invalid = false;
13513
13514 if (CurContext->getRedeclContext()->isRecord()) {
13515 /// In class scope, check if this is a duplicate, for better a diagnostic.
13516 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13517 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13518 RedeclarationKind::ForVisibleRedeclaration);
13519
13520 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13521
13522 for (NamedDecl *D : Previous)
13523 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13524 if (UED->getEnumDecl() == ED) {
13525 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13526 << SourceRange(EnumLoc, NameLoc);
13527 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13528 Invalid = true;
13529 break;
13530 }
13531 }
13532
13533 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13534 Invalid = true;
13535
13536 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13537 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13538 UD->setAccess(AS);
13539 CurContext->addDecl(D: UD);
13540
13541 if (Invalid) {
13542 UD->setInvalidDecl();
13543 return UD;
13544 }
13545
13546 // Create the shadow decls for each enumerator
13547 for (EnumConstantDecl *EC : ED->enumerators()) {
13548 UsingShadowDecl *PrevDecl = nullptr;
13549 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13550 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13551 RedeclarationKind::ForVisibleRedeclaration);
13552 LookupName(R&: Previous, S);
13553 FilterUsingLookup(S, Previous);
13554
13555 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13556 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13557 }
13558
13559 return UD;
13560}
13561
13562NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13563 ArrayRef<NamedDecl *> Expansions) {
13564 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13565 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13566 isa<UsingPackDecl>(InstantiatedFrom));
13567
13568 auto *UPD =
13569 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13570 UPD->setAccess(InstantiatedFrom->getAccess());
13571 CurContext->addDecl(D: UPD);
13572 return UPD;
13573}
13574
13575bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13576 assert(!UD->hasTypename() && "expecting a constructor name");
13577
13578 QualType SourceType(UD->getQualifier().getAsType(), 0);
13579 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13580
13581 // Check whether the named type is a direct base class.
13582 bool AnyDependentBases = false;
13583 auto *Base =
13584 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13585 if (!Base && !AnyDependentBases) {
13586 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13587 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13588 UD->setInvalidDecl();
13589 return true;
13590 }
13591
13592 if (Base)
13593 Base->setInheritConstructors();
13594
13595 return false;
13596}
13597
13598bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13599 bool HasTypenameKeyword,
13600 const CXXScopeSpec &SS,
13601 SourceLocation NameLoc,
13602 const LookupResult &Prev) {
13603 NestedNameSpecifier Qual = SS.getScopeRep();
13604
13605 // C++03 [namespace.udecl]p8:
13606 // C++0x [namespace.udecl]p10:
13607 // A using-declaration is a declaration and can therefore be used
13608 // repeatedly where (and only where) multiple declarations are
13609 // allowed.
13610 //
13611 // That's in non-member contexts.
13612 if (!CurContext->getRedeclContext()->isRecord()) {
13613 // A dependent qualifier outside a class can only ever resolve to an
13614 // enumeration type. Therefore it conflicts with any other non-type
13615 // declaration in the same scope.
13616 // FIXME: How should we check for dependent type-type conflicts at block
13617 // scope?
13618 if (Qual.isDependent() && !HasTypenameKeyword) {
13619 for (auto *D : Prev) {
13620 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13621 bool OldCouldBeEnumerator =
13622 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13623 Diag(Loc: NameLoc,
13624 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13625 : diag::err_redefinition_different_kind)
13626 << Prev.getLookupName();
13627 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13628 return true;
13629 }
13630 }
13631 }
13632 return false;
13633 }
13634
13635 NestedNameSpecifier CNNS = Qual.getCanonical();
13636 for (const NamedDecl *D : Prev) {
13637 bool DTypename;
13638 NestedNameSpecifier DQual = std::nullopt;
13639 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13640 DTypename = UD->hasTypename();
13641 DQual = UD->getQualifier();
13642 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13643 DTypename = false;
13644 DQual = UD->getQualifier();
13645 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13646 DTypename = true;
13647 DQual = UD->getQualifier();
13648 } else
13649 continue;
13650
13651 // using decls differ if one says 'typename' and the other doesn't.
13652 // FIXME: non-dependent using decls?
13653 if (HasTypenameKeyword != DTypename) continue;
13654
13655 // using decls differ if they name different scopes (but note that
13656 // template instantiation can cause this check to trigger when it
13657 // didn't before instantiation).
13658 if (CNNS != DQual.getCanonical())
13659 continue;
13660
13661 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13662 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13663 return true;
13664 }
13665
13666 return false;
13667}
13668
13669bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13670 const CXXScopeSpec &SS,
13671 const DeclarationNameInfo &NameInfo,
13672 SourceLocation NameLoc,
13673 const LookupResult *R, const UsingDecl *UD) {
13674 DeclContext *NamedContext = computeDeclContext(SS);
13675 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13676 "resolvable context must have exactly one set of decls");
13677
13678 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13679 // relationship.
13680 bool Cxx20Enumerator = false;
13681 if (NamedContext) {
13682 EnumConstantDecl *EC = nullptr;
13683 if (R)
13684 EC = R->getAsSingle<EnumConstantDecl>();
13685 else if (UD && UD->shadow_size() == 1)
13686 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13687 if (EC)
13688 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13689
13690 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13691 // C++14 [namespace.udecl]p7:
13692 // A using-declaration shall not name a scoped enumerator.
13693 // C++20 p1099 permits enumerators.
13694 if (EC && R && ED->isScoped())
13695 Diag(Loc: SS.getBeginLoc(),
13696 DiagID: getLangOpts().CPlusPlus20
13697 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13698 : diag::ext_using_decl_scoped_enumerator)
13699 << SS.getRange();
13700
13701 // We want to consider the scope of the enumerator
13702 NamedContext = ED->getDeclContext();
13703 }
13704 }
13705
13706 if (!CurContext->isRecord()) {
13707 // C++03 [namespace.udecl]p3:
13708 // C++0x [namespace.udecl]p8:
13709 // A using-declaration for a class member shall be a member-declaration.
13710 // C++20 [namespace.udecl]p7
13711 // ... other than an enumerator ...
13712
13713 // If we weren't able to compute a valid scope, it might validly be a
13714 // dependent class or enumeration scope. If we have a 'typename' keyword,
13715 // the scope must resolve to a class type.
13716 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13717 : !HasTypename)
13718 return false; // OK
13719
13720 Diag(Loc: NameLoc,
13721 DiagID: Cxx20Enumerator
13722 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13723 : diag::err_using_decl_can_not_refer_to_class_member)
13724 << SS.getRange();
13725
13726 if (Cxx20Enumerator)
13727 return false; // OK
13728
13729 auto *RD = NamedContext
13730 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13731 : nullptr;
13732 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13733 // See if there's a helpful fixit
13734
13735 if (!R) {
13736 // We will have already diagnosed the problem on the template
13737 // definition, Maybe we should do so again?
13738 } else if (R->getAsSingle<TypeDecl>()) {
13739 if (getLangOpts().CPlusPlus11) {
13740 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13741 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13742 << diag::MemClassWorkaround::AliasDecl
13743 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13744 Code: NameInfo.getName().getAsString() +
13745 " = ");
13746 } else {
13747 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13748 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13749 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13750 << diag::MemClassWorkaround::TypedefDecl
13751 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13752 << FixItHint::CreateInsertion(
13753 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13754 }
13755 } else if (R->getAsSingle<VarDecl>()) {
13756 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13757 // repeating the type of the static data member here.
13758 FixItHint FixIt;
13759 if (getLangOpts().CPlusPlus11) {
13760 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13761 FixIt = FixItHint::CreateReplacement(
13762 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13763 }
13764
13765 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13766 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13767 } else if (R->getAsSingle<EnumConstantDecl>()) {
13768 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13769 // repeating the type of the enumeration here, and we can't do so if
13770 // the type is anonymous.
13771 FixItHint FixIt;
13772 if (getLangOpts().CPlusPlus11) {
13773 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13774 FixIt = FixItHint::CreateReplacement(
13775 RemoveRange: UsingLoc,
13776 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13777 }
13778
13779 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13780 << (getLangOpts().CPlusPlus11
13781 ? diag::MemClassWorkaround::ConstexprVar
13782 : diag::MemClassWorkaround::ConstVar)
13783 << FixIt;
13784 }
13785 }
13786
13787 return true; // Fail
13788 }
13789
13790 // If the named context is dependent, we can't decide much.
13791 if (!NamedContext) {
13792 // FIXME: in C++0x, we can diagnose if we can prove that the
13793 // nested-name-specifier does not refer to a base class, which is
13794 // still possible in some cases.
13795
13796 // Otherwise we have to conservatively report that things might be
13797 // okay.
13798 return false;
13799 }
13800
13801 // The current scope is a record.
13802 if (!NamedContext->isRecord()) {
13803 // Ideally this would point at the last name in the specifier,
13804 // but we don't have that level of source info.
13805 Diag(Loc: SS.getBeginLoc(),
13806 DiagID: Cxx20Enumerator
13807 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13808 : diag::err_using_decl_nested_name_specifier_is_not_class)
13809 << SS.getScopeRep() << SS.getRange();
13810
13811 if (Cxx20Enumerator)
13812 return false; // OK
13813
13814 return true;
13815 }
13816
13817 if (!NamedContext->isDependentContext() &&
13818 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13819 return true;
13820
13821 // C++26 [namespace.udecl]p3:
13822 // In a using-declaration used as a member-declaration, each
13823 // using-declarator shall either name an enumerator or have a
13824 // nested-name-specifier naming a base class of the current class
13825 // ([expr.prim.this]). ...
13826 // "have a nested-name-specifier naming a base class of the current class"
13827 // was introduced by CWG400.
13828
13829 if (cast<CXXRecordDecl>(Val: CurContext)
13830 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13831
13832 if (Cxx20Enumerator) {
13833 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13834 << SS.getScopeRep() << SS.getRange();
13835 return false;
13836 }
13837
13838 if (CurContext == NamedContext) {
13839 Diag(Loc: SS.getBeginLoc(),
13840 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13841 << SS.getRange();
13842 return true;
13843 }
13844
13845 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13846 Diag(Loc: SS.getBeginLoc(),
13847 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13848 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13849 << SS.getRange();
13850 }
13851 return true;
13852 }
13853
13854 return false;
13855}
13856
13857Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13858 MultiTemplateParamsArg TemplateParamLists,
13859 SourceLocation UsingLoc, UnqualifiedId &Name,
13860 const ParsedAttributesView &AttrList,
13861 TypeResult Type, Decl *DeclFromDeclSpec) {
13862
13863 if (Type.isInvalid())
13864 return nullptr;
13865
13866 bool Invalid = false;
13867 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13868 TypeSourceInfo *TInfo = nullptr;
13869 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13870
13871 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13872 return nullptr;
13873
13874 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13875 UPPC: UPPC_DeclarationType)) {
13876 Invalid = true;
13877 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13878 Loc: TInfo->getTypeLoc().getBeginLoc());
13879 }
13880
13881 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13882 TemplateParamLists.size()
13883 ? forRedeclarationInCurContext()
13884 : RedeclarationKind::ForVisibleRedeclaration);
13885 LookupName(R&: Previous, S);
13886
13887 // Warn about shadowing the name of a template parameter.
13888 if (Previous.isSingleResult() &&
13889 Previous.getFoundDecl()->isTemplateParameter()) {
13890 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13891 Previous.clear();
13892 }
13893
13894 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13895 "name in alias declaration must be an identifier");
13896 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13897 IdLoc: Name.StartLocation,
13898 Id: Name.Identifier, TInfo);
13899
13900 NewTD->setAccess(AS);
13901
13902 if (Invalid)
13903 NewTD->setInvalidDecl();
13904
13905 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13906 AddPragmaAttributes(S, D: NewTD);
13907 ProcessAPINotes(D: NewTD);
13908
13909 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13910 Invalid |= NewTD->isInvalidDecl();
13911
13912 // Get the innermost enclosing declaration scope.
13913 S = S->getDeclParent();
13914
13915 bool Redeclaration = false;
13916
13917 NamedDecl *NewND;
13918 if (TemplateParamLists.size()) {
13919 TypeAliasTemplateDecl *OldDecl = nullptr;
13920 TemplateParameterList *OldTemplateParams = nullptr;
13921
13922 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13923 if (TemplateParamLists.size() != 1) {
13924 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13925 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13926 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13927 Invalid = true;
13928
13929 // Recover by picking the last non-empty template parameter list.
13930 auto It = llvm::find_if(
13931 Range: llvm::reverse(C&: TemplateParamLists),
13932 P: [](TemplateParameterList *TPL) { return !TPL->empty(); });
13933 assert(It != TemplateParamLists.rend() &&
13934 "if all template parameter lists were empty, this should have "
13935 "been rejected as an explicit specialization");
13936 TemplateParams = *It;
13937 }
13938
13939 // Check that we can declare a template here.
13940 if (CheckTemplateDeclScope(S, TemplateParams))
13941 return nullptr;
13942
13943 // Only consider previous declarations in the same scope.
13944 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13945 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13946 if (!Previous.empty()) {
13947 Redeclaration = true;
13948
13949 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13950 if (!OldDecl && !Invalid) {
13951 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13952 << Name.Identifier;
13953
13954 NamedDecl *OldD = Previous.getRepresentativeDecl();
13955 if (OldD->getLocation().isValid())
13956 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13957
13958 Invalid = true;
13959 }
13960
13961 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13962 if (TemplateParameterListsAreEqual(New: TemplateParams,
13963 Old: OldDecl->getTemplateParameters(),
13964 /*Complain=*/true,
13965 Kind: TPL_TemplateMatch))
13966 OldTemplateParams =
13967 OldDecl->getMostRecentDecl()->getTemplateParameters();
13968 else
13969 Invalid = true;
13970
13971 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13972 if (!Invalid &&
13973 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13974 T2: NewTD->getUnderlyingType())) {
13975 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13976 // but we can't reasonably accept it.
13977 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13978 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13979 if (OldTD->getLocation().isValid())
13980 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13981 Invalid = true;
13982 }
13983 }
13984 }
13985
13986 // Merge any previous default template arguments into our parameters,
13987 // and check the parameter list.
13988 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13989 TPC: TPC_Other))
13990 return nullptr;
13991
13992 TypeAliasTemplateDecl *NewDecl =
13993 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13994 Name: Name.Identifier, Params: TemplateParams,
13995 Decl: NewTD);
13996 NewTD->setDescribedAliasTemplate(NewDecl);
13997
13998 NewDecl->setAccess(AS);
13999
14000 if (Invalid)
14001 NewDecl->setInvalidDecl();
14002 else if (OldDecl) {
14003 NewDecl->setPreviousDecl(OldDecl);
14004 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
14005 }
14006
14007 NewND = NewDecl;
14008 } else {
14009 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
14010 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
14011 handleTagNumbering(Tag: TD, TagScope: S);
14012 }
14013 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
14014 NewND = NewTD;
14015 }
14016
14017 PushOnScopeChains(D: NewND, S);
14018 ActOnDocumentableDecl(D: NewND);
14019 return NewND;
14020}
14021
14022Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
14023 SourceLocation AliasLoc,
14024 IdentifierInfo *Alias, CXXScopeSpec &SS,
14025 SourceLocation IdentLoc,
14026 IdentifierInfo *Ident) {
14027
14028 // Lookup the namespace name.
14029 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14030 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
14031
14032 if (R.isAmbiguous())
14033 return nullptr;
14034
14035 if (R.empty()) {
14036 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
14037 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
14038 return nullptr;
14039 }
14040 }
14041 assert(!R.isAmbiguous() && !R.empty());
14042 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
14043
14044 // Check if we have a previous declaration with the same name.
14045 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14046 RedeclarationKind::ForVisibleRedeclaration);
14047 LookupName(R&: PrevR, S);
14048
14049 // Check we're not shadowing a template parameter.
14050 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14051 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
14052 PrevR.clear();
14053 }
14054
14055 // Filter out any other lookup result from an enclosing scope.
14056 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14057 /*AllowInlineNamespace*/false);
14058
14059 // Find the previous declaration and check that we can redeclare it.
14060 NamespaceAliasDecl *Prev = nullptr;
14061 if (PrevR.isSingleResult()) {
14062 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14063 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14064 // We already have an alias with the same name that points to the same
14065 // namespace; check that it matches.
14066 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14067 Prev = AD;
14068 } else if (isVisible(D: PrevDecl)) {
14069 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14070 << Alias;
14071 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14072 << AD->getNamespace();
14073 return nullptr;
14074 }
14075 } else if (isVisible(D: PrevDecl)) {
14076 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14077 ? diag::err_redefinition
14078 : diag::err_redefinition_different_kind;
14079 Diag(Loc: AliasLoc, DiagID) << Alias;
14080 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14081 return nullptr;
14082 }
14083 }
14084
14085 // The use of a nested name specifier may trigger deprecation warnings.
14086 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14087
14088 NamespaceAliasDecl *AliasDecl =
14089 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14090 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14091 IdentLoc, Namespace: ND);
14092 if (Prev)
14093 AliasDecl->setPreviousDecl(Prev);
14094
14095 PushOnScopeChains(D: AliasDecl, S);
14096 return AliasDecl;
14097}
14098
14099namespace {
14100struct SpecialMemberExceptionSpecInfo
14101 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14102 SourceLocation Loc;
14103 Sema::ImplicitExceptionSpecification ExceptSpec;
14104
14105 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14106 CXXSpecialMemberKind CSM,
14107 Sema::InheritedConstructorInfo *ICI,
14108 SourceLocation Loc)
14109 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14110
14111 bool visitBase(CXXBaseSpecifier *Base);
14112 bool visitField(FieldDecl *FD);
14113
14114 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14115 unsigned Quals);
14116
14117 void visitSubobjectCall(Subobject Subobj,
14118 Sema::SpecialMemberOverloadResult SMOR);
14119};
14120}
14121
14122bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14123 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14124 if (!BaseClass)
14125 return false;
14126
14127 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14128 if (auto *BaseCtor = SMOR.getMethod()) {
14129 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14130 return false;
14131 }
14132
14133 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14134 return false;
14135}
14136
14137bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14138 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14139 FD->hasInClassInitializer()) {
14140 Expr *E = FD->getInClassInitializer();
14141 if (!E)
14142 // FIXME: It's a little wasteful to build and throw away a
14143 // CXXDefaultInitExpr here.
14144 // FIXME: We should have a single context note pointing at Loc, and
14145 // this location should be MD->getLocation() instead, since that's
14146 // the location where we actually use the default init expression.
14147 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
14148 if (E)
14149 ExceptSpec.CalledExpr(E);
14150 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14151 ->getAsCXXRecordDecl()) {
14152 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14153 }
14154 return false;
14155}
14156
14157void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14158 Subobject Subobj,
14159 unsigned Quals) {
14160 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14161 bool IsMutable = Field && Field->isMutable();
14162 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14163}
14164
14165void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14166 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14167 // Note, if lookup fails, it doesn't matter what exception specification we
14168 // choose because the special member will be deleted.
14169 if (CXXMethodDecl *MD = SMOR.getMethod())
14170 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14171}
14172
14173bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14174 llvm::APSInt Result;
14175 ExprResult Converted = CheckConvertedConstantExpression(
14176 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14177 ExplicitSpec.setExpr(Converted.get());
14178 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14179 ExplicitSpec.setKind(Result.getBoolValue()
14180 ? ExplicitSpecKind::ResolvedTrue
14181 : ExplicitSpecKind::ResolvedFalse);
14182 return true;
14183 }
14184 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14185 return false;
14186}
14187
14188ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14189 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14190 if (!ExplicitExpr->isTypeDependent())
14191 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14192 return ES;
14193}
14194
14195static Sema::ImplicitExceptionSpecification
14196ComputeDefaultedSpecialMemberExceptionSpec(
14197 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14198 Sema::InheritedConstructorInfo *ICI) {
14199 ComputingExceptionSpec CES(S, MD, Loc);
14200
14201 CXXRecordDecl *ClassDecl = MD->getParent();
14202
14203 // C++ [except.spec]p14:
14204 // An implicitly declared special member function (Clause 12) shall have an
14205 // exception-specification. [...]
14206 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14207 if (ClassDecl->isInvalidDecl())
14208 return Info.ExceptSpec;
14209
14210 // FIXME: If this diagnostic fires, we're probably missing a check for
14211 // attempting to resolve an exception specification before it's known
14212 // at a higher level.
14213 if (S.RequireCompleteType(Loc: MD->getLocation(),
14214 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14215 DiagID: diag::err_exception_spec_incomplete_type))
14216 return Info.ExceptSpec;
14217
14218 // C++1z [except.spec]p7:
14219 // [Look for exceptions thrown by] a constructor selected [...] to
14220 // initialize a potentially constructed subobject,
14221 // C++1z [except.spec]p8:
14222 // The exception specification for an implicitly-declared destructor, or a
14223 // destructor without a noexcept-specifier, is potentially-throwing if and
14224 // only if any of the destructors for any of its potentially constructed
14225 // subojects is potentially throwing.
14226 // FIXME: We respect the first rule but ignore the "potentially constructed"
14227 // in the second rule to resolve a core issue (no number yet) that would have
14228 // us reject:
14229 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14230 // struct B : A {};
14231 // struct C : B { void f(); };
14232 // ... due to giving B::~B() a non-throwing exception specification.
14233 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14234 : Info.VisitAllBases);
14235
14236 return Info.ExceptSpec;
14237}
14238
14239namespace {
14240/// RAII object to register a special member as being currently declared.
14241struct DeclaringSpecialMember {
14242 Sema &S;
14243 Sema::SpecialMemberDecl D;
14244 Sema::ContextRAII SavedContext;
14245 bool WasAlreadyBeingDeclared;
14246
14247 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14248 : S(S), D(RD, CSM), SavedContext(S, RD) {
14249 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14250 if (WasAlreadyBeingDeclared)
14251 // This almost never happens, but if it does, ensure that our cache
14252 // doesn't contain a stale result.
14253 S.SpecialMemberCache.clear();
14254 else {
14255 // Register a note to be produced if we encounter an error while
14256 // declaring the special member.
14257 Sema::CodeSynthesisContext Ctx;
14258 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14259 // FIXME: We don't have a location to use here. Using the class's
14260 // location maintains the fiction that we declare all special members
14261 // with the class, but (1) it's not clear that lying about that helps our
14262 // users understand what's going on, and (2) there may be outer contexts
14263 // on the stack (some of which are relevant) and printing them exposes
14264 // our lies.
14265 Ctx.PointOfInstantiation = RD->getLocation();
14266 Ctx.Entity = RD;
14267 Ctx.SpecialMember = CSM;
14268 S.pushCodeSynthesisContext(Ctx);
14269 }
14270 }
14271 ~DeclaringSpecialMember() {
14272 if (!WasAlreadyBeingDeclared) {
14273 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14274 S.popCodeSynthesisContext();
14275 }
14276 }
14277
14278 /// Are we already trying to declare this special member?
14279 bool isAlreadyBeingDeclared() const {
14280 return WasAlreadyBeingDeclared;
14281 }
14282};
14283}
14284
14285void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14286 // Look up any existing declarations, but don't trigger declaration of all
14287 // implicit special members with this name.
14288 DeclarationName Name = FD->getDeclName();
14289 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14290 RedeclarationKind::ForExternalRedeclaration);
14291 for (auto *D : FD->getParent()->lookup(Name))
14292 if (auto *Acceptable = R.getAcceptableDecl(D))
14293 R.addDecl(D: Acceptable);
14294 R.resolveKind();
14295 R.suppressDiagnostics();
14296
14297 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14298 DeclIsDefn: FD->isThisDeclarationADefinition());
14299}
14300
14301void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14302 QualType ResultTy,
14303 ArrayRef<QualType> Args) {
14304 // Build an exception specification pointing back at this constructor.
14305 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14306
14307 LangAS AS = getDefaultCXXMethodAddrSpace();
14308 if (AS != LangAS::Default) {
14309 EPI.TypeQuals.addAddressSpace(space: AS);
14310 }
14311
14312 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14313 SpecialMem->setType(QT);
14314
14315 // During template instantiation of implicit special member functions we need
14316 // a reliable TypeSourceInfo for the function prototype in order to allow
14317 // functions to be substituted.
14318 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14319 TypeSourceInfo *TSI =
14320 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14321 SpecialMem->setTypeSourceInfo(TSI);
14322 }
14323}
14324
14325CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14326 CXXRecordDecl *ClassDecl) {
14327 // C++ [class.ctor]p5:
14328 // A default constructor for a class X is a constructor of class X
14329 // that can be called without an argument. If there is no
14330 // user-declared constructor for class X, a default constructor is
14331 // implicitly declared. An implicitly-declared default constructor
14332 // is an inline public member of its class.
14333 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14334 "Should not build implicit default constructor!");
14335
14336 DeclaringSpecialMember DSM(*this, ClassDecl,
14337 CXXSpecialMemberKind::DefaultConstructor);
14338 if (DSM.isAlreadyBeingDeclared())
14339 return nullptr;
14340
14341 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14342 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14343
14344 // Create the actual constructor declaration.
14345 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14346 SourceLocation ClassLoc = ClassDecl->getLocation();
14347 DeclarationName Name
14348 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14349 DeclarationNameInfo NameInfo(Name, ClassLoc);
14350 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14351 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14352 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14353 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14354 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14355 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14356 : ConstexprSpecKind::Unspecified);
14357 DefaultCon->setAccess(AS_public);
14358 DefaultCon->setDefaulted();
14359
14360 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14361
14362 if (getLangOpts().CUDA)
14363 CUDA().inferTargetForImplicitSpecialMember(
14364 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14365 /* ConstRHS */ false,
14366 /* Diagnose */ false);
14367
14368 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14369 // constructors is easy to compute.
14370 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14371
14372 // Note that we have declared this constructor.
14373 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14374
14375 Scope *S = getScopeForContext(Ctx: ClassDecl);
14376 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14377
14378 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14379 CSM: CXXSpecialMemberKind::DefaultConstructor))
14380 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14381
14382 if (S)
14383 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14384 ClassDecl->addDecl(D: DefaultCon);
14385
14386 return DefaultCon;
14387}
14388
14389void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14390 CXXConstructorDecl *Constructor) {
14391 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14392 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14393 !Constructor->doesThisDeclarationHaveABody() &&
14394 !Constructor->isDeleted()) &&
14395 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14396 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14397 return;
14398
14399 CXXRecordDecl *ClassDecl = Constructor->getParent();
14400 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14401 if (ClassDecl->isInvalidDecl()) {
14402 return;
14403 }
14404
14405 SynthesizedFunctionScope Scope(*this, Constructor);
14406
14407 // The exception specification is needed because we are defining the
14408 // function.
14409 ResolveExceptionSpec(Loc: CurrentLocation,
14410 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14411 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14412
14413 // Add a context note for diagnostics produced after this point.
14414 Scope.addContextNote(UseLoc: CurrentLocation);
14415
14416 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14417 Constructor->setInvalidDecl();
14418 return;
14419 }
14420
14421 SourceLocation Loc = Constructor->getEndLoc().isValid()
14422 ? Constructor->getEndLoc()
14423 : Constructor->getLocation();
14424 Constructor->setBody(new (Context) CompoundStmt(Loc));
14425 Constructor->markUsed(C&: Context);
14426
14427 if (ASTMutationListener *L = getASTMutationListener()) {
14428 L->CompletedImplicitDefinition(D: Constructor);
14429 }
14430
14431 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14432
14433 // The synthesized body applies the class's NSDMIs and never reaches the
14434 // normal IssueWarnings path, so run lifetime safety on it here.
14435 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14436}
14437
14438void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14439 // Perform any delayed checks on exception specifications.
14440 CheckDelayedMemberExceptionSpecs();
14441}
14442
14443/// Find or create the fake constructor we synthesize to model constructing an
14444/// object of a derived class via a constructor of a base class.
14445CXXConstructorDecl *
14446Sema::findInheritingConstructor(SourceLocation Loc,
14447 CXXConstructorDecl *BaseCtor,
14448 ConstructorUsingShadowDecl *Shadow) {
14449 CXXRecordDecl *Derived = Shadow->getParent();
14450 SourceLocation UsingLoc = Shadow->getLocation();
14451
14452 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14453 // For now we use the name of the base class constructor as a member of the
14454 // derived class to indicate a (fake) inherited constructor name.
14455 DeclarationName Name = BaseCtor->getDeclName();
14456
14457 // Check to see if we already have a fake constructor for this inherited
14458 // constructor call.
14459 for (NamedDecl *Ctor : Derived->lookup(Name))
14460 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14461 ->getInheritedConstructor()
14462 .getConstructor(),
14463 D2: BaseCtor))
14464 return cast<CXXConstructorDecl>(Val: Ctor);
14465
14466 DeclarationNameInfo NameInfo(Name, UsingLoc);
14467 TypeSourceInfo *TInfo =
14468 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14469 FunctionProtoTypeLoc ProtoLoc =
14470 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14471
14472 // Check the inherited constructor is valid and find the list of base classes
14473 // from which it was inherited.
14474 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14475
14476 bool Constexpr = BaseCtor->isConstexpr() &&
14477 defaultedSpecialMemberIsConstexpr(
14478 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14479 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14480
14481 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14482 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14483 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14484 /*isInline=*/true,
14485 /*isImplicitlyDeclared=*/true,
14486 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14487 Inherited: InheritedConstructor(Shadow, BaseCtor),
14488 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14489 if (Shadow->isInvalidDecl())
14490 DerivedCtor->setInvalidDecl();
14491
14492 // Build an unevaluated exception specification for this fake constructor.
14493 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14494 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14495 EPI.ExceptionSpec.Type = EST_Unevaluated;
14496 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14497 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14498 Args: FPT->getParamTypes(), EPI));
14499
14500 // Build the parameter declarations.
14501 SmallVector<ParmVarDecl *, 16> ParamDecls;
14502 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14503 TypeSourceInfo *TInfo =
14504 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14505 ParmVarDecl *PD = ParmVarDecl::Create(
14506 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14507 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14508 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14509 PD->setImplicit();
14510 // Ensure attributes are propagated onto parameters (this matters for
14511 // format, pass_object_size, ...).
14512 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14513 ParamDecls.push_back(Elt: PD);
14514 ProtoLoc.setParam(i: I, VD: PD);
14515 }
14516
14517 // Set up the new constructor.
14518 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14519 DerivedCtor->setAccess(BaseCtor->getAccess());
14520 DerivedCtor->setParams(ParamDecls);
14521 Derived->addDecl(D: DerivedCtor);
14522
14523 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14524 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14525 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14526
14527 return DerivedCtor;
14528}
14529
14530void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14531 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14532 Ctor->getInheritedConstructor().getShadowDecl());
14533 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14534 ICI: &ICI,
14535 /*Diagnose*/ true);
14536}
14537
14538void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14539 CXXConstructorDecl *Constructor) {
14540 CXXRecordDecl *ClassDecl = Constructor->getParent();
14541 assert(Constructor->getInheritedConstructor() &&
14542 !Constructor->doesThisDeclarationHaveABody() &&
14543 !Constructor->isDeleted());
14544 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14545 return;
14546
14547 // Initializations are performed "as if by a defaulted default constructor",
14548 // so enter the appropriate scope.
14549 SynthesizedFunctionScope Scope(*this, Constructor);
14550
14551 // The exception specification is needed because we are defining the
14552 // function.
14553 ResolveExceptionSpec(Loc: CurrentLocation,
14554 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14555 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14556
14557 // Add a context note for diagnostics produced after this point.
14558 Scope.addContextNote(UseLoc: CurrentLocation);
14559
14560 ConstructorUsingShadowDecl *Shadow =
14561 Constructor->getInheritedConstructor().getShadowDecl();
14562 CXXConstructorDecl *InheritedCtor =
14563 Constructor->getInheritedConstructor().getConstructor();
14564
14565 // [class.inhctor.init]p1:
14566 // initialization proceeds as if a defaulted default constructor is used to
14567 // initialize the D object and each base class subobject from which the
14568 // constructor was inherited
14569
14570 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14571 CXXRecordDecl *RD = Shadow->getParent();
14572 SourceLocation InitLoc = Shadow->getLocation();
14573
14574 // Build explicit initializers for all base classes from which the
14575 // constructor was inherited.
14576 SmallVector<CXXCtorInitializer*, 8> Inits;
14577 for (bool VBase : {false, true}) {
14578 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14579 if (B.isVirtual() != VBase)
14580 continue;
14581
14582 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14583 if (!BaseRD)
14584 continue;
14585
14586 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14587 if (!BaseCtor.first)
14588 continue;
14589
14590 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14591 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14592 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14593
14594 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14595 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14596 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14597 SourceLocation()));
14598 }
14599 }
14600
14601 // We now proceed as if for a defaulted default constructor, with the relevant
14602 // initializers replaced.
14603
14604 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14605 Constructor->setInvalidDecl();
14606 return;
14607 }
14608
14609 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14610 Constructor->markUsed(C&: Context);
14611
14612 if (ASTMutationListener *L = getASTMutationListener()) {
14613 L->CompletedImplicitDefinition(D: Constructor);
14614 }
14615
14616 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14617
14618 // The synthesized body applies the class's NSDMIs and never reaches the
14619 // normal IssueWarnings path, so run lifetime safety on it here.
14620 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14621}
14622
14623CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14624 // C++ [class.dtor]p2:
14625 // If a class has no user-declared destructor, a destructor is
14626 // declared implicitly. An implicitly-declared destructor is an
14627 // inline public member of its class.
14628 assert(ClassDecl->needsImplicitDestructor());
14629
14630 DeclaringSpecialMember DSM(*this, ClassDecl,
14631 CXXSpecialMemberKind::Destructor);
14632 if (DSM.isAlreadyBeingDeclared())
14633 return nullptr;
14634
14635 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14636 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14637
14638 // Create the actual destructor declaration.
14639 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14640 SourceLocation ClassLoc = ClassDecl->getLocation();
14641 DeclarationName Name
14642 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14643 DeclarationNameInfo NameInfo(Name, ClassLoc);
14644 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14645 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14646 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14647 /*isInline=*/true,
14648 /*isImplicitlyDeclared=*/true,
14649 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14650 : ConstexprSpecKind::Unspecified);
14651 Destructor->setAccess(AS_public);
14652 Destructor->setDefaulted();
14653
14654 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14655
14656 if (getLangOpts().CUDA)
14657 CUDA().inferTargetForImplicitSpecialMember(
14658 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14659 /* ConstRHS */ false,
14660 /* Diagnose */ false);
14661
14662 // We don't need to use SpecialMemberIsTrivial here; triviality for
14663 // destructors is easy to compute.
14664 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14665 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14666 ClassDecl->hasTrivialDestructorForCall());
14667
14668 // Note that we have declared this destructor.
14669 ++getASTContext().NumImplicitDestructorsDeclared;
14670
14671 Scope *S = getScopeForContext(Ctx: ClassDecl);
14672 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14673
14674 // We can't check whether an implicit destructor is deleted before we complete
14675 // the definition of the class, because its validity depends on the alignment
14676 // of the class. We'll check this from ActOnFields once the class is complete.
14677 if (ClassDecl->isCompleteDefinition() &&
14678 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14679 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14680
14681 // Introduce this destructor into its scope.
14682 if (S)
14683 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14684 ClassDecl->addDecl(D: Destructor);
14685
14686 return Destructor;
14687}
14688
14689void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14690 CXXDestructorDecl *Destructor) {
14691 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14692 assert((Destructor->isDefaulted() &&
14693 !Destructor->doesThisDeclarationHaveABody() &&
14694 !Destructor->isDeleted()) &&
14695 "DefineImplicitDestructor - call it for implicit default dtor");
14696 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14697 return;
14698
14699 CXXRecordDecl *ClassDecl = Destructor->getParent();
14700 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14701
14702 SynthesizedFunctionScope Scope(*this, Destructor);
14703
14704 // The exception specification is needed because we are defining the
14705 // function.
14706 ResolveExceptionSpec(Loc: CurrentLocation,
14707 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14708 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14709
14710 // Add a context note for diagnostics produced after this point.
14711 Scope.addContextNote(UseLoc: CurrentLocation);
14712
14713 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14714 ClassDecl: Destructor->getParent());
14715
14716 if (CheckDestructor(Destructor)) {
14717 Destructor->setInvalidDecl();
14718 return;
14719 }
14720
14721 SourceLocation Loc = Destructor->getEndLoc().isValid()
14722 ? Destructor->getEndLoc()
14723 : Destructor->getLocation();
14724 Destructor->setBody(new (Context) CompoundStmt(Loc));
14725 Destructor->markUsed(C&: Context);
14726
14727 if (ASTMutationListener *L = getASTMutationListener()) {
14728 L->CompletedImplicitDefinition(D: Destructor);
14729 }
14730}
14731
14732void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14733 CXXDestructorDecl *Destructor) {
14734 if (Destructor->isInvalidDecl())
14735 return;
14736
14737 CXXRecordDecl *ClassDecl = Destructor->getParent();
14738 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14739 "implicit complete dtors unneeded outside MS ABI");
14740 assert(ClassDecl->getNumVBases() > 0 &&
14741 "complete dtor only exists for classes with vbases");
14742
14743 SynthesizedFunctionScope Scope(*this, Destructor);
14744
14745 // Add a context note for diagnostics produced after this point.
14746 Scope.addContextNote(UseLoc: CurrentLocation);
14747
14748 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14749}
14750
14751void Sema::ActOnFinishCXXMemberDecls() {
14752 // If the context is an invalid C++ class, just suppress these checks.
14753 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14754 if (Record->isInvalidDecl()) {
14755 DelayedOverridingExceptionSpecChecks.clear();
14756 DelayedEquivalentExceptionSpecChecks.clear();
14757 return;
14758 }
14759 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14760 }
14761}
14762
14763void Sema::ActOnFinishCXXNonNestedClass() {
14764 referenceDLLExportedClassMethods();
14765
14766 if (!DelayedDllExportMemberFunctions.empty()) {
14767 SmallVector<CXXMethodDecl*, 4> WorkList;
14768 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14769 for (CXXMethodDecl *M : WorkList) {
14770 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14771
14772 // Pass the method to the consumer to get emitted. This is not necessary
14773 // for explicit instantiation definitions, as they will get emitted
14774 // anyway.
14775 if (M->getParent()->getTemplateSpecializationKind() !=
14776 TSK_ExplicitInstantiationDefinition)
14777 ActOnFinishInlineFunctionDef(D: M);
14778 }
14779 }
14780}
14781
14782void Sema::referenceDLLExportedClassMethods() {
14783 if (!DelayedDllExportClasses.empty()) {
14784 // Calling ReferenceDllExportedMembers might cause the current function to
14785 // be called again, so use a local copy of DelayedDllExportClasses.
14786 SmallVector<CXXRecordDecl *, 4> WorkList;
14787 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14788 for (CXXRecordDecl *Class : WorkList)
14789 ReferenceDllExportedMembers(S&: *this, Class);
14790 }
14791}
14792
14793void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14794 assert(getLangOpts().CPlusPlus11 &&
14795 "adjusting dtor exception specs was introduced in c++11");
14796
14797 if (Destructor->isDependentContext())
14798 return;
14799
14800 // C++11 [class.dtor]p3:
14801 // A declaration of a destructor that does not have an exception-
14802 // specification is implicitly considered to have the same exception-
14803 // specification as an implicit declaration.
14804 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14805 if (DtorType->hasExceptionSpec())
14806 return;
14807
14808 // Replace the destructor's type, building off the existing one. Fortunately,
14809 // the only thing of interest in the destructor type is its extended info.
14810 // The return and arguments are fixed.
14811 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14812 EPI.ExceptionSpec.Type = EST_Unevaluated;
14813 EPI.ExceptionSpec.SourceDecl = Destructor;
14814 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14815
14816 // FIXME: If the destructor has a body that could throw, and the newly created
14817 // spec doesn't allow exceptions, we should emit a warning, because this
14818 // change in behavior can break conforming C++03 programs at runtime.
14819 // However, we don't have a body or an exception specification yet, so it
14820 // needs to be done somewhere else.
14821}
14822
14823namespace {
14824/// An abstract base class for all helper classes used in building the
14825// copy/move operators. These classes serve as factory functions and help us
14826// avoid using the same Expr* in the AST twice.
14827class ExprBuilder {
14828 ExprBuilder(const ExprBuilder&) = delete;
14829 ExprBuilder &operator=(const ExprBuilder&) = delete;
14830
14831protected:
14832 static Expr *assertNotNull(Expr *E) {
14833 assert(E && "Expression construction must not fail.");
14834 return E;
14835 }
14836
14837public:
14838 ExprBuilder() {}
14839 virtual ~ExprBuilder() {}
14840
14841 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14842};
14843
14844class RefBuilder: public ExprBuilder {
14845 VarDecl *Var;
14846 QualType VarType;
14847
14848public:
14849 Expr *build(Sema &S, SourceLocation Loc) const override {
14850 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14851 }
14852
14853 RefBuilder(VarDecl *Var, QualType VarType)
14854 : Var(Var), VarType(VarType) {}
14855};
14856
14857class ThisBuilder: public ExprBuilder {
14858public:
14859 Expr *build(Sema &S, SourceLocation Loc) const override {
14860 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14861 }
14862};
14863
14864class CastBuilder: public ExprBuilder {
14865 const ExprBuilder &Builder;
14866 QualType Type;
14867 ExprValueKind Kind;
14868 const CXXCastPath &Path;
14869
14870public:
14871 Expr *build(Sema &S, SourceLocation Loc) const override {
14872 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14873 CK: CK_UncheckedDerivedToBase, VK: Kind,
14874 BasePath: &Path).get());
14875 }
14876
14877 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14878 const CXXCastPath &Path)
14879 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14880};
14881
14882class DerefBuilder: public ExprBuilder {
14883 const ExprBuilder &Builder;
14884
14885public:
14886 Expr *build(Sema &S, SourceLocation Loc) const override {
14887 return assertNotNull(
14888 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14889 }
14890
14891 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14892};
14893
14894class MemberBuilder: public ExprBuilder {
14895 const ExprBuilder &Builder;
14896 QualType Type;
14897 CXXScopeSpec SS;
14898 bool IsArrow;
14899 LookupResult &MemberLookup;
14900
14901public:
14902 Expr *build(Sema &S, SourceLocation Loc) const override {
14903 return assertNotNull(E: S.BuildMemberReferenceExpr(
14904 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14905 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14906 }
14907
14908 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14909 LookupResult &MemberLookup)
14910 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14911 MemberLookup(MemberLookup) {}
14912};
14913
14914class MoveCastBuilder: public ExprBuilder {
14915 const ExprBuilder &Builder;
14916
14917public:
14918 Expr *build(Sema &S, SourceLocation Loc) const override {
14919 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14920 }
14921
14922 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14923};
14924
14925class LvalueConvBuilder: public ExprBuilder {
14926 const ExprBuilder &Builder;
14927
14928public:
14929 Expr *build(Sema &S, SourceLocation Loc) const override {
14930 return assertNotNull(
14931 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14932 }
14933
14934 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14935};
14936
14937class SubscriptBuilder: public ExprBuilder {
14938 const ExprBuilder &Base;
14939 const ExprBuilder &Index;
14940
14941public:
14942 Expr *build(Sema &S, SourceLocation Loc) const override {
14943 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14944 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14945 }
14946
14947 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14948 : Base(Base), Index(Index) {}
14949};
14950
14951} // end anonymous namespace
14952
14953/// When generating a defaulted copy or move assignment operator, if a field
14954/// should be copied with __builtin_memcpy rather than via explicit assignments,
14955/// do so. This optimization only applies for arrays of scalars, and for arrays
14956/// of class type where the selected copy/move-assignment operator is trivial.
14957static StmtResult
14958buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14959 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14960 // Compute the size of the memory buffer to be copied.
14961 QualType SizeType = S.Context.getSizeType();
14962 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14963 S.Context.getTypeSizeInChars(T).getQuantity());
14964
14965 // Take the address of the field references for "from" and "to". We
14966 // directly construct UnaryOperators here because semantic analysis
14967 // does not permit us to take the address of an xvalue.
14968 Expr *From = FromB.build(S, Loc);
14969 From = UnaryOperator::Create(
14970 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14971 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14972 Expr *To = ToB.build(S, Loc);
14973 To = UnaryOperator::Create(
14974 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14975 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14976
14977 bool NeedsCollectableMemCpy = false;
14978 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14979 NeedsCollectableMemCpy = RD->hasObjectMember();
14980
14981 // Create a reference to the __builtin_objc_memmove_collectable function
14982 StringRef MemCpyName = NeedsCollectableMemCpy ?
14983 "__builtin_objc_memmove_collectable" :
14984 "__builtin_memcpy";
14985 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14986 Sema::LookupOrdinaryName);
14987 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14988
14989 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14990 if (!MemCpy)
14991 // Something went horribly wrong earlier, and we will have complained
14992 // about it.
14993 return StmtError();
14994
14995 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
14996 VK: VK_PRValue, Loc, SS: nullptr);
14997 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14998
14999 Expr *CallArgs[] = {
15000 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
15001 };
15002 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
15003 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
15004
15005 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15006 return Call.getAs<Stmt>();
15007}
15008
15009/// Builds a statement that copies/moves the given entity from \p From to
15010/// \c To.
15011///
15012/// This routine is used to copy/move the members of a class with an
15013/// implicitly-declared copy/move assignment operator. When the entities being
15014/// copied are arrays, this routine builds for loops to copy them.
15015///
15016/// \param S The Sema object used for type-checking.
15017///
15018/// \param Loc The location where the implicit copy/move is being generated.
15019///
15020/// \param T The type of the expressions being copied/moved. Both expressions
15021/// must have this type.
15022///
15023/// \param To The expression we are copying/moving to.
15024///
15025/// \param From The expression we are copying/moving from.
15026///
15027/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15028/// Otherwise, it's a non-static member subobject.
15029///
15030/// \param Copying Whether we're copying or moving.
15031///
15032/// \param Depth Internal parameter recording the depth of the recursion.
15033///
15034/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15035/// if a memcpy should be used instead.
15036static StmtResult
15037buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
15038 const ExprBuilder &To, const ExprBuilder &From,
15039 bool CopyingBaseSubobject, bool Copying,
15040 unsigned Depth = 0) {
15041 // C++11 [class.copy]p28:
15042 // Each subobject is assigned in the manner appropriate to its type:
15043 //
15044 // - if the subobject is of class type, as if by a call to operator= with
15045 // the subobject as the object expression and the corresponding
15046 // subobject of x as a single function argument (as if by explicit
15047 // qualification; that is, ignoring any possible virtual overriding
15048 // functions in more derived classes);
15049 //
15050 // C++03 [class.copy]p13:
15051 // - if the subobject is of class type, the copy assignment operator for
15052 // the class is used (as if by explicit qualification; that is,
15053 // ignoring any possible virtual overriding functions in more derived
15054 // classes);
15055 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15056 // Look for operator=.
15057 DeclarationName Name
15058 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15059 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15060 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
15061
15062 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15063 // operator.
15064 if (!S.getLangOpts().CPlusPlus11) {
15065 LookupResult::Filter F = OpLookup.makeFilter();
15066 while (F.hasNext()) {
15067 NamedDecl *D = F.next();
15068 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15069 if (Method->isCopyAssignmentOperator() ||
15070 (!Copying && Method->isMoveAssignmentOperator()))
15071 continue;
15072
15073 F.erase();
15074 }
15075 F.done();
15076 }
15077
15078 // Suppress the protected check (C++ [class.protected]) for each of the
15079 // assignment operators we found. This strange dance is required when
15080 // we're assigning via a base classes's copy-assignment operator. To
15081 // ensure that we're getting the right base class subobject (without
15082 // ambiguities), we need to cast "this" to that subobject type; to
15083 // ensure that we don't go through the virtual call mechanism, we need
15084 // to qualify the operator= name with the base class (see below). However,
15085 // this means that if the base class has a protected copy assignment
15086 // operator, the protected member access check will fail. So, we
15087 // rewrite "protected" access to "public" access in this case, since we
15088 // know by construction that we're calling from a derived class.
15089 if (CopyingBaseSubobject) {
15090 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15091 L != LEnd; ++L) {
15092 if (L.getAccess() == AS_protected)
15093 L.setAccess(AS_public);
15094 }
15095 }
15096
15097 // Create the nested-name-specifier that will be used to qualify the
15098 // reference to operator=; this is required to suppress the virtual
15099 // call mechanism.
15100 CXXScopeSpec SS;
15101 // FIXME: Don't canonicalize this.
15102 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15103 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15104
15105 // Create the reference to operator=.
15106 ExprResult OpEqualRef
15107 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15108 SS, /*TemplateKWLoc=*/SourceLocation(),
15109 /*FirstQualifierInScope=*/nullptr,
15110 R&: OpLookup,
15111 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15112 /*SuppressQualifierCheck=*/true);
15113 if (OpEqualRef.isInvalid())
15114 return StmtError();
15115
15116 // Build the call to the assignment operator.
15117
15118 Expr *FromInst = From.build(S, Loc);
15119 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15120 MemExpr: OpEqualRef.getAs<Expr>(),
15121 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15122 if (Call.isInvalid())
15123 return StmtError();
15124
15125 // If we built a call to a trivial 'operator=' while copying an array,
15126 // bail out. We'll replace the whole shebang with a memcpy.
15127 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15128 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15129 return StmtResult((Stmt*)nullptr);
15130
15131 // Convert to an expression-statement, and clean up any produced
15132 // temporaries.
15133 return S.ActOnExprStmt(Arg: Call);
15134 }
15135
15136 // - if the subobject is of scalar type, the built-in assignment
15137 // operator is used.
15138 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15139 if (!ArrayTy) {
15140 ExprResult Assignment = S.CreateBuiltinBinOp(
15141 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15142 if (Assignment.isInvalid())
15143 return StmtError();
15144 return S.ActOnExprStmt(Arg: Assignment);
15145 }
15146
15147 // - if the subobject is an array, each element is assigned, in the
15148 // manner appropriate to the element type;
15149
15150 // Construct a loop over the array bounds, e.g.,
15151 //
15152 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15153 //
15154 // that will copy each of the array elements.
15155 QualType SizeType = S.Context.getSizeType();
15156
15157 // Create the iteration variable.
15158 IdentifierInfo *IterationVarName = nullptr;
15159 {
15160 SmallString<8> Str;
15161 llvm::raw_svector_ostream OS(Str);
15162 OS << "__i" << Depth;
15163 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15164 }
15165 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15166 Id: IterationVarName, T: SizeType,
15167 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15168 S: SC_None);
15169
15170 // Initialize the iteration variable to zero.
15171 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15172 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15173
15174 // Creates a reference to the iteration variable.
15175 RefBuilder IterationVarRef(IterationVar, SizeType);
15176 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15177
15178 // Create the DeclStmt that holds the iteration variable.
15179 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15180
15181 // Subscript the "from" and "to" expressions with the iteration variable.
15182 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15183 MoveCastBuilder FromIndexMove(FromIndexCopy);
15184 const ExprBuilder *FromIndex;
15185 if (Copying)
15186 FromIndex = &FromIndexCopy;
15187 else
15188 FromIndex = &FromIndexMove;
15189
15190 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15191
15192 // Build the copy/move for an individual element of the array.
15193 StmtResult Copy =
15194 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15195 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15196 Copying, Depth: Depth + 1);
15197 // Bail out if copying fails or if we determined that we should use memcpy.
15198 if (Copy.isInvalid() || !Copy.get())
15199 return Copy;
15200
15201 // Create the comparison against the array bound.
15202 llvm::APInt Upper
15203 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15204 Expr *Comparison = BinaryOperator::Create(
15205 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15206 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15207 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15208 FPFeatures: S.CurFPFeatureOverrides());
15209
15210 // Create the pre-increment of the iteration variable. We can determine
15211 // whether the increment will overflow based on the value of the array
15212 // bound.
15213 Expr *Increment = UnaryOperator::Create(
15214 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15215 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15216
15217 // Construct the loop that copies all elements of this array.
15218 return S.ActOnForStmt(
15219 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15220 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15221 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15222}
15223
15224static StmtResult
15225buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15226 const ExprBuilder &To, const ExprBuilder &From,
15227 bool CopyingBaseSubobject, bool Copying) {
15228 // Maybe we should use a memcpy?
15229 if (T->isArrayType() && !T.hasQualifiers() &&
15230 T.isTriviallyCopyableType(Context: S.Context))
15231 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15232
15233 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15234 CopyingBaseSubobject,
15235 Copying, Depth: 0));
15236
15237 // If we ended up picking a trivial assignment operator for an array of a
15238 // non-trivially-copyable class type, just emit a memcpy.
15239 if (!Result.isInvalid() && !Result.get())
15240 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15241
15242 return Result;
15243}
15244
15245CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15246 // Note: The following rules are largely analoguous to the copy
15247 // constructor rules. Note that virtual bases are not taken into account
15248 // for determining the argument type of the operator. Note also that
15249 // operators taking an object instead of a reference are allowed.
15250 assert(ClassDecl->needsImplicitCopyAssignment());
15251
15252 DeclaringSpecialMember DSM(*this, ClassDecl,
15253 CXXSpecialMemberKind::CopyAssignment);
15254 if (DSM.isAlreadyBeingDeclared())
15255 return nullptr;
15256
15257 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15258 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15259 /*OwnsTag=*/false);
15260 LangAS AS = getDefaultCXXMethodAddrSpace();
15261 if (AS != LangAS::Default)
15262 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15263 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15264 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15265 if (Const)
15266 ArgType = ArgType.withConst();
15267
15268 ArgType = Context.getLValueReferenceType(T: ArgType);
15269
15270 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15271 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15272
15273 // An implicitly-declared copy assignment operator is an inline public
15274 // member of its class.
15275 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15276 SourceLocation ClassLoc = ClassDecl->getLocation();
15277 DeclarationNameInfo NameInfo(Name, ClassLoc);
15278 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15279 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15280 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15281 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15282 /*isInline=*/true,
15283 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15284 EndLocation: SourceLocation());
15285 CopyAssignment->setAccess(AS_public);
15286 CopyAssignment->setDefaulted();
15287 CopyAssignment->setImplicit();
15288
15289 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15290
15291 if (getLangOpts().CUDA)
15292 CUDA().inferTargetForImplicitSpecialMember(
15293 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15294 /* ConstRHS */ Const,
15295 /* Diagnose */ false);
15296
15297 // Add the parameter to the operator.
15298 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15299 StartLoc: ClassLoc, IdLoc: ClassLoc,
15300 /*Id=*/nullptr, T: ArgType,
15301 /*TInfo=*/nullptr, S: SC_None,
15302 DefArg: nullptr);
15303 CopyAssignment->setParams(FromParam);
15304
15305 CopyAssignment->setTrivial(
15306 ClassDecl->needsOverloadResolutionForCopyAssignment()
15307 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15308 CSM: CXXSpecialMemberKind::CopyAssignment)
15309 : ClassDecl->hasTrivialCopyAssignment());
15310
15311 // Note that we have added this copy-assignment operator.
15312 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15313
15314 Scope *S = getScopeForContext(Ctx: ClassDecl);
15315 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15316
15317 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15318 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15319 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15320 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15321 }
15322
15323 if (S)
15324 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15325 ClassDecl->addDecl(D: CopyAssignment);
15326
15327 return CopyAssignment;
15328}
15329
15330/// Diagnose an implicit copy operation for a class which is odr-used, but
15331/// which is deprecated because the class has a user-declared copy constructor,
15332/// copy assignment operator, or destructor.
15333static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15334 assert(CopyOp->isImplicit());
15335
15336 CXXRecordDecl *RD = CopyOp->getParent();
15337 CXXMethodDecl *UserDeclaredOperation = nullptr;
15338
15339 if (RD->hasUserDeclaredDestructor()) {
15340 UserDeclaredOperation = RD->getDestructor();
15341 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15342 RD->hasUserDeclaredCopyConstructor()) {
15343 // Find any user-declared copy constructor.
15344 for (auto *I : RD->ctors()) {
15345 if (I->isCopyConstructor()) {
15346 UserDeclaredOperation = I;
15347 break;
15348 }
15349 }
15350 assert(UserDeclaredOperation);
15351 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15352 RD->hasUserDeclaredCopyAssignment()) {
15353 // Find any user-declared move assignment operator.
15354 for (auto *I : RD->methods()) {
15355 if (I->isCopyAssignmentOperator()) {
15356 UserDeclaredOperation = I;
15357 break;
15358 }
15359 }
15360 assert(UserDeclaredOperation);
15361 }
15362
15363 if (UserDeclaredOperation) {
15364 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15365 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15366 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15367 unsigned DiagID =
15368 (UDOIsUserProvided && UDOIsDestructor)
15369 ? diag::warn_deprecated_copy_with_user_provided_dtor
15370 : (UDOIsUserProvided && !UDOIsDestructor)
15371 ? diag::warn_deprecated_copy_with_user_provided_copy
15372 : (!UDOIsUserProvided && UDOIsDestructor)
15373 ? diag::warn_deprecated_copy_with_dtor
15374 : diag::warn_deprecated_copy;
15375 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15376 << RD << IsCopyAssignment;
15377 }
15378}
15379
15380void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15381 CXXMethodDecl *CopyAssignOperator) {
15382 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15383 assert((CopyAssignOperator->isDefaulted() &&
15384 CopyAssignOperator->isOverloadedOperator() &&
15385 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15386 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15387 !CopyAssignOperator->isDeleted()) &&
15388 "DefineImplicitCopyAssignment called for wrong function");
15389 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15390 return;
15391
15392 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15393 if (ClassDecl->isInvalidDecl()) {
15394 CopyAssignOperator->setInvalidDecl();
15395 return;
15396 }
15397
15398 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15399
15400 // The exception specification is needed because we are defining the
15401 // function.
15402 ResolveExceptionSpec(Loc: CurrentLocation,
15403 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15404
15405 // Add a context note for diagnostics produced after this point.
15406 Scope.addContextNote(UseLoc: CurrentLocation);
15407
15408 // C++11 [class.copy]p18:
15409 // The [definition of an implicitly declared copy assignment operator] is
15410 // deprecated if the class has a user-declared copy constructor or a
15411 // user-declared destructor.
15412 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15413 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15414
15415 // C++0x [class.copy]p30:
15416 // The implicitly-defined or explicitly-defaulted copy assignment operator
15417 // for a non-union class X performs memberwise copy assignment of its
15418 // subobjects. The direct base classes of X are assigned first, in the
15419 // order of their declaration in the base-specifier-list, and then the
15420 // immediate non-static data members of X are assigned, in the order in
15421 // which they were declared in the class definition.
15422
15423 // The statements that form the synthesized function body.
15424 SmallVector<Stmt*, 8> Statements;
15425
15426 // The parameter for the "other" object, which we are copying from.
15427 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15428 Qualifiers OtherQuals = Other->getType().getQualifiers();
15429 QualType OtherRefType = Other->getType();
15430 if (OtherRefType->isLValueReferenceType()) {
15431 OtherRefType = OtherRefType->getPointeeType();
15432 OtherQuals = OtherRefType.getQualifiers();
15433 }
15434
15435 // Our location for everything implicitly-generated.
15436 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15437 ? CopyAssignOperator->getEndLoc()
15438 : CopyAssignOperator->getLocation();
15439
15440 // Builds a DeclRefExpr for the "other" object.
15441 RefBuilder OtherRef(Other, OtherRefType);
15442
15443 // Builds the function object parameter.
15444 std::optional<ThisBuilder> This;
15445 std::optional<DerefBuilder> DerefThis;
15446 std::optional<RefBuilder> ExplicitObject;
15447 bool IsArrow = false;
15448 QualType ObjectType;
15449 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15450 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15451 if (ObjectType->isReferenceType())
15452 ObjectType = ObjectType->getPointeeType();
15453 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15454 } else {
15455 ObjectType = getCurrentThisType();
15456 This.emplace();
15457 DerefThis.emplace(args&: *This);
15458 IsArrow = !LangOpts.HLSL;
15459 }
15460 ExprBuilder &ObjectParameter =
15461 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15462 : static_cast<ExprBuilder &>(*This);
15463
15464 // Assign base classes.
15465 bool Invalid = false;
15466 for (auto &Base : ClassDecl->bases()) {
15467 // Form the assignment:
15468 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15469 QualType BaseType = Base.getType().getUnqualifiedType();
15470 if (!BaseType->isRecordType()) {
15471 Invalid = true;
15472 continue;
15473 }
15474
15475 CXXCastPath BasePath;
15476 BasePath.push_back(Elt: &Base);
15477
15478 // Construct the "from" expression, which is an implicit cast to the
15479 // appropriately-qualified base type.
15480 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15481 VK_LValue, BasePath);
15482
15483 // Dereference "this".
15484 CastBuilder To(
15485 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15486 : static_cast<ExprBuilder &>(*DerefThis),
15487 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15488 VK_LValue, BasePath);
15489
15490 // Build the copy.
15491 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15492 To, From,
15493 /*CopyingBaseSubobject=*/true,
15494 /*Copying=*/true);
15495 if (Copy.isInvalid()) {
15496 CopyAssignOperator->setInvalidDecl();
15497 return;
15498 }
15499
15500 // Success! Record the copy.
15501 Statements.push_back(Elt: Copy.getAs<Expr>());
15502 }
15503
15504 // Assign non-static members.
15505 for (auto *Field : ClassDecl->fields()) {
15506 // FIXME: We should form some kind of AST representation for the implied
15507 // memcpy in a union copy operation.
15508 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15509 continue;
15510
15511 if (Field->isInvalidDecl()) {
15512 Invalid = true;
15513 continue;
15514 }
15515
15516 // Check for members of reference type; we can't copy those.
15517 if (Field->getType()->isReferenceType()) {
15518 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15519 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15520 << Field->getDeclName();
15521 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15522 Invalid = true;
15523 continue;
15524 }
15525
15526 // Check for members of const-qualified, non-class type.
15527 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15528 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15529 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15530 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15531 << Field->getDeclName();
15532 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15533 Invalid = true;
15534 continue;
15535 }
15536
15537 // Suppress assigning zero-width bitfields.
15538 if (Field->isZeroLengthBitField())
15539 continue;
15540
15541 QualType FieldType = Field->getType().getNonReferenceType();
15542 if (FieldType->isIncompleteArrayType()) {
15543 assert(ClassDecl->hasFlexibleArrayMember() &&
15544 "Incomplete array type is not valid");
15545 continue;
15546 }
15547
15548 // Build references to the field in the object we're copying from and to.
15549 CXXScopeSpec SS; // Intentionally empty
15550 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15551 LookupMemberName);
15552 MemberLookup.addDecl(D: Field);
15553 MemberLookup.resolveKind();
15554
15555 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15556 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15557 // Build the copy of this field.
15558 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15559 To, From,
15560 /*CopyingBaseSubobject=*/false,
15561 /*Copying=*/true);
15562 if (Copy.isInvalid()) {
15563 CopyAssignOperator->setInvalidDecl();
15564 return;
15565 }
15566
15567 // Success! Record the copy.
15568 Statements.push_back(Elt: Copy.getAs<Stmt>());
15569 }
15570
15571 if (!Invalid) {
15572 // Add a "return *this;"
15573 Expr *ThisExpr =
15574 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15575 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15576 : static_cast<ExprBuilder &>(*DerefThis))
15577 .build(S&: *this, Loc);
15578 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15579 if (Return.isInvalid())
15580 Invalid = true;
15581 else
15582 Statements.push_back(Elt: Return.getAs<Stmt>());
15583 }
15584
15585 if (Invalid) {
15586 CopyAssignOperator->setInvalidDecl();
15587 return;
15588 }
15589
15590 StmtResult Body;
15591 {
15592 CompoundScopeRAII CompoundScope(*this);
15593 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15594 /*isStmtExpr=*/false);
15595 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15596 }
15597 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15598 CopyAssignOperator->markUsed(C&: Context);
15599
15600 if (ASTMutationListener *L = getASTMutationListener()) {
15601 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15602 }
15603}
15604
15605CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15606 assert(ClassDecl->needsImplicitMoveAssignment());
15607
15608 DeclaringSpecialMember DSM(*this, ClassDecl,
15609 CXXSpecialMemberKind::MoveAssignment);
15610 if (DSM.isAlreadyBeingDeclared())
15611 return nullptr;
15612
15613 // Note: The following rules are largely analoguous to the move
15614 // constructor rules.
15615
15616 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15617 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15618 /*OwnsTag=*/false);
15619 LangAS AS = getDefaultCXXMethodAddrSpace();
15620 if (AS != LangAS::Default)
15621 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15622 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15623 ArgType = Context.getRValueReferenceType(T: ArgType);
15624
15625 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15626 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15627
15628 // An implicitly-declared move assignment operator is an inline public
15629 // member of its class.
15630 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15631 SourceLocation ClassLoc = ClassDecl->getLocation();
15632 DeclarationNameInfo NameInfo(Name, ClassLoc);
15633 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15634 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15635 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15636 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15637 /*isInline=*/true,
15638 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15639 EndLocation: SourceLocation());
15640 MoveAssignment->setAccess(AS_public);
15641 MoveAssignment->setDefaulted();
15642 MoveAssignment->setImplicit();
15643
15644 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15645
15646 if (getLangOpts().CUDA)
15647 CUDA().inferTargetForImplicitSpecialMember(
15648 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15649 /* ConstRHS */ false,
15650 /* Diagnose */ false);
15651
15652 // Add the parameter to the operator.
15653 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15654 StartLoc: ClassLoc, IdLoc: ClassLoc,
15655 /*Id=*/nullptr, T: ArgType,
15656 /*TInfo=*/nullptr, S: SC_None,
15657 DefArg: nullptr);
15658 MoveAssignment->setParams(FromParam);
15659
15660 MoveAssignment->setTrivial(
15661 ClassDecl->needsOverloadResolutionForMoveAssignment()
15662 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15663 CSM: CXXSpecialMemberKind::MoveAssignment)
15664 : ClassDecl->hasTrivialMoveAssignment());
15665
15666 // Note that we have added this copy-assignment operator.
15667 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15668
15669 Scope *S = getScopeForContext(Ctx: ClassDecl);
15670 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15671
15672 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15673 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15674 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15675 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15676 }
15677
15678 if (S)
15679 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15680 ClassDecl->addDecl(D: MoveAssignment);
15681
15682 return MoveAssignment;
15683}
15684
15685/// Check if we're implicitly defining a move assignment operator for a class
15686/// with virtual bases. Such a move assignment might move-assign the virtual
15687/// base multiple times.
15688static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15689 SourceLocation CurrentLocation) {
15690 assert(!Class->isDependentContext() && "should not define dependent move");
15691
15692 // Only a virtual base could get implicitly move-assigned multiple times.
15693 // Only a non-trivial move assignment can observe this. We only want to
15694 // diagnose if we implicitly define an assignment operator that assigns
15695 // two base classes, both of which move-assign the same virtual base.
15696 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15697 Class->getNumBases() < 2)
15698 return;
15699
15700 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15701 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15702 VBaseMap VBases;
15703
15704 for (auto &BI : Class->bases()) {
15705 Worklist.push_back(Elt: &BI);
15706 while (!Worklist.empty()) {
15707 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15708 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15709
15710 // If the base has no non-trivial move assignment operators,
15711 // we don't care about moves from it.
15712 if (!Base->hasNonTrivialMoveAssignment())
15713 continue;
15714
15715 // If there's nothing virtual here, skip it.
15716 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15717 continue;
15718
15719 // If we're not actually going to call a move assignment for this base,
15720 // or the selected move assignment is trivial, skip it.
15721 Sema::SpecialMemberOverloadResult SMOR =
15722 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15723 /*ConstArg*/ false, /*VolatileArg*/ false,
15724 /*RValueThis*/ true, /*ConstThis*/ false,
15725 /*VolatileThis*/ false);
15726 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15727 !SMOR.getMethod()->isMoveAssignmentOperator())
15728 continue;
15729
15730 if (BaseSpec->isVirtual()) {
15731 // We're going to move-assign this virtual base, and its move
15732 // assignment operator is not trivial. If this can happen for
15733 // multiple distinct direct bases of Class, diagnose it. (If it
15734 // only happens in one base, we'll diagnose it when synthesizing
15735 // that base class's move assignment operator.)
15736 CXXBaseSpecifier *&Existing =
15737 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15738 .first->second;
15739 if (Existing && Existing != &BI) {
15740 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15741 << Class << Base;
15742 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15743 << (Base->getCanonicalDecl() ==
15744 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15745 << Base << Existing->getType() << Existing->getSourceRange();
15746 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15747 << (Base->getCanonicalDecl() ==
15748 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15749 << Base << BI.getType() << BaseSpec->getSourceRange();
15750
15751 // Only diagnose each vbase once.
15752 Existing = nullptr;
15753 }
15754 } else {
15755 // Only walk over bases that have defaulted move assignment operators.
15756 // We assume that any user-provided move assignment operator handles
15757 // the multiple-moves-of-vbase case itself somehow.
15758 if (!SMOR.getMethod()->isDefaulted())
15759 continue;
15760
15761 // We're going to move the base classes of Base. Add them to the list.
15762 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15763 }
15764 }
15765 }
15766}
15767
15768void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15769 CXXMethodDecl *MoveAssignOperator) {
15770 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15771 assert((MoveAssignOperator->isDefaulted() &&
15772 MoveAssignOperator->isOverloadedOperator() &&
15773 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15774 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15775 !MoveAssignOperator->isDeleted()) &&
15776 "DefineImplicitMoveAssignment called for wrong function");
15777 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15778 return;
15779
15780 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15781 if (ClassDecl->isInvalidDecl()) {
15782 MoveAssignOperator->setInvalidDecl();
15783 return;
15784 }
15785
15786 // C++0x [class.copy]p28:
15787 // The implicitly-defined or move assignment operator for a non-union class
15788 // X performs memberwise move assignment of its subobjects. The direct base
15789 // classes of X are assigned first, in the order of their declaration in the
15790 // base-specifier-list, and then the immediate non-static data members of X
15791 // are assigned, in the order in which they were declared in the class
15792 // definition.
15793
15794 // Issue a warning if our implicit move assignment operator will move
15795 // from a virtual base more than once.
15796 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15797
15798 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15799
15800 // The exception specification is needed because we are defining the
15801 // function.
15802 ResolveExceptionSpec(Loc: CurrentLocation,
15803 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15804
15805 // Add a context note for diagnostics produced after this point.
15806 Scope.addContextNote(UseLoc: CurrentLocation);
15807
15808 // The statements that form the synthesized function body.
15809 SmallVector<Stmt*, 8> Statements;
15810
15811 // The parameter for the "other" object, which we are move from.
15812 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15813 QualType OtherRefType =
15814 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15815
15816 // Our location for everything implicitly-generated.
15817 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15818 ? MoveAssignOperator->getEndLoc()
15819 : MoveAssignOperator->getLocation();
15820
15821 // Builds a reference to the "other" object.
15822 RefBuilder OtherRef(Other, OtherRefType);
15823 // Cast to rvalue.
15824 MoveCastBuilder MoveOther(OtherRef);
15825
15826 // Builds the function object parameter.
15827 std::optional<ThisBuilder> This;
15828 std::optional<DerefBuilder> DerefThis;
15829 std::optional<RefBuilder> ExplicitObject;
15830 QualType ObjectType;
15831 bool IsArrow = false;
15832 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15833 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15834 if (ObjectType->isReferenceType())
15835 ObjectType = ObjectType->getPointeeType();
15836 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15837 } else {
15838 ObjectType = getCurrentThisType();
15839 This.emplace();
15840 DerefThis.emplace(args&: *This);
15841 IsArrow = !getLangOpts().HLSL;
15842 }
15843 ExprBuilder &ObjectParameter =
15844 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15845
15846 // Assign base classes.
15847 bool Invalid = false;
15848 for (auto &Base : ClassDecl->bases()) {
15849 // C++11 [class.copy]p28:
15850 // It is unspecified whether subobjects representing virtual base classes
15851 // are assigned more than once by the implicitly-defined copy assignment
15852 // operator.
15853 // FIXME: Do not assign to a vbase that will be assigned by some other base
15854 // class. For a move-assignment, this can result in the vbase being moved
15855 // multiple times.
15856
15857 // Form the assignment:
15858 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15859 QualType BaseType = Base.getType().getUnqualifiedType();
15860 if (!BaseType->isRecordType()) {
15861 Invalid = true;
15862 continue;
15863 }
15864
15865 CXXCastPath BasePath;
15866 BasePath.push_back(Elt: &Base);
15867
15868 // Construct the "from" expression, which is an implicit cast to the
15869 // appropriately-qualified base type.
15870 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15871
15872 // Implicitly cast "this" to the appropriately-qualified base type.
15873 // Dereference "this".
15874 CastBuilder To(
15875 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15876 : static_cast<ExprBuilder &>(*DerefThis),
15877 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15878 VK_LValue, BasePath);
15879
15880 // Build the move.
15881 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15882 To, From,
15883 /*CopyingBaseSubobject=*/true,
15884 /*Copying=*/false);
15885 if (Move.isInvalid()) {
15886 MoveAssignOperator->setInvalidDecl();
15887 return;
15888 }
15889
15890 // Success! Record the move.
15891 Statements.push_back(Elt: Move.getAs<Expr>());
15892 }
15893
15894 // Assign non-static members.
15895 for (auto *Field : ClassDecl->fields()) {
15896 // FIXME: We should form some kind of AST representation for the implied
15897 // memcpy in a union copy operation.
15898 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15899 continue;
15900
15901 if (Field->isInvalidDecl()) {
15902 Invalid = true;
15903 continue;
15904 }
15905
15906 // Check for members of reference type; we can't move those.
15907 if (Field->getType()->isReferenceType()) {
15908 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15909 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15910 << Field->getDeclName();
15911 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15912 Invalid = true;
15913 continue;
15914 }
15915
15916 // Check for members of const-qualified, non-class type.
15917 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15918 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15919 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15920 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15921 << Field->getDeclName();
15922 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15923 Invalid = true;
15924 continue;
15925 }
15926
15927 // Suppress assigning zero-width bitfields.
15928 if (Field->isZeroLengthBitField())
15929 continue;
15930
15931 QualType FieldType = Field->getType().getNonReferenceType();
15932 if (FieldType->isIncompleteArrayType()) {
15933 assert(ClassDecl->hasFlexibleArrayMember() &&
15934 "Incomplete array type is not valid");
15935 continue;
15936 }
15937
15938 // Build references to the field in the object we're copying from and to.
15939 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15940 LookupMemberName);
15941 MemberLookup.addDecl(D: Field);
15942 MemberLookup.resolveKind();
15943 MemberBuilder From(MoveOther, OtherRefType,
15944 /*IsArrow=*/false, MemberLookup);
15945 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15946
15947 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15948 "Member reference with rvalue base must be rvalue except for reference "
15949 "members, which aren't allowed for move assignment.");
15950
15951 // Build the move of this field.
15952 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15953 To, From,
15954 /*CopyingBaseSubobject=*/false,
15955 /*Copying=*/false);
15956 if (Move.isInvalid()) {
15957 MoveAssignOperator->setInvalidDecl();
15958 return;
15959 }
15960
15961 // Success! Record the copy.
15962 Statements.push_back(Elt: Move.getAs<Stmt>());
15963 }
15964
15965 if (!Invalid) {
15966 // Add a "return *this;"
15967 Expr *ThisExpr =
15968 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15969 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15970 : static_cast<ExprBuilder &>(*DerefThis))
15971 .build(S&: *this, Loc);
15972
15973 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15974 if (Return.isInvalid())
15975 Invalid = true;
15976 else
15977 Statements.push_back(Elt: Return.getAs<Stmt>());
15978 }
15979
15980 if (Invalid) {
15981 MoveAssignOperator->setInvalidDecl();
15982 return;
15983 }
15984
15985 StmtResult Body;
15986 {
15987 CompoundScopeRAII CompoundScope(*this);
15988 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15989 /*isStmtExpr=*/false);
15990 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15991 }
15992 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15993 MoveAssignOperator->markUsed(C&: Context);
15994
15995 if (ASTMutationListener *L = getASTMutationListener()) {
15996 L->CompletedImplicitDefinition(D: MoveAssignOperator);
15997 }
15998}
15999
16000CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
16001 CXXRecordDecl *ClassDecl) {
16002 // C++ [class.copy]p4:
16003 // If the class definition does not explicitly declare a copy
16004 // constructor, one is declared implicitly.
16005 assert(ClassDecl->needsImplicitCopyConstructor());
16006
16007 DeclaringSpecialMember DSM(*this, ClassDecl,
16008 CXXSpecialMemberKind::CopyConstructor);
16009 if (DSM.isAlreadyBeingDeclared())
16010 return nullptr;
16011
16012 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16013 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16014 /*OwnsTag=*/false);
16015 QualType ArgType = ClassType;
16016 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16017 if (Const)
16018 ArgType = ArgType.withConst();
16019
16020 LangAS AS = getDefaultCXXMethodAddrSpace();
16021 if (AS != LangAS::Default)
16022 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
16023
16024 ArgType = Context.getLValueReferenceType(T: ArgType);
16025
16026 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16027 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
16028
16029 DeclarationName Name
16030 = Context.DeclarationNames.getCXXConstructorName(
16031 Ty: Context.getCanonicalType(T: ClassType));
16032 SourceLocation ClassLoc = ClassDecl->getLocation();
16033 DeclarationNameInfo NameInfo(Name, ClassLoc);
16034
16035 // An implicitly-declared copy constructor is an inline public
16036 // member of its class.
16037 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
16038 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16039 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16040 /*isInline=*/true,
16041 /*isImplicitlyDeclared=*/true,
16042 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16043 : ConstexprSpecKind::Unspecified);
16044 CopyConstructor->setAccess(AS_public);
16045 CopyConstructor->setDefaulted();
16046
16047 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16048
16049 if (getLangOpts().CUDA)
16050 CUDA().inferTargetForImplicitSpecialMember(
16051 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
16052 /* ConstRHS */ Const,
16053 /* Diagnose */ false);
16054
16055 // During template instantiation of special member functions we need a
16056 // reliable TypeSourceInfo for the parameter types in order to allow functions
16057 // to be substituted.
16058 TypeSourceInfo *TSI = nullptr;
16059 if (inTemplateInstantiation() && ClassDecl->isLambda())
16060 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
16061
16062 // Add the parameter to the constructor.
16063 ParmVarDecl *FromParam =
16064 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
16065 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
16066 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
16067 CopyConstructor->setParams(FromParam);
16068
16069 CopyConstructor->setTrivial(
16070 ClassDecl->needsOverloadResolutionForCopyConstructor()
16071 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16072 CSM: CXXSpecialMemberKind::CopyConstructor)
16073 : ClassDecl->hasTrivialCopyConstructor());
16074
16075 CopyConstructor->setTrivialForCall(
16076 ClassDecl->hasAttr<TrivialABIAttr>() ||
16077 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16078 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16079 CSM: CXXSpecialMemberKind::CopyConstructor,
16080 TAH: TrivialABIHandling::ConsiderTrivialABI)
16081 : ClassDecl->hasTrivialCopyConstructorForCall()));
16082
16083 // Note that we have declared this constructor.
16084 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16085
16086 Scope *S = getScopeForContext(Ctx: ClassDecl);
16087 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16088
16089 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16090 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16091 ClassDecl->setImplicitCopyConstructorIsDeleted();
16092 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16093 }
16094
16095 if (S)
16096 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16097 ClassDecl->addDecl(D: CopyConstructor);
16098
16099 return CopyConstructor;
16100}
16101
16102void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16103 CXXConstructorDecl *CopyConstructor) {
16104 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16105 assert((CopyConstructor->isDefaulted() &&
16106 CopyConstructor->isCopyConstructor() &&
16107 !CopyConstructor->doesThisDeclarationHaveABody() &&
16108 !CopyConstructor->isDeleted()) &&
16109 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16110 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16111 return;
16112
16113 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16114 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16115
16116 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16117
16118 // The exception specification is needed because we are defining the
16119 // function.
16120 ResolveExceptionSpec(Loc: CurrentLocation,
16121 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16122 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16123
16124 // Add a context note for diagnostics produced after this point.
16125 Scope.addContextNote(UseLoc: CurrentLocation);
16126
16127 // C++11 [class.copy]p7:
16128 // The [definition of an implicitly declared copy constructor] is
16129 // deprecated if the class has a user-declared copy assignment operator
16130 // or a user-declared destructor.
16131 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16132 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16133
16134 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16135 CopyConstructor->setInvalidDecl();
16136 } else {
16137 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16138 ? CopyConstructor->getEndLoc()
16139 : CopyConstructor->getLocation();
16140 Sema::CompoundScopeRAII CompoundScope(*this);
16141 CopyConstructor->setBody(
16142 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16143 CopyConstructor->markUsed(C&: Context);
16144 }
16145
16146 if (ASTMutationListener *L = getASTMutationListener()) {
16147 L->CompletedImplicitDefinition(D: CopyConstructor);
16148 }
16149}
16150
16151CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16152 CXXRecordDecl *ClassDecl) {
16153 assert(ClassDecl->needsImplicitMoveConstructor());
16154
16155 DeclaringSpecialMember DSM(*this, ClassDecl,
16156 CXXSpecialMemberKind::MoveConstructor);
16157 if (DSM.isAlreadyBeingDeclared())
16158 return nullptr;
16159
16160 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16161 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16162 /*OwnsTag=*/false);
16163
16164 QualType ArgType = ClassType;
16165 LangAS AS = getDefaultCXXMethodAddrSpace();
16166 if (AS != LangAS::Default)
16167 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16168 ArgType = Context.getRValueReferenceType(T: ArgType);
16169
16170 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16171 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16172
16173 DeclarationName Name
16174 = Context.DeclarationNames.getCXXConstructorName(
16175 Ty: Context.getCanonicalType(T: ClassType));
16176 SourceLocation ClassLoc = ClassDecl->getLocation();
16177 DeclarationNameInfo NameInfo(Name, ClassLoc);
16178
16179 // C++11 [class.copy]p11:
16180 // An implicitly-declared copy/move constructor is an inline public
16181 // member of its class.
16182 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16183 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16184 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16185 /*isInline=*/true,
16186 /*isImplicitlyDeclared=*/true,
16187 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16188 : ConstexprSpecKind::Unspecified);
16189 MoveConstructor->setAccess(AS_public);
16190 MoveConstructor->setDefaulted();
16191
16192 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16193
16194 if (getLangOpts().CUDA)
16195 CUDA().inferTargetForImplicitSpecialMember(
16196 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16197 /* ConstRHS */ false,
16198 /* Diagnose */ false);
16199
16200 // Add the parameter to the constructor.
16201 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16202 StartLoc: ClassLoc, IdLoc: ClassLoc,
16203 /*IdentifierInfo=*/Id: nullptr,
16204 T: ArgType, /*TInfo=*/nullptr,
16205 S: SC_None, DefArg: nullptr);
16206 MoveConstructor->setParams(FromParam);
16207
16208 MoveConstructor->setTrivial(
16209 ClassDecl->needsOverloadResolutionForMoveConstructor()
16210 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16211 CSM: CXXSpecialMemberKind::MoveConstructor)
16212 : ClassDecl->hasTrivialMoveConstructor());
16213
16214 MoveConstructor->setTrivialForCall(
16215 ClassDecl->hasAttr<TrivialABIAttr>() ||
16216 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16217 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16218 CSM: CXXSpecialMemberKind::MoveConstructor,
16219 TAH: TrivialABIHandling::ConsiderTrivialABI)
16220 : ClassDecl->hasTrivialMoveConstructorForCall()));
16221
16222 // Note that we have declared this constructor.
16223 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16224
16225 Scope *S = getScopeForContext(Ctx: ClassDecl);
16226 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16227
16228 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16229 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16230 ClassDecl->setImplicitMoveConstructorIsDeleted();
16231 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16232 }
16233
16234 if (S)
16235 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16236 ClassDecl->addDecl(D: MoveConstructor);
16237
16238 return MoveConstructor;
16239}
16240
16241void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16242 CXXConstructorDecl *MoveConstructor) {
16243 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16244 assert((MoveConstructor->isDefaulted() &&
16245 MoveConstructor->isMoveConstructor() &&
16246 !MoveConstructor->doesThisDeclarationHaveABody() &&
16247 !MoveConstructor->isDeleted()) &&
16248 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16249 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16250 return;
16251
16252 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16253 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16254
16255 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16256
16257 // The exception specification is needed because we are defining the
16258 // function.
16259 ResolveExceptionSpec(Loc: CurrentLocation,
16260 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16261 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16262
16263 // Add a context note for diagnostics produced after this point.
16264 Scope.addContextNote(UseLoc: CurrentLocation);
16265
16266 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16267 MoveConstructor->setInvalidDecl();
16268 } else {
16269 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16270 ? MoveConstructor->getEndLoc()
16271 : MoveConstructor->getLocation();
16272 Sema::CompoundScopeRAII CompoundScope(*this);
16273 MoveConstructor->setBody(
16274 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16275 MoveConstructor->markUsed(C&: Context);
16276 }
16277
16278 if (ASTMutationListener *L = getASTMutationListener()) {
16279 L->CompletedImplicitDefinition(D: MoveConstructor);
16280 }
16281}
16282
16283bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16284 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16285}
16286
16287void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16288 SourceLocation CurrentLocation,
16289 CXXConversionDecl *Conv) {
16290 SynthesizedFunctionScope Scope(*this, Conv);
16291 assert(!Conv->getReturnType()->isUndeducedType());
16292
16293 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16294 CallingConv CC =
16295 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16296
16297 CXXRecordDecl *Lambda = Conv->getParent();
16298 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16299 FunctionDecl *Invoker =
16300 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16301 ? CallOp
16302 : Lambda->getLambdaStaticInvoker(CC);
16303
16304 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16305 CallOp = InstantiateFunctionDeclaration(
16306 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16307 if (!CallOp)
16308 return;
16309
16310 if (CallOp != Invoker) {
16311 Invoker = InstantiateFunctionDeclaration(
16312 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16313 Loc: CurrentLocation);
16314 if (!Invoker)
16315 return;
16316 }
16317 }
16318
16319 if (CallOp->isInvalidDecl())
16320 return;
16321
16322 // Mark the call operator referenced (and add to pending instantiations
16323 // if necessary).
16324 // For both the conversion and static-invoker template specializations
16325 // we construct their body's in this function, so no need to add them
16326 // to the PendingInstantiations.
16327 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16328
16329 if (Invoker != CallOp) {
16330 // Fill in the __invoke function with a dummy implementation. IR generation
16331 // will fill in the actual details. Update its type in case it contained
16332 // an 'auto'.
16333 Invoker->markUsed(C&: Context);
16334 Invoker->setReferenced();
16335 Invoker->setType(Conv->getReturnType()->getPointeeType());
16336 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16337 }
16338
16339 // Construct the body of the conversion function { return __invoke; }.
16340 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16341 Loc: Conv->getLocation());
16342 assert(FunctionRef && "Can't refer to __invoke function?");
16343 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16344 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16345 LB: Conv->getLocation(), RB: Conv->getLocation()));
16346 Conv->markUsed(C&: Context);
16347 Conv->setReferenced();
16348
16349 if (ASTMutationListener *L = getASTMutationListener()) {
16350 L->CompletedImplicitDefinition(D: Conv);
16351 if (Invoker != CallOp)
16352 L->CompletedImplicitDefinition(D: Invoker);
16353 }
16354}
16355
16356void Sema::DefineImplicitLambdaToBlockPointerConversion(
16357 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16358 assert(!Conv->getParent()->isGenericLambda());
16359
16360 SynthesizedFunctionScope Scope(*this, Conv);
16361
16362 // Copy-initialize the lambda object as needed to capture it.
16363 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16364 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16365
16366 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16367 ConvLocation: Conv->getLocation(),
16368 Conv, Src: DerefThis);
16369
16370 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16371 // behavior. Note that only the general conversion function does this
16372 // (since it's unusable otherwise); in the case where we inline the
16373 // block literal, it has block literal lifetime semantics.
16374 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16375 BuildBlock = ImplicitCastExpr::Create(
16376 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16377 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16378
16379 if (BuildBlock.isInvalid()) {
16380 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16381 Conv->setInvalidDecl();
16382 return;
16383 }
16384
16385 // Create the return statement that returns the block from the conversion
16386 // function.
16387 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16388 if (Return.isInvalid()) {
16389 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16390 Conv->setInvalidDecl();
16391 return;
16392 }
16393
16394 // Set the body of the conversion function.
16395 Stmt *ReturnS = Return.get();
16396 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16397 LB: Conv->getLocation(), RB: Conv->getLocation()));
16398 Conv->markUsed(C&: Context);
16399
16400 // We're done; notify the mutation listener, if any.
16401 if (ASTMutationListener *L = getASTMutationListener()) {
16402 L->CompletedImplicitDefinition(D: Conv);
16403 }
16404}
16405
16406/// Determine whether the given list arguments contains exactly one
16407/// "real" (non-default) argument.
16408static bool hasOneRealArgument(MultiExprArg Args) {
16409 switch (Args.size()) {
16410 case 0:
16411 return false;
16412
16413 default:
16414 if (!Args[1]->isDefaultArgument())
16415 return false;
16416
16417 [[fallthrough]];
16418 case 1:
16419 return !Args[0]->isDefaultArgument();
16420 }
16421
16422 return false;
16423}
16424
16425ExprResult Sema::BuildCXXConstructExpr(
16426 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16427 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16428 bool HadMultipleCandidates, bool IsListInitialization,
16429 bool IsStdInitListInitialization, bool RequiresZeroInit,
16430 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16431 bool Elidable = false;
16432
16433 // C++0x [class.copy]p34:
16434 // When certain criteria are met, an implementation is allowed to
16435 // omit the copy/move construction of a class object, even if the
16436 // copy/move constructor and/or destructor for the object have
16437 // side effects. [...]
16438 // - when a temporary class object that has not been bound to a
16439 // reference (12.2) would be copied/moved to a class object
16440 // with the same cv-unqualified type, the copy/move operation
16441 // can be omitted by constructing the temporary object
16442 // directly into the target of the omitted copy/move
16443 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16444 // FIXME: Converting constructors should also be accepted.
16445 // But to fix this, the logic that digs down into a CXXConstructExpr
16446 // to find the source object needs to handle it.
16447 // Right now it assumes the source object is passed directly as the
16448 // first argument.
16449 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16450 Expr *SubExpr = ExprArgs[0];
16451 // FIXME: Per above, this is also incorrect if we want to accept
16452 // converting constructors, as isTemporaryObject will
16453 // reject temporaries with different type from the
16454 // CXXRecord itself.
16455 Elidable = SubExpr->isTemporaryObject(
16456 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16457 }
16458
16459 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16460 FoundDecl, Constructor,
16461 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16462 IsListInitialization,
16463 IsStdInitListInitialization, RequiresZeroInit,
16464 ConstructKind, ParenRange);
16465}
16466
16467ExprResult Sema::BuildCXXConstructExpr(
16468 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16469 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16470 bool HadMultipleCandidates, bool IsListInitialization,
16471 bool IsStdInitListInitialization, bool RequiresZeroInit,
16472 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16473 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16474 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16475 // The only way to get here is if we did overload resolution to find the
16476 // shadow decl, so we don't need to worry about re-checking the trailing
16477 // requires clause.
16478 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16479 return ExprError();
16480 }
16481
16482 return BuildCXXConstructExpr(
16483 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16484 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16485 RequiresZeroInit, ConstructKind, ParenRange);
16486}
16487
16488/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16489/// including handling of its default argument expressions.
16490ExprResult Sema::BuildCXXConstructExpr(
16491 SourceLocation ConstructLoc, QualType DeclInitType,
16492 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16493 bool HadMultipleCandidates, bool IsListInitialization,
16494 bool IsStdInitListInitialization, bool RequiresZeroInit,
16495 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16496 assert(declaresSameEntity(
16497 Constructor->getParent(),
16498 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16499 "given constructor for wrong type");
16500 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16501 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16502 return ExprError();
16503
16504 return CheckForImmediateInvocation(
16505 E: CXXConstructExpr::Create(
16506 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16507 HadMultipleCandidates, ListInitialization: IsListInitialization,
16508 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16509 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16510 Decl: Constructor);
16511}
16512
16513void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16514 if (VD->isInvalidDecl()) return;
16515 // If initializing the variable failed, don't also diagnose problems with
16516 // the destructor, they're likely related.
16517 if (VD->getInit() && VD->getInit()->containsErrors())
16518 return;
16519
16520 ClassDecl = ClassDecl->getDefinitionOrSelf();
16521 if (ClassDecl->isInvalidDecl()) return;
16522 if (ClassDecl->hasIrrelevantDestructor()) return;
16523 if (ClassDecl->isDependentContext()) return;
16524
16525 if (VD->isNoDestroy(getASTContext()))
16526 return;
16527
16528 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16529 // The result of `LookupDestructor` might be nullptr if the destructor is
16530 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16531 // will not be selected by `CXXRecordDecl::getDestructor()`.
16532 if (!Destructor)
16533 return;
16534 // If this is an array, we'll require the destructor during initialization, so
16535 // we can skip over this. We still want to emit exit-time destructor warnings
16536 // though.
16537 if (!VD->getType()->isArrayType()) {
16538 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16539 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16540 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16541 << VD->getDeclName() << VD->getType());
16542 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16543 }
16544
16545 if (Destructor->isTrivial()) return;
16546
16547 // If the destructor is constexpr, check whether the variable has constant
16548 // destruction now.
16549 if (Destructor->isConstexpr()) {
16550 bool HasConstantInit = false;
16551 if (VD->getInit() && !VD->getInit()->isValueDependent())
16552 HasConstantInit = VD->evaluateValue();
16553 SmallVector<PartialDiagnosticAt, 8> Notes;
16554 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16555 HasConstantInit) {
16556 Diag(Loc: VD->getLocation(),
16557 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16558 for (const PartialDiagnosticAt &Note : Notes)
16559 Diag(Loc: Note.first, PD: Note.second);
16560 }
16561 }
16562
16563 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16564 return;
16565
16566 // Emit warning for non-trivial dtor in global scope (a real global,
16567 // class-static, function-static).
16568 if (!VD->hasAttr<AlwaysDestroyAttr>())
16569 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16570
16571 // TODO: this should be re-enabled for static locals by !CXAAtExit
16572 if (!VD->isStaticLocal())
16573 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16574}
16575
16576bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16577 QualType DeclInitType, MultiExprArg ArgsPtr,
16578 SourceLocation Loc,
16579 SmallVectorImpl<Expr *> &ConvertedArgs,
16580 bool AllowExplicit,
16581 bool IsListInitialization) {
16582 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16583 unsigned NumArgs = ArgsPtr.size();
16584 Expr **Args = ArgsPtr.data();
16585
16586 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16587 unsigned NumParams = Proto->getNumParams();
16588
16589 // If too few arguments are available, we'll fill in the rest with defaults.
16590 if (NumArgs < NumParams)
16591 ConvertedArgs.reserve(N: NumParams);
16592 else
16593 ConvertedArgs.reserve(N: NumArgs);
16594
16595 VariadicCallType CallType = Proto->isVariadic()
16596 ? VariadicCallType::Constructor
16597 : VariadicCallType::DoesNotApply;
16598 SmallVector<Expr *, 8> AllArgs;
16599 bool Invalid = GatherArgumentsForCall(
16600 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16601 CallType, AllowExplicit, IsListInitialization);
16602 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16603
16604 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16605
16606 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16607 Proto, Loc);
16608
16609 return Invalid;
16610}
16611
16612TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16613 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16614 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16615}
16616
16617FunctionDecl *
16618Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16619 QualType DeallocType, SourceLocation Loc) {
16620 if (DeallocType.isNull())
16621 return nullptr;
16622
16623 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16624 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16625 return nullptr;
16626
16627 if (FnDecl->isVariadic())
16628 return nullptr;
16629
16630 unsigned NumParams = FnDecl->getNumParams();
16631 constexpr unsigned RequiredParameterCount =
16632 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16633 // A usual deallocation function has no placement parameters
16634 if (NumParams != RequiredParameterCount)
16635 return nullptr;
16636
16637 // A type aware allocation is only usual if the only dependent parameter is
16638 // the first parameter.
16639 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16640 P: [](const ParmVarDecl *ParamDecl) {
16641 return ParamDecl->getType()->isDependentType();
16642 }))
16643 return nullptr;
16644
16645 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16646 if (SpecializedTypeIdentity.isNull())
16647 return nullptr;
16648
16649 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16650 ArgTypes.reserve(N: NumParams);
16651
16652 // The first parameter to a type aware operator delete is by definition the
16653 // type-identity argument, so we explicitly set this to the target
16654 // type-identity type, the remaining usual parameters should then simply match
16655 // the type declared in the function template.
16656 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16657 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16658 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16659
16660 FunctionProtoType::ExtProtoInfo EPI;
16661 QualType ExpectedFunctionType =
16662 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16663 sema::TemplateDeductionInfo Info(Loc);
16664 FunctionDecl *Result;
16665 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16666 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16667 return nullptr;
16668 return Result;
16669}
16670
16671static inline bool
16672CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16673 const FunctionDecl *FnDecl) {
16674 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16675 if (isa<NamespaceDecl>(Val: DC)) {
16676 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16677 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16678 << FnDecl->getDeclName();
16679 }
16680
16681 if (isa<TranslationUnitDecl>(Val: DC) &&
16682 FnDecl->getStorageClass() == SC_Static) {
16683 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16684 DiagID: diag::err_operator_new_delete_declared_static)
16685 << FnDecl->getDeclName();
16686 }
16687
16688 return false;
16689}
16690
16691static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16692 const PointerType *PtrTy) {
16693 auto &Ctx = SemaRef.Context;
16694 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16695 PtrQuals.removeAddressSpace();
16696 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16697 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16698}
16699
16700enum class AllocationOperatorKind { New, Delete };
16701
16702static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16703 const FunctionDecl *FD,
16704 bool *WasMalformed) {
16705 const Decl *MalformedDecl = nullptr;
16706 if (FD->getNumParams() > 0 &&
16707 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16708 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16709 return true;
16710
16711 if (!MalformedDecl)
16712 return false;
16713
16714 if (WasMalformed)
16715 *WasMalformed = true;
16716
16717 return true;
16718}
16719
16720static bool isDestroyingDeleteT(QualType Type) {
16721 auto *RD = Type->getAsCXXRecordDecl();
16722 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16723 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16724}
16725
16726static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16727 const FunctionDecl *FD) {
16728 // C++ P0722:
16729 // Within a class C, a single object deallocation function with signature
16730 // (T, std::destroying_delete_t, <more params>)
16731 // is a destroying operator delete.
16732 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16733 SemaRef, FD, /*WasMalformed=*/nullptr);
16734 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16735 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16736 FD->getNumParams() > DestroyingDeleteIdx &&
16737 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16738}
16739
16740static inline bool CheckOperatorNewDeleteTypes(
16741 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16742 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16743 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16744 auto NormalizeType = [&SemaRef](QualType T) {
16745 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16746 // The operator is valid on any address space for OpenCL.
16747 // Drop address space from actual and expected result types.
16748 if (const auto PtrTy = T->template getAs<PointerType>())
16749 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16750 }
16751 return SemaRef.Context.getCanonicalType(T);
16752 };
16753
16754 const unsigned NumParams = FnDecl->getNumParams();
16755 unsigned FirstNonTypeParam = 0;
16756 bool MalformedTypeIdentity = false;
16757 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16758 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16759 unsigned MinimumMandatoryArgumentCount = 1;
16760 unsigned SizeParameterIndex = 0;
16761 if (IsPotentiallyTypeAware) {
16762 // We don't emit this diagnosis for template instantiations as we will
16763 // have already emitted it for the original template declaration.
16764 if (!FnDecl->isTemplateInstantiation())
16765 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16766
16767 if (OperatorKind == AllocationOperatorKind::New) {
16768 SizeParameterIndex = 1;
16769 MinimumMandatoryArgumentCount =
16770 FunctionDecl::RequiredTypeAwareNewParameterCount;
16771 } else {
16772 SizeParameterIndex = 2;
16773 MinimumMandatoryArgumentCount =
16774 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16775 }
16776 FirstNonTypeParam = 1;
16777 }
16778
16779 bool IsPotentiallyDestroyingDelete =
16780 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16781
16782 if (IsPotentiallyDestroyingDelete) {
16783 ++MinimumMandatoryArgumentCount;
16784 ++SizeParameterIndex;
16785 }
16786
16787 if (NumParams < MinimumMandatoryArgumentCount)
16788 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16789 DiagID: diag::err_operator_new_delete_too_few_parameters)
16790 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16791 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16792
16793 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16794 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16795 if (ParamDecl->hasDefaultArg())
16796 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16797 DiagID: diag::err_operator_new_default_arg)
16798 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16799 }
16800
16801 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16802 QualType CanResultType = NormalizeType(FnType->getReturnType());
16803 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16804 QualType CanExpectedSizeOrAddressParamType =
16805 NormalizeType(ExpectedSizeOrAddressParamType);
16806
16807 // Check that the result type is what we expect.
16808 if (CanResultType != CanExpectedResultType) {
16809 // Reject even if the type is dependent; an operator delete function is
16810 // required to have a non-dependent result type.
16811 return SemaRef.Diag(
16812 Loc: FnDecl->getLocation(),
16813 DiagID: CanResultType->isDependentType()
16814 ? diag::err_operator_new_delete_dependent_result_type
16815 : diag::err_operator_new_delete_invalid_result_type)
16816 << FnDecl->getDeclName() << ExpectedResultType;
16817 }
16818
16819 // A function template must have at least 2 parameters.
16820 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16821 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16822 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16823 << FnDecl->getDeclName();
16824
16825 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16826 auto FallbackType) -> bool {
16827 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16828 if (ExpectedType.isNull()) {
16829 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16830 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16831 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16832 << ParamDecl->getSourceRange();
16833 }
16834 CanQualType CanExpectedTy =
16835 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16836 auto ActualParamType =
16837 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16838 if (ActualParamType == CanExpectedTy)
16839 return false;
16840 unsigned Diagnostic = ActualParamType->isDependentType()
16841 ? DependentParamTypeDiag
16842 : InvalidParamTypeDiag;
16843 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16844 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16845 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16846 << FallbackType << ParamDecl->getSourceRange();
16847 };
16848
16849 // Check that the first parameter type is what we expect.
16850 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16851 return true;
16852
16853 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16854
16855 // If the first parameter type is not a type-identity we're done, otherwise
16856 // we need to ensure the size and alignment parameters have the correct type
16857 if (!IsPotentiallyTypeAware)
16858 return false;
16859
16860 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16861 return true;
16862 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16863 CanQualType StdAlignValT =
16864 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16865 : CanQualType();
16866 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16867 return true;
16868
16869 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16870 return MalformedTypeIdentity;
16871}
16872
16873static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16874 // C++ [basic.stc.dynamic.allocation]p1:
16875 // A program is ill-formed if an allocation function is declared in a
16876 // namespace scope other than global scope or declared static in global
16877 // scope.
16878 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16879 return true;
16880
16881 CanQualType SizeTy =
16882 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16883
16884 // C++ [basic.stc.dynamic.allocation]p1:
16885 // The return type shall be void*. The first parameter shall have type
16886 // std::size_t.
16887 return CheckOperatorNewDeleteTypes(
16888 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16889 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16890 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16891}
16892
16893static bool
16894CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16895 // C++ [basic.stc.dynamic.deallocation]p1:
16896 // A program is ill-formed if deallocation functions are declared in a
16897 // namespace scope other than global scope or declared static in global
16898 // scope.
16899 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16900 return true;
16901
16902 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16903 auto ConstructDestroyingDeleteAddressType = [&]() {
16904 assert(MD);
16905 return SemaRef.Context.getPointerType(
16906 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16907 };
16908
16909 // C++ P2719: A destroying operator delete cannot be type aware
16910 // so for QoL we actually check for this explicitly by considering
16911 // an destroying-delete appropriate address type and the presence of
16912 // any parameter of type destroying_delete_t as an erroneous attempt
16913 // to declare a type aware destroying delete, rather than emitting a
16914 // pile of incorrect parameter type errors.
16915 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16916 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16917 QualType AddressParamType =
16918 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16919 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16920 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16921 // The address parameter type implies an author trying to construct a
16922 // type aware destroying delete, so we'll see if we can find a parameter
16923 // of type `std::destroying_delete_t`, and if we find it we'll report
16924 // this as being an attempt at a type aware destroying delete just stop
16925 // here. If we don't do this, the resulting incorrect parameter ordering
16926 // results in a pile mismatched argument type errors that don't explain
16927 // the core problem.
16928 for (auto Param : MD->parameters()) {
16929 if (isDestroyingDeleteT(Type: Param->getType())) {
16930 SemaRef.Diag(Loc: MD->getLocation(),
16931 DiagID: diag::err_type_aware_destroying_operator_delete)
16932 << Param->getSourceRange();
16933 return true;
16934 }
16935 }
16936 }
16937 }
16938
16939 // C++ P0722:
16940 // Within a class C, the first parameter of a destroying operator delete
16941 // shall be of type C *. The first parameter of any other deallocation
16942 // function shall be of type void *.
16943 CanQualType ExpectedAddressParamType =
16944 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16945 ? SemaRef.Context.getPointerType(
16946 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16947 : SemaRef.Context.VoidPtrTy;
16948
16949 // C++ [basic.stc.dynamic.deallocation]p2:
16950 // Each deallocation function shall return void
16951 if (CheckOperatorNewDeleteTypes(
16952 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16953 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16954 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16955 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
16956 return true;
16957
16958 // C++ P0722:
16959 // A destroying operator delete shall be a usual deallocation function.
16960 if (MD && !MD->getParent()->isDependentContext() &&
16961 MD->isDestroyingOperatorDelete()) {
16962 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16963 SemaRef.Diag(Loc: MD->getLocation(),
16964 DiagID: diag::err_destroying_operator_delete_not_usual);
16965 return true;
16966 }
16967 }
16968
16969 return false;
16970}
16971
16972bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16973 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16974 "Expected an overloaded operator declaration");
16975
16976 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16977
16978 // C++ [over.oper]p5:
16979 // The allocation and deallocation functions, operator new,
16980 // operator new[], operator delete and operator delete[], are
16981 // described completely in 3.7.3. The attributes and restrictions
16982 // found in the rest of this subclause do not apply to them unless
16983 // explicitly stated in 3.7.3.
16984 if (Op == OO_Delete || Op == OO_Array_Delete)
16985 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16986
16987 if (Op == OO_New || Op == OO_Array_New)
16988 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16989
16990 // C++ [over.oper]p7:
16991 // An operator function shall either be a member function or
16992 // be a non-member function and have at least one parameter
16993 // whose type is a class, a reference to a class, an enumeration,
16994 // or a reference to an enumeration.
16995 // Note: Before C++23, a member function could not be static. The only member
16996 // function allowed to be static is the call operator function.
16997 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16998 if (MethodDecl->isStatic()) {
16999 if (Op == OO_Call || Op == OO_Subscript)
17000 Diag(Loc: FnDecl->getLocation(),
17001 DiagID: (LangOpts.CPlusPlus23
17002 ? diag::warn_cxx20_compat_operator_overload_static
17003 : diag::ext_operator_overload_static))
17004 << FnDecl;
17005 else
17006 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
17007 << FnDecl;
17008 }
17009 } else {
17010 bool ClassOrEnumParam = false;
17011 for (auto *Param : FnDecl->parameters()) {
17012 QualType ParamType = Param->getType().getNonReferenceType();
17013 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17014 ParamType->isEnumeralType()) {
17015 ClassOrEnumParam = true;
17016 break;
17017 }
17018 }
17019
17020 if (!ClassOrEnumParam)
17021 return Diag(Loc: FnDecl->getLocation(),
17022 DiagID: diag::err_operator_overload_needs_class_or_enum)
17023 << FnDecl->getDeclName();
17024 }
17025
17026 // C++ [over.oper]p8:
17027 // An operator function cannot have default arguments (8.3.6),
17028 // except where explicitly stated below.
17029 //
17030 // Only the function-call operator (C++ [over.call]p1) and the subscript
17031 // operator (CWG2507) allow default arguments.
17032 if (Op != OO_Call) {
17033 ParmVarDecl *FirstDefaultedParam = nullptr;
17034 for (auto *Param : FnDecl->parameters()) {
17035 if (Param->hasDefaultArg()) {
17036 FirstDefaultedParam = Param;
17037 break;
17038 }
17039 }
17040 if (FirstDefaultedParam) {
17041 if (Op == OO_Subscript) {
17042 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17043 ? diag::ext_subscript_overload
17044 : diag::error_subscript_overload)
17045 << FnDecl->getDeclName() << 1
17046 << FirstDefaultedParam->getDefaultArgRange();
17047 } else {
17048 return Diag(Loc: FirstDefaultedParam->getLocation(),
17049 DiagID: diag::err_operator_overload_default_arg)
17050 << FnDecl->getDeclName()
17051 << FirstDefaultedParam->getDefaultArgRange();
17052 }
17053 }
17054 }
17055
17056 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17057 { false, false, false }
17058#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17059 , { Unary, Binary, MemberOnly }
17060#include "clang/Basic/OperatorKinds.def"
17061 };
17062
17063 bool CanBeUnaryOperator = OperatorUses[Op][0];
17064 bool CanBeBinaryOperator = OperatorUses[Op][1];
17065 bool MustBeMemberOperator = OperatorUses[Op][2];
17066
17067 // C++ [over.oper]p8:
17068 // [...] Operator functions cannot have more or fewer parameters
17069 // than the number required for the corresponding operator, as
17070 // described in the rest of this subclause.
17071 unsigned NumParams = FnDecl->getNumParams() +
17072 (isa<CXXMethodDecl>(Val: FnDecl) &&
17073 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17074 ? 1
17075 : 0);
17076 if (Op != OO_Call && Op != OO_Subscript &&
17077 ((NumParams == 1 && !CanBeUnaryOperator) ||
17078 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17079 (NumParams > 2))) {
17080 // We have the wrong number of parameters.
17081 unsigned ErrorKind;
17082 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17083 ErrorKind = 2; // 2 -> unary or binary.
17084 } else if (CanBeUnaryOperator) {
17085 ErrorKind = 0; // 0 -> unary
17086 } else {
17087 assert(CanBeBinaryOperator &&
17088 "All non-call overloaded operators are unary or binary!");
17089 ErrorKind = 1; // 1 -> binary
17090 }
17091 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17092 << FnDecl->getDeclName() << NumParams << ErrorKind;
17093 }
17094
17095 if (Op == OO_Subscript && NumParams != 2) {
17096 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17097 ? diag::ext_subscript_overload
17098 : diag::error_subscript_overload)
17099 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17100 }
17101
17102 // Overloaded operators other than operator() and operator[] cannot be
17103 // variadic.
17104 if (Op != OO_Call &&
17105 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17106 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17107 << FnDecl->getDeclName();
17108 }
17109
17110 // Some operators must be member functions.
17111 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17112 return Diag(Loc: FnDecl->getLocation(),
17113 DiagID: diag::err_operator_overload_must_be_member)
17114 << FnDecl->getDeclName();
17115 }
17116
17117 // C++ [over.inc]p1:
17118 // The user-defined function called operator++ implements the
17119 // prefix and postfix ++ operator. If this function is a member
17120 // function with no parameters, or a non-member function with one
17121 // parameter of class or enumeration type, it defines the prefix
17122 // increment operator ++ for objects of that type. If the function
17123 // is a member function with one parameter (which shall be of type
17124 // int) or a non-member function with two parameters (the second
17125 // of which shall be of type int), it defines the postfix
17126 // increment operator ++ for objects of that type.
17127 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17128 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17129 QualType ParamType = LastParam->getType();
17130
17131 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17132 !ParamType->isDependentType())
17133 return Diag(Loc: LastParam->getLocation(),
17134 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17135 << LastParam->getType() << (Op == OO_MinusMinus);
17136 }
17137
17138 return false;
17139}
17140
17141static bool
17142checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17143 FunctionTemplateDecl *TpDecl) {
17144 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17145
17146 // Must have one or two template parameters.
17147 if (TemplateParams->size() == 1) {
17148 NonTypeTemplateParmDecl *PmDecl =
17149 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17150
17151 // The template parameter must be a char parameter pack.
17152 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17153 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17154 return false;
17155
17156 // C++20 [over.literal]p5:
17157 // A string literal operator template is a literal operator template
17158 // whose template-parameter-list comprises a single non-type
17159 // template-parameter of class type.
17160 //
17161 // As a DR resolution, we also allow placeholders for deduced class
17162 // template specializations.
17163 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17164 !PmDecl->isTemplateParameterPack() &&
17165 (PmDecl->getType()->isRecordType() ||
17166 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17167 return false;
17168 } else if (TemplateParams->size() == 2) {
17169 TemplateTypeParmDecl *PmType =
17170 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17171 NonTypeTemplateParmDecl *PmArgs =
17172 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17173
17174 // The second template parameter must be a parameter pack with the
17175 // first template parameter as its type.
17176 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17177 PmArgs->isTemplateParameterPack()) {
17178 if (const auto *TArgs =
17179 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17180 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17181 TArgs->getIndex() == PmType->getIndex()) {
17182 if (!SemaRef.inTemplateInstantiation())
17183 SemaRef.Diag(Loc: TpDecl->getLocation(),
17184 DiagID: diag::ext_string_literal_operator_template);
17185 return false;
17186 }
17187 }
17188 }
17189
17190 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17191 DiagID: diag::err_literal_operator_template)
17192 << TpDecl->getTemplateParameters()->getSourceRange();
17193 return true;
17194}
17195
17196bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17197 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17198 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17199 << FnDecl->getDeclName();
17200 return true;
17201 }
17202
17203 if (FnDecl->isExternC()) {
17204 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17205 if (const LinkageSpecDecl *LSD =
17206 FnDecl->getDeclContext()->getExternCContext())
17207 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17208 return true;
17209 }
17210
17211 // This might be the definition of a literal operator template.
17212 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17213
17214 // This might be a specialization of a literal operator template.
17215 if (!TpDecl)
17216 TpDecl = FnDecl->getPrimaryTemplate();
17217
17218 // template <char...> type operator "" name() and
17219 // template <class T, T...> type operator "" name() are the only valid
17220 // template signatures, and the only valid signatures with no parameters.
17221 //
17222 // C++20 also allows template <SomeClass T> type operator "" name().
17223 if (TpDecl) {
17224 if (FnDecl->param_size() != 0) {
17225 Diag(Loc: FnDecl->getLocation(),
17226 DiagID: diag::err_literal_operator_template_with_params);
17227 return true;
17228 }
17229
17230 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17231 return true;
17232
17233 } else if (FnDecl->param_size() == 1) {
17234 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17235
17236 QualType ParamType = Param->getType().getUnqualifiedType();
17237
17238 // Only unsigned long long int, long double, any character type, and const
17239 // char * are allowed as the only parameters.
17240 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17241 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17242 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17243 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17244 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17245 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17246 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17247 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17248 QualType InnerType = Ptr->getPointeeType();
17249
17250 // Pointer parameter must be a const char *.
17251 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17252 T2: Context.CharTy) &&
17253 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17254 Diag(Loc: Param->getSourceRange().getBegin(),
17255 DiagID: diag::err_literal_operator_param)
17256 << ParamType << "'const char *'" << Param->getSourceRange();
17257 return true;
17258 }
17259
17260 } else if (ParamType->isRealFloatingType()) {
17261 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17262 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17263 return true;
17264
17265 } else if (ParamType->isIntegerType()) {
17266 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17267 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17268 return true;
17269
17270 } else {
17271 Diag(Loc: Param->getSourceRange().getBegin(),
17272 DiagID: diag::err_literal_operator_invalid_param)
17273 << ParamType << Param->getSourceRange();
17274 return true;
17275 }
17276
17277 } else if (FnDecl->param_size() == 2) {
17278 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17279
17280 // First, verify that the first parameter is correct.
17281
17282 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17283
17284 // Two parameter function must have a pointer to const as a
17285 // first parameter; let's strip those qualifiers.
17286 const PointerType *PT = FirstParamType->getAs<PointerType>();
17287
17288 if (!PT) {
17289 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17290 DiagID: diag::err_literal_operator_param)
17291 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17292 return true;
17293 }
17294
17295 QualType PointeeType = PT->getPointeeType();
17296 // First parameter must be const
17297 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17298 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17299 DiagID: diag::err_literal_operator_param)
17300 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17301 return true;
17302 }
17303
17304 QualType InnerType = PointeeType.getUnqualifiedType();
17305 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17306 // const char32_t* are allowed as the first parameter to a two-parameter
17307 // function
17308 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17309 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17310 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17311 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17312 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17313 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17314 DiagID: diag::err_literal_operator_param)
17315 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17316 return true;
17317 }
17318
17319 // Move on to the second and final parameter.
17320 ++Param;
17321
17322 // The second parameter must be a std::size_t.
17323 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17324 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17325 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17326 DiagID: diag::err_literal_operator_param)
17327 << SecondParamType << Context.getSizeType()
17328 << (*Param)->getSourceRange();
17329 return true;
17330 }
17331 } else {
17332 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17333 return true;
17334 }
17335
17336 // Parameters are good.
17337
17338 // A parameter-declaration-clause containing a default argument is not
17339 // equivalent to any of the permitted forms.
17340 for (auto *Param : FnDecl->parameters()) {
17341 if (Param->hasDefaultArg()) {
17342 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17343 DiagID: diag::err_literal_operator_default_argument)
17344 << Param->getDefaultArgRange();
17345 break;
17346 }
17347 }
17348
17349 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17350 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17351 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17352 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17353 // C++23 [usrlit.suffix]p1:
17354 // Literal suffix identifiers that do not start with an underscore are
17355 // reserved for future standardization. Literal suffix identifiers that
17356 // contain a double underscore __ are reserved for use by C++
17357 // implementations.
17358 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17359 << static_cast<int>(Status)
17360 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17361 }
17362
17363 return false;
17364}
17365
17366Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17367 Expr *LangStr,
17368 SourceLocation LBraceLoc) {
17369 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17370 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17371
17372 StringRef Lang = Lit->getString();
17373 LinkageSpecLanguageIDs Language;
17374 if (Lang == "C")
17375 Language = LinkageSpecLanguageIDs::C;
17376 else if (Lang == "C++")
17377 Language = LinkageSpecLanguageIDs::CXX;
17378 else {
17379 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17380 << LangStr->getSourceRange();
17381 return nullptr;
17382 }
17383
17384 // FIXME: Add all the various semantics of linkage specifications
17385
17386 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17387 LangLoc: LangStr->getExprLoc(), Lang: Language,
17388 HasBraces: LBraceLoc.isValid());
17389
17390 /// C++ [module.unit]p7.2.3
17391 /// - Otherwise, if the declaration
17392 /// - ...
17393 /// - ...
17394 /// - appears within a linkage-specification,
17395 /// it is attached to the global module.
17396 ///
17397 /// If the declaration is already in global module fragment, we don't
17398 /// need to attach it again.
17399 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17400 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17401 D->setLocalOwningModule(GlobalModule);
17402 }
17403
17404 CurContext->addDecl(D);
17405 PushDeclContext(S, DC: D);
17406 return D;
17407}
17408
17409Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17410 Decl *LinkageSpec,
17411 SourceLocation RBraceLoc) {
17412 if (RBraceLoc.isValid()) {
17413 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17414 LSDecl->setRBraceLoc(RBraceLoc);
17415 }
17416
17417 // If the current module doesn't has Parent, it implies that the
17418 // LinkageSpec isn't in the module created by itself. So we don't
17419 // need to pop it.
17420 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17421 getCurrentModule()->isImplicitGlobalModule() &&
17422 getCurrentModule()->Parent)
17423 PopImplicitGlobalModuleFragment();
17424
17425 PopDeclContext();
17426 return LinkageSpec;
17427}
17428
17429Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17430 const ParsedAttributesView &AttrList,
17431 SourceLocation SemiLoc) {
17432 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17433 // Attribute declarations appertain to empty declaration so we handle
17434 // them here.
17435 ProcessDeclAttributeList(S, D: ED, AttrList);
17436
17437 CurContext->addDecl(D: ED);
17438 return ED;
17439}
17440
17441VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17442 SourceLocation StartLoc,
17443 SourceLocation Loc,
17444 const IdentifierInfo *Name) {
17445 bool Invalid = false;
17446 QualType ExDeclType = TInfo->getType();
17447
17448 // Arrays and functions decay.
17449 if (ExDeclType->isArrayType())
17450 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17451 else if (ExDeclType->isFunctionType())
17452 ExDeclType = Context.getPointerType(T: ExDeclType);
17453
17454 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17455 // The exception-declaration shall not denote a pointer or reference to an
17456 // incomplete type, other than [cv] void*.
17457 // N2844 forbids rvalue references.
17458 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17459 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17460 Invalid = true;
17461 }
17462
17463 if (ExDeclType->isVariablyModifiedType()) {
17464 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17465 Invalid = true;
17466 }
17467
17468 QualType BaseType = ExDeclType;
17469 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17470 unsigned DK = diag::err_catch_incomplete;
17471 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17472 BaseType = Ptr->getPointeeType();
17473 Mode = 1;
17474 DK = diag::err_catch_incomplete_ptr;
17475 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17476 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17477 BaseType = Ref->getPointeeType();
17478 Mode = 2;
17479 DK = diag::err_catch_incomplete_ref;
17480 }
17481 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17482 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17483 Invalid = true;
17484
17485 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17486 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17487 Invalid = true;
17488 }
17489
17490 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17491 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17492 Invalid = true;
17493 }
17494
17495 if (!Invalid && !ExDeclType->isDependentType() &&
17496 RequireNonAbstractType(Loc, T: ExDeclType,
17497 DiagID: diag::err_abstract_type_in_decl,
17498 Args: AbstractVariableType))
17499 Invalid = true;
17500
17501 // Only the non-fragile NeXT runtime currently supports C++ catches
17502 // of ObjC types, and no runtime supports catching ObjC types by value.
17503 if (!Invalid && getLangOpts().ObjC) {
17504 QualType T = ExDeclType;
17505 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17506 T = RT->getPointeeType();
17507
17508 if (T->isObjCObjectType()) {
17509 Diag(Loc, DiagID: diag::err_objc_object_catch);
17510 Invalid = true;
17511 } else if (T->isObjCObjectPointerType()) {
17512 // FIXME: should this be a test for macosx-fragile specifically?
17513 if (getLangOpts().ObjCRuntime.isFragile())
17514 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17515 }
17516 }
17517
17518 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17519 T: ExDeclType, TInfo, S: SC_None);
17520 ExDecl->setExceptionVariable(true);
17521
17522 // In ARC, infer 'retaining' for variables of retainable type.
17523 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17524 Invalid = true;
17525
17526 if (!Invalid && !ExDeclType->isDependentType()) {
17527 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17528 // Insulate this from anything else we might currently be parsing.
17529 EnterExpressionEvaluationContext scope(
17530 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17531
17532 // C++ [except.handle]p16:
17533 // The object declared in an exception-declaration or, if the
17534 // exception-declaration does not specify a name, a temporary (12.2) is
17535 // copy-initialized (8.5) from the exception object. [...]
17536 // The object is destroyed when the handler exits, after the destruction
17537 // of any automatic objects initialized within the handler.
17538 //
17539 // We just pretend to initialize the object with itself, then make sure
17540 // it can be destroyed later.
17541 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17542
17543 InitializedEntity entity =
17544 InitializedEntity::InitializeVariable(Var: ExDecl);
17545 InitializationKind initKind =
17546 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17547
17548 Expr *opaqueValue =
17549 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17550 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17551 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17552 if (result.isInvalid())
17553 Invalid = true;
17554 else {
17555 // If the constructor used was non-trivial, set this as the
17556 // "initializer".
17557 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17558 if (!construct->getConstructor()->isTrivial()) {
17559 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17560 ExDecl->setInit(init);
17561 }
17562
17563 // And make sure it's destructable.
17564 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17565 }
17566 }
17567 }
17568
17569 if (Invalid)
17570 ExDecl->setInvalidDecl();
17571
17572 return ExDecl;
17573}
17574
17575Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17576 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17577 bool Invalid = D.isInvalidType();
17578
17579 // Check for unexpanded parameter packs.
17580 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17581 UPPC: UPPC_ExceptionType)) {
17582 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17583 Loc: D.getIdentifierLoc());
17584 Invalid = true;
17585 }
17586
17587 const IdentifierInfo *II = D.getIdentifier();
17588 if (NamedDecl *PrevDecl =
17589 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17590 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17591 // The scope should be freshly made just for us. There is just no way
17592 // it contains any previous declaration, except for function parameters in
17593 // a function-try-block's catch statement.
17594 assert(!S->isDeclScope(PrevDecl));
17595 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17596 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17597 << D.getIdentifier();
17598 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17599 Invalid = true;
17600 } else if (PrevDecl->isTemplateParameter())
17601 // Maybe we will complain about the shadowed template parameter.
17602 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17603 }
17604
17605 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17606 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17607 << D.getCXXScopeSpec().getRange();
17608 Invalid = true;
17609 }
17610
17611 VarDecl *ExDecl = BuildExceptionDeclaration(
17612 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17613 if (Invalid)
17614 ExDecl->setInvalidDecl();
17615
17616 // Add the exception declaration into this scope.
17617 if (II)
17618 PushOnScopeChains(D: ExDecl, S);
17619 else
17620 CurContext->addDecl(D: ExDecl);
17621
17622 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17623 return ExDecl;
17624}
17625
17626Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17627 Expr *AssertExpr,
17628 Expr *AssertMessageExpr,
17629 SourceLocation RParenLoc) {
17630 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17631 return nullptr;
17632
17633 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17634 AssertMessageExpr, RParenLoc, Failed: false);
17635}
17636
17637static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17638 switch (BTK) {
17639 case BuiltinType::Char_S:
17640 case BuiltinType::Char_U:
17641 break;
17642 case BuiltinType::Char8:
17643 OS << "u8";
17644 break;
17645 case BuiltinType::Char16:
17646 OS << 'u';
17647 break;
17648 case BuiltinType::Char32:
17649 OS << 'U';
17650 break;
17651 case BuiltinType::WChar_S:
17652 case BuiltinType::WChar_U:
17653 OS << 'L';
17654 break;
17655 default:
17656 llvm_unreachable("Non-character type");
17657 }
17658}
17659
17660/// Convert character's value, interpreted as a code unit, to a string.
17661/// The value needs to be zero-extended to 32-bits.
17662/// FIXME: This assumes Unicode literal encodings
17663static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17664 unsigned TyWidth,
17665 SmallVectorImpl<char> &Str) {
17666 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17667 char *Ptr = Arr;
17668 BuiltinType::Kind K = BTy->getKind();
17669 llvm::raw_svector_ostream OS(Str);
17670
17671 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17672 // other types.
17673 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17674 K == BuiltinType::Char8 || Value <= 0x7F) {
17675 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17676 if (!Escaped.empty())
17677 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17678 else
17679 OS << static_cast<char>(Value);
17680 return;
17681 }
17682
17683 switch (K) {
17684 case BuiltinType::Char16:
17685 case BuiltinType::Char32:
17686 case BuiltinType::WChar_S:
17687 case BuiltinType::WChar_U: {
17688 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17689 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17690 else
17691 OS << "\\x"
17692 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17693 break;
17694 }
17695 default:
17696 llvm_unreachable("Non-character type is passed");
17697 }
17698}
17699
17700/// Convert \V to a string we can present to the user in a diagnostic
17701/// \T is the type of the expression that has been evaluated into \V
17702static bool ConvertAPValueToString(const APValue &V, QualType T,
17703 SmallVectorImpl<char> &Str,
17704 ASTContext &Context) {
17705 if (!V.hasValue())
17706 return false;
17707
17708 switch (V.getKind()) {
17709 case APValue::ValueKind::Int:
17710 if (T->isBooleanType()) {
17711 // Bools are reduced to ints during evaluation, but for
17712 // diagnostic purposes we want to print them as
17713 // true or false.
17714 int64_t BoolValue = V.getInt().getExtValue();
17715 assert((BoolValue == 0 || BoolValue == 1) &&
17716 "Bool type, but value is not 0 or 1");
17717 llvm::raw_svector_ostream OS(Str);
17718 OS << (BoolValue ? "true" : "false");
17719 } else {
17720 llvm::raw_svector_ostream OS(Str);
17721 // Same is true for chars.
17722 // We want to print the character representation for textual types
17723 const auto *BTy = T->getAs<BuiltinType>();
17724 if (BTy) {
17725 switch (BTy->getKind()) {
17726 case BuiltinType::Char_S:
17727 case BuiltinType::Char_U:
17728 case BuiltinType::Char8:
17729 case BuiltinType::Char16:
17730 case BuiltinType::Char32:
17731 case BuiltinType::WChar_S:
17732 case BuiltinType::WChar_U: {
17733 unsigned TyWidth = Context.getIntWidth(T);
17734 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17735 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17736 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17737 OS << '\'';
17738 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17739 OS << "' (0x"
17740 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17741 /*Upper=*/true)
17742 << ", " << V.getInt() << ')';
17743 return true;
17744 }
17745 default:
17746 break;
17747 }
17748 }
17749 V.getInt().toString(Str);
17750 }
17751
17752 break;
17753
17754 case APValue::ValueKind::Float:
17755 V.getFloat().toString(Str);
17756 break;
17757
17758 case APValue::ValueKind::LValue:
17759 if (V.isNullPointer()) {
17760 llvm::raw_svector_ostream OS(Str);
17761 OS << "nullptr";
17762 } else
17763 return false;
17764 break;
17765
17766 case APValue::ValueKind::ComplexFloat: {
17767 llvm::raw_svector_ostream OS(Str);
17768 OS << '(';
17769 V.getComplexFloatReal().toString(Str);
17770 OS << " + ";
17771 V.getComplexFloatImag().toString(Str);
17772 OS << "i)";
17773 } break;
17774
17775 case APValue::ValueKind::ComplexInt: {
17776 llvm::raw_svector_ostream OS(Str);
17777 OS << '(';
17778 V.getComplexIntReal().toString(Str);
17779 OS << " + ";
17780 V.getComplexIntImag().toString(Str);
17781 OS << "i)";
17782 } break;
17783
17784 default:
17785 return false;
17786 }
17787
17788 return true;
17789}
17790
17791/// Some Expression types are not useful to print notes about,
17792/// e.g. literals and values that have already been expanded
17793/// before such as int-valued template parameters.
17794static bool UsefulToPrintExpr(const Expr *E) {
17795 E = E->IgnoreParenImpCasts();
17796 // Literals are pretty easy for humans to understand.
17797 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17798 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17799 return false;
17800
17801 // These have been substituted from template parameters
17802 // and appear as literals in the static assert error.
17803 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17804 return false;
17805
17806 // -5 is also simple to understand.
17807 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17808 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17809
17810 // Only print nested arithmetic operators.
17811 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17812 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17813 BO->isBitwiseOp());
17814
17815 return true;
17816}
17817
17818void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17819 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17820 Op && Op->getOpcode() != BO_LOr) {
17821 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17822 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17823
17824 // Ignore comparisons of boolean expressions with a boolean literal.
17825 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17826 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17827 return;
17828
17829 // Don't print obvious expressions.
17830 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17831 return;
17832
17833 struct {
17834 const clang::Expr *Cond;
17835 Expr::EvalResult Result;
17836 SmallString<12> ValueString;
17837 bool Print;
17838 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17839 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17840 for (auto &DiagSide : DiagSides) {
17841 const Expr *Side = DiagSide.Cond;
17842
17843 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17844
17845 DiagSide.Print = ConvertAPValueToString(
17846 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17847 }
17848 if (DiagSides[0].Print && DiagSides[1].Print) {
17849 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17850 << DiagSides[0].ValueString << Op->getOpcodeStr()
17851 << DiagSides[1].ValueString << Op->getSourceRange();
17852 }
17853 } else {
17854 DiagnoseTypeTraitDetails(E);
17855 }
17856}
17857
17858template <typename ResultType>
17859static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17860 ResultType &Result, ASTContext &Ctx,
17861 Sema::StringEvaluationContext EvalContext,
17862 bool ErrorOnInvalidMessage) {
17863
17864 assert(Message);
17865 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17866 "can't evaluate a dependant static assert message");
17867
17868 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17869 assert(SL->isUnevaluated() && "expected an unevaluated string");
17870 if constexpr (std::is_same_v<APValue, ResultType>) {
17871 Result =
17872 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17873 const ConstantArrayType *CAT =
17874 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17875 assert(CAT && "string literal isn't an array");
17876 QualType CharType = CAT->getElementType();
17877 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17878 CharType->isUnsignedIntegerType());
17879 for (unsigned I = 0; I < SL->getLength(); I++) {
17880 Value = SL->getCodeUnit(i: I);
17881 Result.getArrayInitializedElt(I) = APValue(Value);
17882 }
17883 } else {
17884 Result.assign(SL->getString().begin(), SL->getString().end());
17885 }
17886 return true;
17887 }
17888
17889 SourceLocation Loc = Message->getBeginLoc();
17890 QualType T = Message->getType().getNonReferenceType();
17891 auto *RD = T->getAsCXXRecordDecl();
17892 if (!RD) {
17893 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17894 return false;
17895 }
17896
17897 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17898 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17899 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17900 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17901 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17902 OverloadCandidateSet::CSK_Normal);
17903 if (MemberLookup.empty())
17904 return std::nullopt;
17905 return std::move(MemberLookup);
17906 };
17907
17908 std::optional<LookupResult> SizeMember = FindMember("size");
17909 std::optional<LookupResult> DataMember = FindMember("data");
17910 if (!SizeMember || !DataMember) {
17911 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17912 << EvalContext
17913 << ((!SizeMember && !DataMember) ? 2
17914 : !SizeMember ? 0
17915 : 1);
17916 return false;
17917 }
17918
17919 auto BuildExpr = [&](LookupResult &LR) {
17920 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17921 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17922 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17923 if (Res.isInvalid())
17924 return ExprError();
17925 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17926 IsExecConfig: false, AllowRecovery: true);
17927 if (Res.isInvalid())
17928 return ExprError();
17929 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17930 return ExprError();
17931 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17932 };
17933
17934 ExprResult SizeE = BuildExpr(*SizeMember);
17935 ExprResult DataE = BuildExpr(*DataMember);
17936
17937 QualType SizeT = SemaRef.Context.getSizeType();
17938 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17939 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17940
17941 ExprResult EvaluatedSize =
17942 SizeE.isInvalid()
17943 ? ExprError()
17944 : SemaRef.BuildConvertedConstantExpression(
17945 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17946 if (EvaluatedSize.isInvalid()) {
17947 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17948 << EvalContext << /*size*/ 0;
17949 return false;
17950 }
17951
17952 ExprResult EvaluatedData =
17953 DataE.isInvalid()
17954 ? ExprError()
17955 : SemaRef.BuildConvertedConstantExpression(
17956 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17957 if (EvaluatedData.isInvalid()) {
17958 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17959 << EvalContext << /*data*/ 1;
17960 return false;
17961 }
17962
17963 if (!ErrorOnInvalidMessage &&
17964 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
17965 return true;
17966
17967 Expr::EvalResult Status;
17968 SmallVector<PartialDiagnosticAt, 8> Notes;
17969 Status.Diag = &Notes;
17970 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17971 EvaluatedData.get(), Ctx, Status) ||
17972 !Notes.empty()) {
17973 SemaRef.Diag(Loc: Message->getBeginLoc(),
17974 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17975 : diag::warn_user_defined_msg_constexpr)
17976 << EvalContext;
17977 for (const auto &Note : Notes)
17978 SemaRef.Diag(Loc: Note.first, PD: Note.second);
17979 return !ErrorOnInvalidMessage;
17980 }
17981 return true;
17982}
17983
17984bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17985 StringEvaluationContext EvalContext,
17986 bool ErrorOnInvalidMessage) {
17987 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17988 ErrorOnInvalidMessage);
17989}
17990
17991bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17992 StringEvaluationContext EvalContext,
17993 bool ErrorOnInvalidMessage) {
17994 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17995 ErrorOnInvalidMessage);
17996}
17997
17998Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17999 Expr *AssertExpr, Expr *AssertMessage,
18000 SourceLocation RParenLoc,
18001 bool Failed) {
18002 assert(AssertExpr != nullptr && "Expected non-null condition");
18003 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18004 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18005 !AssertMessage->isValueDependent())) &&
18006 !Failed) {
18007 // In a static_assert-declaration, the constant-expression shall be a
18008 // constant expression that can be contextually converted to bool.
18009 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
18010 if (Converted.isInvalid())
18011 Failed = true;
18012
18013 ExprResult FullAssertExpr =
18014 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
18015 /*DiscardedValue*/ false,
18016 /*IsConstexpr*/ true);
18017 if (FullAssertExpr.isInvalid())
18018 Failed = true;
18019 else
18020 AssertExpr = FullAssertExpr.get();
18021
18022 llvm::APSInt Cond;
18023 Expr *BaseExpr = AssertExpr;
18024 AllowFoldKind FoldKind = AllowFoldKind::No;
18025
18026 if (!getLangOpts().CPlusPlus) {
18027 // In C mode, allow folding as an extension for better compatibility with
18028 // C++ in terms of expressions like static_assert("test") or
18029 // static_assert(nullptr).
18030 FoldKind = AllowFoldKind::Allow;
18031 }
18032
18033 if (!Failed && VerifyIntegerConstantExpression(
18034 E: BaseExpr, Result: &Cond,
18035 DiagID: diag::err_static_assert_expression_is_not_constant,
18036 CanFold: FoldKind).isInvalid())
18037 Failed = true;
18038
18039 // If the static_assert passes, only verify that
18040 // the message is grammatically valid without evaluating it.
18041 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18042 std::string Str;
18043 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18044 EvalContext: StringEvaluationContext::StaticAssert,
18045 /*ErrorOnInvalidMessage=*/false);
18046 }
18047
18048 // CWG2518
18049 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18050 // template definition, the declaration has no effect.
18051 bool InTemplateDefinition =
18052 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18053
18054 if (!Failed && !Cond && !InTemplateDefinition) {
18055 SmallString<256> MsgBuffer;
18056 llvm::raw_svector_ostream Msg(MsgBuffer);
18057 bool HasMessage = AssertMessage;
18058 if (AssertMessage) {
18059 std::string Str;
18060 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18061 EvalContext: StringEvaluationContext::StaticAssert,
18062 /*ErrorOnInvalidMessage=*/true) ||
18063 !Str.empty();
18064 Msg << Str;
18065 }
18066 Expr *InnerCond = nullptr;
18067 std::string InnerCondDescription;
18068 std::tie(args&: InnerCond, args&: InnerCondDescription) =
18069 findFailedBooleanCondition(Cond: Converted.get());
18070 if (const auto *ConceptIDExpr =
18071 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18072 const ASTConstraintSatisfaction &Satisfaction =
18073 ConceptIDExpr->getSatisfaction();
18074 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18075 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18076 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18077 // Drill down into concept specialization expressions to see why they
18078 // weren't satisfied.
18079 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18080 }
18081 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18082 !isa<IntegerLiteral>(Val: InnerCond)) {
18083 Diag(Loc: InnerCond->getBeginLoc(),
18084 DiagID: diag::err_static_assert_requirement_failed)
18085 << InnerCondDescription << !HasMessage << Msg.str()
18086 << InnerCond->getSourceRange();
18087 DiagnoseStaticAssertDetails(E: InnerCond);
18088 } else {
18089 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18090 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18091 PrintContextStack();
18092 }
18093 Failed = true;
18094 }
18095 } else {
18096 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18097 /*DiscardedValue*/false,
18098 /*IsConstexpr*/true);
18099 if (FullAssertExpr.isInvalid())
18100 Failed = true;
18101 else
18102 AssertExpr = FullAssertExpr.get();
18103 }
18104
18105 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18106 AssertExpr, Message: AssertMessage, RParenLoc,
18107 Failed);
18108
18109 CurContext->addDecl(D: Decl);
18110 return Decl;
18111}
18112
18113DeclResult Sema::ActOnTemplatedFriendTag(
18114 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18115 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18116 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18117 MultiTemplateParamsArg TempParamLists) {
18118 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18119
18120 bool IsMemberSpecialization = false;
18121 bool Invalid = false;
18122
18123 if (TemplateParameterList *TemplateParams =
18124 MatchTemplateParametersToScopeSpecifier(
18125 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18126 IsMemberSpecialization, Invalid)) {
18127 if (TemplateParams->size() > 0) {
18128 // This is a declaration of a class template.
18129 if (Invalid)
18130 return true;
18131
18132 return CheckClassTemplate(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS,
18133 Name, NameLoc, Attr, TemplateParams, AS: AS_public,
18134 /*ModulePrivateLoc=*/SourceLocation(),
18135 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
18136 OuterTemplateParamLists: TempParamLists.data(), IsMemberSpecialization)
18137 .get();
18138 } else {
18139 // The "template<>" header is extraneous.
18140 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18141 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18142 }
18143 }
18144
18145 if (Invalid) return true;
18146
18147 bool isAllExplicitSpecializations =
18148 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18149 return List->size() == 0;
18150 });
18151
18152 // FIXME: don't ignore attributes.
18153
18154 // If it's explicit specializations all the way down, just forget
18155 // about the template header and build an appropriate non-templated
18156 // friend. TODO: for source fidelity, remember the headers.
18157 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18158 if (isAllExplicitSpecializations) {
18159 if (SS.isEmpty()) {
18160 bool Owned = false;
18161 bool IsDependent = false;
18162 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18163 Attr, AS: AS_public,
18164 /*ModulePrivateLoc=*/SourceLocation(),
18165 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18166 /*ScopedEnumKWLoc=*/SourceLocation(),
18167 /*ScopedEnumUsesClassTag=*/false,
18168 /*UnderlyingType=*/TypeResult(),
18169 /*IsTypeSpecifier=*/false,
18170 /*IsTemplateParamOrArg=*/false,
18171 /*OOK=*/OffsetOfKind::Outside);
18172 }
18173
18174 TypeSourceInfo *TSI = nullptr;
18175 ElaboratedTypeKeyword Keyword
18176 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18177 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18178 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18179 if (T.isNull())
18180 return true;
18181
18182 FriendDecl *Friend =
18183 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18184 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18185 Friend->setAccess(AS_public);
18186 CurContext->addDecl(D: Friend);
18187 return Friend;
18188 }
18189
18190 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18191
18192 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18193 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18194 // shall not have been introduced by the template-declaration.
18195 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18196 collectUnexpandedParameterPacks(NNS: QualifierLoc, Unexpanded);
18197 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18198 for (UnexpandedParameterPack &U : Unexpanded) {
18199 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(UPP: U);
18200 DI && DI->first >= FriendDeclDepth) {
18201 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18202 if (!ND)
18203 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18204 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18205 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18206 return true;
18207 }
18208 }
18209
18210 // Handle the case of a templated-scope friend class. e.g.
18211 // template <class T> class A<T>::B;
18212 // FIXME: we don't support these right now.
18213 Diag(Loc: NameLoc, DiagID: diag::warn_template_qualified_friend_unsupported)
18214 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(Val: CurContext);
18215 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18216 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18217 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18218 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18219 TL.setElaboratedKeywordLoc(TagLoc);
18220 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18221 TL.setNameLoc(NameLoc);
18222
18223 FriendDecl *Friend =
18224 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18225 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18226 Friend->setAccess(AS_public);
18227 Friend->setUnsupportedFriend(true);
18228 CurContext->addDecl(D: Friend);
18229 return Friend;
18230}
18231
18232Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18233 MultiTemplateParamsArg TempParams,
18234 SourceLocation EllipsisLoc) {
18235 SourceLocation Loc = DS.getBeginLoc();
18236 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18237
18238 assert(DS.isFriendSpecified());
18239 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18240
18241 // C++ [class.friend]p3:
18242 // A friend declaration that does not declare a function shall have one of
18243 // the following forms:
18244 // friend elaborated-type-specifier ;
18245 // friend simple-type-specifier ;
18246 // friend typename-specifier ;
18247 //
18248 // If the friend keyword isn't first, or if the declarations has any type
18249 // qualifiers, then the declaration doesn't have that form.
18250 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18251 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18252 if (DS.getTypeQualifiers()) {
18253 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18254 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18255 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18256 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18257 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18258 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18259 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18260 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18261 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18262 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18263 }
18264
18265 // Try to convert the decl specifier to a type. This works for
18266 // friend templates because ActOnTag never produces a ClassTemplateDecl
18267 // for a TagUseKind::Friend.
18268 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18269 DeclaratorContext::Member);
18270 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18271 QualType T = TSI->getType();
18272 if (TheDeclarator.isInvalidType())
18273 return nullptr;
18274
18275 // If '...' is present, the type must contain an unexpanded parameter
18276 // pack, and vice versa.
18277 bool Invalid = false;
18278 if (EllipsisLoc.isInvalid() &&
18279 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18280 return nullptr;
18281 if (EllipsisLoc.isValid() &&
18282 !TSI->getType()->containsUnexpandedParameterPack()) {
18283 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18284 << TSI->getTypeLoc().getSourceRange();
18285 Invalid = true;
18286 }
18287
18288 if (!T->isElaboratedTypeSpecifier()) {
18289 if (TempParams.size()) {
18290 // C++23 [dcl.pre]p5:
18291 // In a simple-declaration, the optional init-declarator-list can be
18292 // omitted only when declaring a class or enumeration, that is, when
18293 // the decl-specifier-seq contains either a class-specifier, an
18294 // elaborated-type-specifier with a class-key, or an enum-specifier.
18295 //
18296 // The declaration of a template-declaration or explicit-specialization
18297 // is never a member-declaration, so this must be a simple-declaration
18298 // with no init-declarator-list. Therefore, this is ill-formed.
18299 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18300 return nullptr;
18301 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18302 SmallString<16> InsertionText(" ");
18303 InsertionText += RD->getKindName();
18304
18305 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18306 ? diag::warn_cxx98_compat_unelaborated_friend_type
18307 : diag::ext_unelaborated_friend_type)
18308 << (unsigned)RD->getTagKind() << T
18309 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18310 Code: InsertionText);
18311 } else {
18312 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18313 << T << DS.getSourceRange();
18314 }
18315 }
18316
18317 // C++98 [class.friend]p1: A friend of a class is a function
18318 // or class that is not a member of the class . . .
18319 // This is fixed in DR77, which just barely didn't make the C++03
18320 // deadline. It's also a very silly restriction that seriously
18321 // affects inner classes and which nobody else seems to implement;
18322 // thus we never diagnose it, not even in -pedantic.
18323 //
18324 // But note that we could warn about it: it's always useless to
18325 // friend one of your own members (it's not, however, worthless to
18326 // friend a member of an arbitrary specialization of your template).
18327
18328 Decl *D;
18329 if (!TempParams.empty())
18330 // TODO: Support variadic friend template decls?
18331 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
18332 FriendLoc);
18333 else
18334 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18335 Friend_: TSI, FriendL: FriendLoc, EllipsisLoc);
18336
18337 if (!D)
18338 return nullptr;
18339
18340 D->setAccess(AS_public);
18341 CurContext->addDecl(D);
18342
18343 if (Invalid)
18344 D->setInvalidDecl();
18345
18346 return D;
18347}
18348
18349NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18350 MultiTemplateParamsArg TemplateParams) {
18351 const DeclSpec &DS = D.getDeclSpec();
18352
18353 assert(DS.isFriendSpecified());
18354 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18355
18356 SourceLocation Loc = D.getIdentifierLoc();
18357 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18358
18359 // C++ [class.friend]p1
18360 // A friend of a class is a function or class....
18361 // Note that this sees through typedefs, which is intended.
18362 // It *doesn't* see through dependent types, which is correct
18363 // according to [temp.arg.type]p3:
18364 // If a declaration acquires a function type through a
18365 // type dependent on a template-parameter and this causes
18366 // a declaration that does not use the syntactic form of a
18367 // function declarator to have a function type, the program
18368 // is ill-formed.
18369 if (!TInfo->getType()->isFunctionType()) {
18370 Diag(Loc, DiagID: diag::err_unexpected_friend);
18371
18372 // It might be worthwhile to try to recover by creating an
18373 // appropriate declaration.
18374 return nullptr;
18375 }
18376
18377 // C++ [namespace.memdef]p3
18378 // - If a friend declaration in a non-local class first declares a
18379 // class or function, the friend class or function is a member
18380 // of the innermost enclosing namespace.
18381 // - The name of the friend is not found by simple name lookup
18382 // until a matching declaration is provided in that namespace
18383 // scope (either before or after the class declaration granting
18384 // friendship).
18385 // - If a friend function is called, its name may be found by the
18386 // name lookup that considers functions from namespaces and
18387 // classes associated with the types of the function arguments.
18388 // - When looking for a prior declaration of a class or a function
18389 // declared as a friend, scopes outside the innermost enclosing
18390 // namespace scope are not considered.
18391
18392 CXXScopeSpec &SS = D.getCXXScopeSpec();
18393 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18394 assert(NameInfo.getName());
18395
18396 // Check for unexpanded parameter packs.
18397 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18398 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18399 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18400 return nullptr;
18401
18402 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18403
18404 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18405 auto Kind = SS.getScopeRep().getKind();
18406 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18407 Kind == NestedNameSpecifier::Kind::Namespace;
18408 if (IsNamespaceOrGlobal) {
18409 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def)
18410 << SS.getScopeRep() << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18411 SS.clear();
18412 }
18413 }
18414
18415 // The context we found the declaration in, or in which we should
18416 // create the declaration.
18417 DeclContext *DC;
18418 Scope *DCScope = S;
18419 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18420 RedeclarationKind::ForExternalRedeclaration);
18421
18422 // There are five cases here.
18423 // - There's no scope specifier and we're in a local class. Only look
18424 // for functions declared in the immediately-enclosing block scope.
18425 // We recover from invalid scope qualifiers as if they just weren't there.
18426 FunctionDecl *FunctionContainingLocalClass = nullptr;
18427 if ((SS.isInvalid() || !SS.isSet()) &&
18428 (FunctionContainingLocalClass =
18429 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18430 // C++11 [class.friend]p11:
18431 // If a friend declaration appears in a local class and the name
18432 // specified is an unqualified name, a prior declaration is
18433 // looked up without considering scopes that are outside the
18434 // innermost enclosing non-class scope. For a friend function
18435 // declaration, if there is no prior declaration, the program is
18436 // ill-formed.
18437
18438 // Find the innermost enclosing non-class scope. This is the block
18439 // scope containing the local class definition (or for a nested class,
18440 // the outer local class).
18441 DCScope = S->getFnParent();
18442
18443 // Look up the function name in the scope.
18444 Previous.clear(Kind: LookupLocalFriendName);
18445 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18446
18447 if (!Previous.empty()) {
18448 // All possible previous declarations must have the same context:
18449 // either they were declared at block scope or they are members of
18450 // one of the enclosing local classes.
18451 DC = Previous.getRepresentativeDecl()->getDeclContext();
18452 } else {
18453 // This is ill-formed, but provide the context that we would have
18454 // declared the function in, if we were permitted to, for error recovery.
18455 DC = FunctionContainingLocalClass;
18456 }
18457 adjustContextForLocalExternDecl(DC);
18458
18459 // - There's no scope specifier, in which case we just go to the
18460 // appropriate scope and look for a function or function template
18461 // there as appropriate.
18462 } else if (SS.isInvalid() || !SS.isSet()) {
18463 // C++11 [namespace.memdef]p3:
18464 // If the name in a friend declaration is neither qualified nor
18465 // a template-id and the declaration is a function or an
18466 // elaborated-type-specifier, the lookup to determine whether
18467 // the entity has been previously declared shall not consider
18468 // any scopes outside the innermost enclosing namespace.
18469
18470 // Find the appropriate context according to the above.
18471 DC = CurContext;
18472
18473 // Skip class contexts. If someone can cite chapter and verse
18474 // for this behavior, that would be nice --- it's what GCC and
18475 // EDG do, and it seems like a reasonable intent, but the spec
18476 // really only says that checks for unqualified existing
18477 // declarations should stop at the nearest enclosing namespace,
18478 // not that they should only consider the nearest enclosing
18479 // namespace.
18480 while (DC->isRecord())
18481 DC = DC->getParent();
18482
18483 DeclContext *LookupDC = DC->getNonTransparentContext();
18484 while (true) {
18485 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18486
18487 if (!Previous.empty()) {
18488 DC = LookupDC;
18489 break;
18490 }
18491
18492 if (isTemplateId) {
18493 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18494 } else {
18495 if (LookupDC->isFileContext()) break;
18496 }
18497 LookupDC = LookupDC->getParent();
18498 }
18499
18500 DCScope = getScopeForDeclContext(S, DC);
18501
18502 // - There's a non-dependent scope specifier, in which case we
18503 // compute it and do a previous lookup there for a function
18504 // or function template.
18505 } else if (!SS.getScopeRep().isDependent()) {
18506 DC = computeDeclContext(SS);
18507 if (!DC) return nullptr;
18508
18509 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18510
18511 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18512
18513 // C++ [class.friend]p1: A friend of a class is a function or
18514 // class that is not a member of the class . . .
18515 if (DC->Equals(DC: CurContext))
18516 Diag(Loc: DS.getFriendSpecLoc(),
18517 DiagID: getLangOpts().CPlusPlus11 ?
18518 diag::warn_cxx98_compat_friend_is_member :
18519 diag::err_friend_is_member);
18520
18521 // - There's a scope specifier that does not match any template
18522 // parameter lists, in which case we use some arbitrary context,
18523 // create a method or method template, and wait for instantiation.
18524 // - There's a scope specifier that does match some template
18525 // parameter lists, which we don't handle right now.
18526 } else {
18527 DC = CurContext;
18528 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18529 }
18530
18531 if (!DC->isRecord()) {
18532 int DiagArg = -1;
18533 switch (D.getName().getKind()) {
18534 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18535 case UnqualifiedIdKind::IK_ConstructorName:
18536 DiagArg = 0;
18537 break;
18538 case UnqualifiedIdKind::IK_DestructorName:
18539 DiagArg = 1;
18540 break;
18541 case UnqualifiedIdKind::IK_ConversionFunctionId:
18542 DiagArg = 2;
18543 break;
18544 case UnqualifiedIdKind::IK_DeductionGuideName:
18545 DiagArg = 3;
18546 break;
18547 case UnqualifiedIdKind::IK_Identifier:
18548 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18549 case UnqualifiedIdKind::IK_LiteralOperatorId:
18550 case UnqualifiedIdKind::IK_OperatorFunctionId:
18551 case UnqualifiedIdKind::IK_TemplateId:
18552 break;
18553 }
18554 // This implies that it has to be an operator or function.
18555 if (DiagArg >= 0) {
18556 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18557 return nullptr;
18558 }
18559 } else {
18560 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(Val: DC);
18561 if (RC->isLambda()) {
18562 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_lambda_decl);
18563 }
18564 }
18565
18566 // FIXME: This is an egregious hack to cope with cases where the scope stack
18567 // does not contain the declaration context, i.e., in an out-of-line
18568 // definition of a class.
18569 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18570 if (!DCScope) {
18571 FakeDCScope.setEntity(DC);
18572 DCScope = &FakeDCScope;
18573 }
18574
18575 bool AddToScope = true;
18576 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18577 TemplateParamLists: TemplateParams, AddToScope);
18578 if (!ND) return nullptr;
18579
18580 assert(ND->getLexicalDeclContext() == CurContext);
18581
18582 // If we performed typo correction, we might have added a scope specifier
18583 // and changed the decl context.
18584 DC = ND->getDeclContext();
18585
18586 // Add the function declaration to the appropriate lookup tables,
18587 // adjusting the redeclarations list as necessary. We don't
18588 // want to do this yet if the friending class is dependent.
18589 //
18590 // Also update the scope-based lookup if the target context's
18591 // lookup context is in lexical scope.
18592 if (!CurContext->isDependentContext()) {
18593 DC = DC->getRedeclContext();
18594 DC->makeDeclVisibleInContext(D: ND);
18595 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18596 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18597 }
18598
18599 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18600 L: D.getIdentifierLoc(), Friend_: ND,
18601 FriendL: DS.getFriendSpecLoc());
18602 FrD->setAccess(AS_public);
18603 CurContext->addDecl(D: FrD);
18604
18605 if (ND->isInvalidDecl()) {
18606 FrD->setInvalidDecl();
18607 } else {
18608 if (DC->isRecord()) CheckFriendAccess(D: ND);
18609
18610 FunctionDecl *FD;
18611 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18612 FD = FTD->getTemplatedDecl();
18613 else
18614 FD = cast<FunctionDecl>(Val: ND);
18615
18616 // C++ [class.friend]p6:
18617 // A function may be defined in a friend declaration of a class if and
18618 // only if the class is a non-local class, and the function name is
18619 // unqualified.
18620 if (D.isFunctionDefinition()) {
18621 // Qualified friend function definition.
18622 if (SS.isNotEmpty()) {
18623 // FIXME: We should only do this if the scope specifier names the
18624 // innermost enclosing namespace; otherwise the fixit changes the
18625 // meaning of the code.
18626 SemaDiagnosticBuilder DB =
18627 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18628
18629 DB << SS.getScopeRep();
18630 if (DC->isFileContext())
18631 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18632
18633 // Friend function defined in a local class.
18634 } else if (FunctionContainingLocalClass) {
18635 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18636
18637 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18638 // a template-id, the function name is not unqualified because these is
18639 // no name. While the wording requires some reading in-between the
18640 // lines, GCC, MSVC, and EDG all consider a friend function
18641 // specialization definitions to be de facto explicit specialization
18642 // and diagnose them as such.
18643 } else if (isTemplateId) {
18644 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18645 }
18646 }
18647
18648 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18649 // default argument expression, that declaration shall be a definition
18650 // and shall be the only declaration of the function or function
18651 // template in the translation unit.
18652 if (functionDeclHasDefaultArgument(FD)) {
18653 // We can't look at FD->getPreviousDecl() because it may not have been set
18654 // if we're in a dependent context. If the function is known to be a
18655 // redeclaration, we will have narrowed Previous down to the right decl.
18656 if (D.isRedeclaration()) {
18657 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18658 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18659 DiagID: diag::note_previous_declaration);
18660 } else if (!D.isFunctionDefinition())
18661 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18662 }
18663
18664 // Mark templated-scope function declarations as unsupported.
18665 if (!FD->getTemplateParameterLists().empty() && SS.isValid()) {
18666 Diag(Loc: FD->getLocation(), DiagID: diag::warn_template_qualified_friend_unsupported)
18667 << SS.getScopeRep() << SS.getRange()
18668 << cast<CXXRecordDecl>(Val: CurContext);
18669 FrD->setUnsupportedFriend(true);
18670 }
18671 }
18672
18673 warnOnReservedIdentifier(D: ND);
18674
18675 return ND;
18676}
18677
18678void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18679 StringLiteral *Message) {
18680 AdjustDeclIfTemplate(Decl&: Dcl);
18681
18682 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18683 if (!Fn) {
18684 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18685 return;
18686 }
18687
18688 // Deleted function does not have a body.
18689 Fn->setWillHaveBody(false);
18690
18691 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18692 // Don't consider the implicit declaration we generate for explicit
18693 // specializations. FIXME: Do not generate these implicit declarations.
18694 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18695 Prev->getPreviousDecl()) &&
18696 !Prev->isDefined()) {
18697 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18698 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18699 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18700 : diag::note_previous_declaration);
18701 // We can't recover from this; the declaration might have already
18702 // been used.
18703 Fn->setInvalidDecl();
18704 return;
18705 }
18706
18707 // To maintain the invariant that functions are only deleted on their first
18708 // declaration, mark the implicitly-instantiated declaration of the
18709 // explicitly-specialized function as deleted instead of marking the
18710 // instantiated redeclaration.
18711 Fn = Fn->getCanonicalDecl();
18712 }
18713
18714 // dllimport/dllexport cannot be deleted.
18715 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18716 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18717 Fn->setInvalidDecl();
18718 }
18719
18720 // C++11 [basic.start.main]p3:
18721 // A program that defines main as deleted [...] is ill-formed.
18722 if (Fn->isMain())
18723 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18724
18725 // C++11 [dcl.fct.def.delete]p4:
18726 // A deleted function is implicitly inline.
18727 Fn->setImplicitlyInline();
18728 Fn->setDeletedAsWritten(D: true, Message);
18729}
18730
18731void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18732 if (!Dcl || Dcl->isInvalidDecl())
18733 return;
18734
18735 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18736 if (!FD) {
18737 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18738 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18739 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18740 return;
18741 }
18742 }
18743
18744 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18745 << getLangOpts().CPlusPlus20;
18746 return;
18747 }
18748
18749 // Reject if this can't possibly be a defaultable function.
18750 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18751 if (!DefKind &&
18752 // A dependent function that doesn't locally look defaultable can
18753 // still instantiate to a defaultable function if it's a constructor
18754 // or assignment operator.
18755 (!FD->isDependentContext() ||
18756 (!isa<CXXConstructorDecl>(Val: FD) &&
18757 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18758 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18759 << getLangOpts().CPlusPlus20;
18760 return;
18761 }
18762
18763 // Issue compatibility warning. We already warned if the operator is
18764 // 'operator<=>' when parsing the '<=>' token.
18765 if (DefKind.isComparison() &&
18766 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18767 Diag(Loc: DefaultLoc, DiagID: getLangOpts().CPlusPlus20
18768 ? diag::warn_cxx17_compat_defaulted_comparison
18769 : diag::ext_defaulted_comparison);
18770 }
18771
18772 FD->setDefaulted();
18773 FD->setExplicitlyDefaulted();
18774 FD->setDefaultLoc(DefaultLoc);
18775
18776 // Defer checking functions that are defaulted in a dependent context.
18777 if (FD->isDependentContext())
18778 return;
18779
18780 // Unset that we will have a body for this function. We might not,
18781 // if it turns out to be trivial, and we don't need this marking now
18782 // that we've marked it as defaulted.
18783 FD->setWillHaveBody(false);
18784
18785 if (DefKind.isComparison()) {
18786 // If this comparison's defaulting occurs within the definition of its
18787 // lexical class context, we have to do the checking when complete.
18788 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
18789 if (!RD->isCompleteDefinition())
18790 return;
18791 }
18792
18793 // If this member fn was defaulted on its first declaration, we will have
18794 // already performed the checking in CheckCompletedCXXClass. Such a
18795 // declaration doesn't trigger an implicit definition.
18796 if (isa<CXXMethodDecl>(Val: FD)) {
18797 const FunctionDecl *Primary = FD;
18798 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18799 // Ask the template instantiation pattern that actually had the
18800 // '= default' on it.
18801 Primary = Pattern;
18802 if (Primary->getCanonicalDecl()->isDefaulted())
18803 return;
18804 }
18805
18806 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
18807 // non-default FP features to stash. This avoids memory overhead for
18808 // the vast majority of defaulted functions.
18809 if (!FD->getDefaultedOrDeletedInfo() &&
18810 CurFPFeatureOverrides().requiresTrailingStorage()) {
18811 FD->setDefaultedOrDeletedInfo(
18812 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
18813 Context, /*Lookups=*/{}, FPFeatures: CurFPFeatureOverrides()));
18814 }
18815
18816 if (DefKind.isComparison()) {
18817 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18818 FD->setInvalidDecl();
18819 else
18820 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18821 } else {
18822 auto *MD = cast<CXXMethodDecl>(Val: FD);
18823
18824 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18825 DefaultLoc))
18826 MD->setInvalidDecl();
18827 else
18828 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
18829 }
18830}
18831
18832static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18833 for (Stmt *SubStmt : S->children()) {
18834 if (!SubStmt)
18835 continue;
18836 if (isa<ReturnStmt>(Val: SubStmt))
18837 Self.Diag(Loc: SubStmt->getBeginLoc(),
18838 DiagID: diag::err_return_in_constructor_handler);
18839 if (!isa<Expr>(Val: SubStmt))
18840 SearchForReturnInStmt(Self, S: SubStmt);
18841 }
18842}
18843
18844void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18845 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18846 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18847 SearchForReturnInStmt(Self&: *this, S: Handler);
18848 }
18849}
18850
18851void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18852 StringLiteral *DeletedMessage) {
18853 switch (BodyKind) {
18854 case FnBodyKind::Delete:
18855 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
18856 break;
18857 case FnBodyKind::Default:
18858 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18859 break;
18860 case FnBodyKind::Other:
18861 llvm_unreachable(
18862 "Parsed function body should be '= delete;' or '= default;'");
18863 }
18864}
18865
18866bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18867 const CXXMethodDecl *Old) {
18868 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18869 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18870
18871 if (OldFT->hasExtParameterInfos()) {
18872 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18873 // A parameter of the overriding method should be annotated with noescape
18874 // if the corresponding parameter of the overridden method is annotated.
18875 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18876 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18877 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
18878 DiagID: diag::warn_overriding_method_missing_noescape);
18879 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
18880 DiagID: diag::note_overridden_marked_noescape);
18881 }
18882 }
18883
18884 // SME attributes must match when overriding a function declaration.
18885 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18886 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
18887 << New << New->getType() << Old->getType();
18888 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18889 return true;
18890 }
18891
18892 // Virtual overrides must have the same code_seg.
18893 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18894 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18895 if ((NewCSA || OldCSA) &&
18896 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18897 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
18898 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
18899 return true;
18900 }
18901
18902 // Virtual overrides: check for matching effects.
18903 if (Context.hasAnyFunctionEffects()) {
18904 const auto OldFX = Old->getFunctionEffects();
18905 const auto NewFXOrig = New->getFunctionEffects();
18906
18907 if (OldFX != NewFXOrig) {
18908 FunctionEffectSet NewFX(NewFXOrig);
18909 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18910 FunctionEffectSet::Conflicts Errs;
18911 for (const auto &Diff : Diffs) {
18912 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
18913 case FunctionEffectDiff::OverrideResult::NoAction:
18914 break;
18915 case FunctionEffectDiff::OverrideResult::Warn:
18916 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
18917 << Diff.effectName();
18918 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18919 << Old->getReturnTypeSourceRange();
18920 break;
18921 case FunctionEffectDiff::OverrideResult::Merge: {
18922 NewFX.insert(NewEC: Diff.Old.value(), Errs);
18923 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18924 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18925 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18926 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
18927 Args: NewFT->getParamTypes(), EPI);
18928 New->setType(ModQT);
18929 if (Errs.empty()) {
18930 // A warning here is somewhat pedantic. Skip this if there was
18931 // already a merge conflict, which is more serious.
18932 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
18933 << Diff.effectName();
18934 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18935 << Old->getReturnTypeSourceRange();
18936 }
18937 break;
18938 }
18939 }
18940 }
18941 if (!Errs.empty())
18942 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
18943 OldLoc: Old->getLocation());
18944 }
18945 }
18946
18947 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18948
18949 // If the calling conventions match, everything is fine
18950 if (NewCC == OldCC)
18951 return false;
18952
18953 // If the calling conventions mismatch because the new function is static,
18954 // suppress the calling convention mismatch error; the error about static
18955 // function override (err_static_overrides_virtual from
18956 // Sema::CheckFunctionDeclaration) is more clear.
18957 if (New->getStorageClass() == SC_Static)
18958 return false;
18959
18960 Diag(Loc: New->getLocation(),
18961 DiagID: diag::err_conflicting_overriding_cc_attributes)
18962 << New->getDeclName() << New->getType() << Old->getType();
18963 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18964 return true;
18965}
18966
18967bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18968 const CXXMethodDecl *Old) {
18969 // CWG2553
18970 // A virtual function shall not be an explicit object member function.
18971 if (!New->isExplicitObjectMemberFunction())
18972 return true;
18973 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
18974 DiagID: diag::err_explicit_object_parameter_nonmember)
18975 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18976 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18977 New->setInvalidDecl();
18978 return false;
18979}
18980
18981bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18982 const CXXMethodDecl *Old) {
18983 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18984 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18985
18986 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18987 NewTy->isDependentType() || OldTy->isDependentType())
18988 return false;
18989
18990 // Check if the return types are covariant
18991 QualType NewClassTy, OldClassTy;
18992
18993 /// Both types must be pointers or references to classes.
18994 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18995 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18996 NewClassTy = NewPT->getPointeeType();
18997 OldClassTy = OldPT->getPointeeType();
18998 }
18999 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19000 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19001 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19002 NewClassTy = NewRT->getPointeeType();
19003 OldClassTy = OldRT->getPointeeType();
19004 }
19005 }
19006 }
19007
19008 // The return types aren't either both pointers or references to a class type.
19009 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19010 Diag(Loc: New->getLocation(),
19011 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
19012 << New->getDeclName() << NewTy << OldTy
19013 << New->getReturnTypeSourceRange();
19014 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19015 << Old->getReturnTypeSourceRange();
19016
19017 return true;
19018 }
19019
19020 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
19021 // C++14 [class.virtual]p8:
19022 // If the class type in the covariant return type of D::f differs from
19023 // that of B::f, the class type in the return type of D::f shall be
19024 // complete at the point of declaration of D::f or shall be the class
19025 // type D.
19026 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19027 if (!RD->isBeingDefined() &&
19028 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
19029 DiagID: diag::err_covariant_return_incomplete,
19030 Args: New->getDeclName()))
19031 return true;
19032 }
19033
19034 // Check if the new class derives from the old class.
19035 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
19036 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
19037 << New->getDeclName() << NewTy << OldTy
19038 << New->getReturnTypeSourceRange();
19039 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19040 << Old->getReturnTypeSourceRange();
19041 return true;
19042 }
19043
19044 // Check if we the conversion from derived to base is valid.
19045 if (CheckDerivedToBaseConversion(
19046 Derived: NewClassTy, Base: OldClassTy,
19047 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
19048 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
19049 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
19050 Name: New->getDeclName(), BasePath: nullptr)) {
19051 // FIXME: this note won't trigger for delayed access control
19052 // diagnostics, and it's impossible to get an undelayed error
19053 // here from access control during the original parse because
19054 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19055 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19056 << Old->getReturnTypeSourceRange();
19057 return true;
19058 }
19059 }
19060
19061 // The qualifiers of the return types must be the same.
19062 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19063 Diag(Loc: New->getLocation(),
19064 DiagID: diag::err_covariant_return_type_different_qualifications)
19065 << New->getDeclName() << NewTy << OldTy
19066 << New->getReturnTypeSourceRange();
19067 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19068 << Old->getReturnTypeSourceRange();
19069 return true;
19070 }
19071
19072
19073 // The new class type must have the same or less qualifiers as the old type.
19074 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
19075 Diag(Loc: New->getLocation(),
19076 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19077 << New->getDeclName() << NewTy << OldTy
19078 << New->getReturnTypeSourceRange();
19079 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19080 << Old->getReturnTypeSourceRange();
19081 return true;
19082 }
19083
19084 return false;
19085}
19086
19087bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
19088 SourceLocation EndLoc = InitRange.getEnd();
19089 if (EndLoc.isValid())
19090 Method->setRangeEnd(EndLoc);
19091
19092 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19093 Method->setIsPureVirtual();
19094 return false;
19095 }
19096
19097 if (!Method->isInvalidDecl())
19098 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19099 << Method->getDeclName() << InitRange;
19100 return true;
19101}
19102
19103void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19104 if (D->getFriendObjectKind())
19105 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19106 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19107 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19108 else
19109 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19110}
19111
19112/// Invoked when we are about to parse an initializer for the declaration
19113/// 'Dcl'.
19114///
19115/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19116/// static data member of class X, names should be looked up in the scope of
19117/// class X. If the declaration had a scope specifier, a scope will have
19118/// been created and passed in for this purpose. Otherwise, S will be null.
19119void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19120 assert(D && !D->isInvalidDecl());
19121
19122 // We will always have a nested name specifier here, but this declaration
19123 // might not be out of line if the specifier names the current namespace:
19124 // extern int n;
19125 // int ::n = 0;
19126 if (S && D->isOutOfLine())
19127 EnterDeclaratorContext(S, DC: D->getDeclContext());
19128
19129 PushExpressionEvaluationContext(
19130 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19131 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19132}
19133
19134void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19135 assert(D);
19136
19137 if (S && D->isOutOfLine())
19138 ExitDeclaratorContext(S);
19139
19140 PopExpressionEvaluationContext();
19141}
19142
19143DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19144 // C++ 6.4p2:
19145 // The declarator shall not specify a function or an array.
19146 // The type-specifier-seq shall not contain typedef and shall not declare a
19147 // new class or enumeration.
19148 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19149 "Parser allowed 'typedef' as storage class of condition decl.");
19150
19151 Decl *Dcl = ActOnDeclarator(S, D);
19152 if (!Dcl)
19153 return true;
19154
19155 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19156 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19157 << D.getSourceRange();
19158 return true;
19159 }
19160
19161 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19162 VD->setCXXCondDecl();
19163
19164 return Dcl;
19165}
19166
19167void Sema::LoadExternalVTableUses() {
19168 if (!ExternalSource)
19169 return;
19170
19171 SmallVector<ExternalVTableUse, 4> VTables;
19172 ExternalSource->ReadUsedVTables(VTables);
19173 SmallVector<VTableUse, 4> NewUses;
19174 for (const ExternalVTableUse &VTable : VTables) {
19175 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19176 VTablesUsed.find(Val: VTable.Record);
19177 // Even if a definition wasn't required before, it may be required now.
19178 if (Pos != VTablesUsed.end()) {
19179 if (!Pos->second && VTable.DefinitionRequired)
19180 Pos->second = true;
19181 continue;
19182 }
19183
19184 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19185 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19186 }
19187
19188 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19189}
19190
19191void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19192 bool DefinitionRequired) {
19193 // Ignore any vtable uses in unevaluated operands or for classes that do
19194 // not have a vtable.
19195 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19196 CurContext->isDependentContext() || isUnevaluatedContext())
19197 return;
19198 // Do not mark as used if compiling for the device outside of the target
19199 // region.
19200 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19201 !OpenMP().isInOpenMPDeclareTargetContext() &&
19202 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19203 if (!DefinitionRequired)
19204 MarkVirtualMembersReferenced(Loc, RD: Class);
19205 return;
19206 }
19207
19208 // Try to insert this class into the map.
19209 LoadExternalVTableUses();
19210 Class = Class->getCanonicalDecl();
19211 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19212 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19213 if (!Pos.second) {
19214 // If we already had an entry, check to see if we are promoting this vtable
19215 // to require a definition. If so, we need to reappend to the VTableUses
19216 // list, since we may have already processed the first entry.
19217 if (DefinitionRequired && !Pos.first->second) {
19218 Pos.first->second = true;
19219 } else {
19220 // Otherwise, we can early exit.
19221 return;
19222 }
19223 } else {
19224 // The Microsoft ABI requires that we perform the destructor body
19225 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19226 // the deleting destructor is emitted with the vtable, not with the
19227 // destructor definition as in the Itanium ABI.
19228 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19229 CXXDestructorDecl *DD = Class->getDestructor();
19230 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19231 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19232 // If this is an out-of-line declaration, marking it referenced will
19233 // not do anything. Manually call CheckDestructor to look up operator
19234 // delete().
19235 ContextRAII SavedContext(*this, DD);
19236 CheckDestructor(Destructor: DD);
19237 if (!DD->getOperatorDelete())
19238 DD->setInvalidDecl();
19239 } else {
19240 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19241 }
19242 }
19243 }
19244 }
19245
19246 // Local classes need to have their virtual members marked
19247 // immediately. For all other classes, we mark their virtual members
19248 // at the end of the translation unit.
19249 if (Class->isLocalClass())
19250 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19251 else
19252 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19253}
19254
19255bool Sema::DefineUsedVTables() {
19256 LoadExternalVTableUses();
19257 if (VTableUses.empty())
19258 return false;
19259
19260 // Note: The VTableUses vector could grow as a result of marking
19261 // the members of a class as "used", so we check the size each
19262 // time through the loop and prefer indices (which are stable) to
19263 // iterators (which are not).
19264 bool DefinedAnything = false;
19265 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19266 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19267 if (!Class)
19268 continue;
19269 TemplateSpecializationKind ClassTSK =
19270 Class->getTemplateSpecializationKind();
19271
19272 SourceLocation Loc = VTableUses[I].second;
19273
19274 bool DefineVTable = true;
19275
19276 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19277 // V-tables for non-template classes with an owning module are always
19278 // uniquely emitted in that module.
19279 if (Class->isInCurrentModuleUnit()) {
19280 DefineVTable = true;
19281 } else if (KeyFunction && !KeyFunction->hasBody()) {
19282 // If this class has a key function, but that key function is
19283 // defined in another translation unit, we don't need to emit the
19284 // vtable even though we're using it.
19285 // The key function is in another translation unit.
19286 DefineVTable = false;
19287 TemplateSpecializationKind TSK =
19288 KeyFunction->getTemplateSpecializationKind();
19289 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19290 TSK != TSK_ImplicitInstantiation &&
19291 "Instantiations don't have key functions");
19292 (void)TSK;
19293 } else if (!KeyFunction) {
19294 // If we have a class with no key function that is the subject
19295 // of an explicit instantiation declaration, suppress the
19296 // vtable; it will live with the explicit instantiation
19297 // definition.
19298 bool IsExplicitInstantiationDeclaration =
19299 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19300 for (auto *R : Class->redecls()) {
19301 TemplateSpecializationKind TSK
19302 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19303 if (TSK == TSK_ExplicitInstantiationDeclaration)
19304 IsExplicitInstantiationDeclaration = true;
19305 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19306 IsExplicitInstantiationDeclaration = false;
19307 break;
19308 }
19309 }
19310
19311 if (IsExplicitInstantiationDeclaration) {
19312 const bool HasExcludeFromExplicitInstantiation =
19313 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19314 // If the class has a member function declared with
19315 // `__attribute__((exclude_from_explicit_instantiation))`, the
19316 // explicit instantiation declaration should not suppress emitting
19317 // the vtable, since the corresponding explicit instantiation
19318 // definition might not emit the vtable if a triggering method is
19319 // excluded.
19320 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19321 });
19322 if (!HasExcludeFromExplicitInstantiation)
19323 DefineVTable = false;
19324 }
19325 }
19326
19327 // The exception specifications for all virtual members may be needed even
19328 // if we are not providing an authoritative form of the vtable in this TU.
19329 // We may choose to emit it available_externally anyway.
19330 if (!DefineVTable) {
19331 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19332 continue;
19333 }
19334
19335 // Mark all of the virtual members of this class as referenced, so
19336 // that we can build a vtable. Then, tell the AST consumer that a
19337 // vtable for this class is required.
19338 DefinedAnything = true;
19339 MarkVirtualMembersReferenced(Loc, RD: Class);
19340 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19341 // The vtable is assumed to be emitted in an external source only for
19342 // classes attached to a named module, which is guaranteed to have an object
19343 // file. This isn't true for -fmodules-debuginfo, which still has
19344 // shouldEmitInExternalSource as true so that debug info gets supressed.
19345 if (VTablesUsed[Canonical] &&
19346 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19347 Consumer.HandleVTable(RD: Class);
19348
19349 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19350 // no key function or the key function is inlined. Don't warn in C++ ABIs
19351 // that lack key functions, since the user won't be able to make one.
19352 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19353 Class->isExternallyVisible() &&
19354 !(Class->getOwningModule() &&
19355 Class->getOwningModule()->isInterfaceOrPartition()) &&
19356 ClassTSK != TSK_ImplicitInstantiation &&
19357 ClassTSK != TSK_ExplicitInstantiationDeclaration &&
19358 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19359 const FunctionDecl *KeyFunctionDef = nullptr;
19360 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19361 KeyFunctionDef->isInlined()))
19362 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19363 }
19364 }
19365 VTableUses.clear();
19366
19367 return DefinedAnything;
19368}
19369
19370void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19371 const CXXRecordDecl *RD) {
19372 for (const auto *I : RD->methods())
19373 if (I->isVirtual() && !I->isPureVirtual())
19374 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19375}
19376
19377void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19378 const CXXRecordDecl *RD,
19379 bool ConstexprOnly) {
19380 // Mark all functions which will appear in RD's vtable as used.
19381 CXXFinalOverriderMap FinalOverriders;
19382 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19383 for (const auto &FinalOverrider : FinalOverriders) {
19384 for (const auto &OverridingMethod : FinalOverrider.second) {
19385 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19386 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19387
19388 // C++ [basic.def.odr]p2:
19389 // [...] A virtual member function is used if it is not pure. [...]
19390 if (!Overrider->isPureVirtual() &&
19391 (!ConstexprOnly || Overrider->isConstexpr()))
19392 MarkFunctionReferenced(Loc, Func: Overrider);
19393 }
19394 }
19395
19396 // Only classes that have virtual bases need a VTT.
19397 if (RD->getNumVBases() == 0)
19398 return;
19399
19400 for (const auto &I : RD->bases()) {
19401 const auto *Base = I.getType()->castAsCXXRecordDecl();
19402 if (Base->getNumVBases() == 0)
19403 continue;
19404 MarkVirtualMembersReferenced(Loc, RD: Base);
19405 }
19406}
19407
19408static
19409void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19410 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19411 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19412 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19413 Sema &S) {
19414 if (Ctor->isInvalidDecl())
19415 return;
19416
19417 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19418
19419 // Target may not be determinable yet, for instance if this is a dependent
19420 // call in an uninstantiated template.
19421 if (Target) {
19422 const FunctionDecl *FNTarget = nullptr;
19423 (void)Target->hasBody(Definition&: FNTarget);
19424 Target = const_cast<CXXConstructorDecl*>(
19425 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19426 }
19427
19428 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19429 // Avoid dereferencing a null pointer here.
19430 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19431
19432 if (!Current.insert(Ptr: Canonical).second)
19433 return;
19434
19435 // We know that beyond here, we aren't chaining into a cycle.
19436 if (!Target || !Target->isDelegatingConstructor() ||
19437 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19438 Valid.insert_range(R&: Current);
19439 Current.clear();
19440 // We've hit a cycle.
19441 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19442 Current.count(Ptr: TCanonical)) {
19443 // If we haven't diagnosed this cycle yet, do so now.
19444 if (!Invalid.count(Ptr: TCanonical)) {
19445 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19446 DiagID: diag::warn_delegating_ctor_cycle)
19447 << Ctor;
19448
19449 // Don't add a note for a function delegating directly to itself.
19450 if (TCanonical != Canonical)
19451 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19452
19453 CXXConstructorDecl *C = Target;
19454 while (C->getCanonicalDecl() != Canonical) {
19455 const FunctionDecl *FNTarget = nullptr;
19456 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19457 assert(FNTarget && "Ctor cycle through bodiless function");
19458
19459 C = const_cast<CXXConstructorDecl*>(
19460 cast<CXXConstructorDecl>(Val: FNTarget));
19461 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19462 }
19463 }
19464
19465 Invalid.insert_range(R&: Current);
19466 Current.clear();
19467 } else {
19468 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19469 }
19470}
19471
19472
19473void Sema::CheckDelegatingCtorCycles() {
19474 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19475
19476 for (DelegatingCtorDeclsType::iterator
19477 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19478 E = DelegatingCtorDecls.end();
19479 I != E; ++I)
19480 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19481
19482 for (CXXConstructorDecl *CI : Invalid)
19483 CI->setInvalidDecl();
19484}
19485
19486namespace {
19487 /// AST visitor that finds references to the 'this' expression.
19488class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19489 Sema &S;
19490
19491public:
19492 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19493
19494 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19495 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19496 << E->isImplicit();
19497 return false;
19498 }
19499};
19500}
19501
19502bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19503 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19504 if (!TSInfo)
19505 return false;
19506
19507 TypeLoc TL = TSInfo->getTypeLoc();
19508 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19509 if (!ProtoTL)
19510 return false;
19511
19512 // C++11 [expr.prim.general]p3:
19513 // [The expression this] shall not appear before the optional
19514 // cv-qualifier-seq and it shall not appear within the declaration of a
19515 // static member function (although its type and value category are defined
19516 // within a static member function as they are within a non-static member
19517 // function). [ Note: this is because declaration matching does not occur
19518 // until the complete declarator is known. - end note ]
19519 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19520 FindCXXThisExpr Finder(*this);
19521
19522 // If the return type came after the cv-qualifier-seq, check it now.
19523 if (Proto->hasTrailingReturn() &&
19524 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19525 return true;
19526
19527 // Check the exception specification.
19528 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19529 return true;
19530
19531 // Check the trailing requires clause
19532 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19533 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19534 return true;
19535
19536 return checkThisInStaticMemberFunctionAttributes(Method);
19537}
19538
19539bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19540 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19541 if (!TSInfo)
19542 return false;
19543
19544 TypeLoc TL = TSInfo->getTypeLoc();
19545 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19546 if (!ProtoTL)
19547 return false;
19548
19549 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19550 FindCXXThisExpr Finder(*this);
19551
19552 switch (Proto->getExceptionSpecType()) {
19553 case EST_Unparsed:
19554 case EST_Uninstantiated:
19555 case EST_Unevaluated:
19556 case EST_BasicNoexcept:
19557 case EST_NoThrow:
19558 case EST_DynamicNone:
19559 case EST_MSAny:
19560 case EST_None:
19561 break;
19562
19563 case EST_DependentNoexcept:
19564 case EST_NoexceptFalse:
19565 case EST_NoexceptTrue:
19566 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19567 return true;
19568 [[fallthrough]];
19569
19570 case EST_Dynamic:
19571 for (const auto &E : Proto->exceptions()) {
19572 if (!Finder.TraverseType(T: E))
19573 return true;
19574 }
19575 break;
19576 }
19577
19578 return false;
19579}
19580
19581bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19582 FindCXXThisExpr Finder(*this);
19583
19584 // Check attributes.
19585 for (const auto *A : Method->attrs()) {
19586 // FIXME: This should be emitted by tblgen.
19587 Expr *Arg = nullptr;
19588 ArrayRef<Expr *> Args;
19589 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19590 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19591 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19592 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19593 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19594 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19595 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19596 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19597 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19598 Arg = LR->getArg();
19599 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19600 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19601 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19602 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19603 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19604 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19605 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19606 Arg = AC->getSuccessValue();
19607 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19608 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19609 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19610
19611 if (Arg && !Finder.TraverseStmt(S: Arg))
19612 return true;
19613
19614 for (Expr *A : Args) {
19615 if (!Finder.TraverseStmt(S: A))
19616 return true;
19617 }
19618 }
19619
19620 return false;
19621}
19622
19623void Sema::checkExceptionSpecification(
19624 bool IsTopLevel, ExceptionSpecificationType EST,
19625 ArrayRef<ParsedType> DynamicExceptions,
19626 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19627 SmallVectorImpl<QualType> &Exceptions,
19628 FunctionProtoType::ExceptionSpecInfo &ESI) {
19629 Exceptions.clear();
19630 ESI.Type = EST;
19631 if (EST == EST_Dynamic) {
19632 Exceptions.reserve(N: DynamicExceptions.size());
19633 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19634 // FIXME: Preserve type source info.
19635 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19636
19637 if (IsTopLevel) {
19638 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19639 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19640 if (!Unexpanded.empty()) {
19641 DiagnoseUnexpandedParameterPacks(
19642 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19643 Unexpanded);
19644 continue;
19645 }
19646 }
19647
19648 // Check that the type is valid for an exception spec, and
19649 // drop it if not.
19650 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19651 Exceptions.push_back(Elt: ET);
19652 }
19653 ESI.Exceptions = Exceptions;
19654 return;
19655 }
19656
19657 if (isComputedNoexcept(ESpecType: EST)) {
19658 assert((NoexceptExpr->isTypeDependent() ||
19659 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19660 Context.BoolTy) &&
19661 "Parser should have made sure that the expression is boolean");
19662 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19663 ESI.Type = EST_BasicNoexcept;
19664 return;
19665 }
19666
19667 ESI.NoexceptExpr = NoexceptExpr;
19668 return;
19669 }
19670}
19671
19672void Sema::actOnDelayedExceptionSpecification(
19673 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19674 ArrayRef<ParsedType> DynamicExceptions,
19675 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19676 if (!D)
19677 return;
19678
19679 // Dig out the function we're referring to.
19680 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19681 D = FTD->getTemplatedDecl();
19682
19683 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19684 if (!FD)
19685 return;
19686
19687 // Check the exception specification.
19688 llvm::SmallVector<QualType, 4> Exceptions;
19689 FunctionProtoType::ExceptionSpecInfo ESI;
19690 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19691 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19692 ESI);
19693
19694 // Update the exception specification on the function type.
19695 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19696
19697 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19698 if (MD->isStatic())
19699 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19700
19701 if (MD->isVirtual()) {
19702 // Check overrides, which we previously had to delay.
19703 for (const CXXMethodDecl *O : MD->overridden_methods())
19704 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19705 }
19706 }
19707}
19708
19709/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19710///
19711MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19712 SourceLocation DeclStart, Declarator &D,
19713 Expr *BitWidth,
19714 InClassInitStyle InitStyle,
19715 AccessSpecifier AS,
19716 const ParsedAttr &MSPropertyAttr) {
19717 const IdentifierInfo *II = D.getIdentifier();
19718 if (!II) {
19719 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19720 return nullptr;
19721 }
19722 SourceLocation Loc = D.getIdentifierLoc();
19723
19724 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19725 QualType T = TInfo->getType();
19726 if (getLangOpts().CPlusPlus) {
19727 CheckExtraCXXDefaultArguments(D);
19728
19729 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19730 UPPC: UPPC_DataMemberType)) {
19731 D.setInvalidType();
19732 T = Context.IntTy;
19733 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19734 }
19735 }
19736
19737 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19738
19739 if (D.getDeclSpec().isInlineSpecified())
19740 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19741 << getLangOpts().CPlusPlus17;
19742 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19743 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19744 DiagID: diag::err_invalid_thread)
19745 << DeclSpec::getSpecifierName(S: TSCS);
19746
19747 // Check to see if this name was declared as a member previously
19748 NamedDecl *PrevDecl = nullptr;
19749 LookupResult Previous(*this, II, Loc, LookupMemberName,
19750 RedeclarationKind::ForVisibleRedeclaration);
19751 LookupName(R&: Previous, S);
19752 switch (Previous.getResultKind()) {
19753 case LookupResultKind::Found:
19754 case LookupResultKind::FoundUnresolvedValue:
19755 PrevDecl = Previous.getAsSingle<NamedDecl>();
19756 break;
19757
19758 case LookupResultKind::FoundOverloaded:
19759 PrevDecl = Previous.getRepresentativeDecl();
19760 break;
19761
19762 case LookupResultKind::NotFound:
19763 case LookupResultKind::NotFoundInCurrentInstantiation:
19764 case LookupResultKind::Ambiguous:
19765 break;
19766 }
19767
19768 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19769 // Maybe we will complain about the shadowed template parameter.
19770 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19771 // Just pretend that we didn't see the previous declaration.
19772 PrevDecl = nullptr;
19773 }
19774
19775 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19776 PrevDecl = nullptr;
19777
19778 SourceLocation TSSL = D.getBeginLoc();
19779 MSPropertyDecl *NewPD =
19780 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
19781 Getter: MSPropertyAttr.getPropertyDataGetter(),
19782 Setter: MSPropertyAttr.getPropertyDataSetter());
19783 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
19784 NewPD->setAccess(AS);
19785
19786 if (NewPD->isInvalidDecl())
19787 Record->setInvalidDecl();
19788
19789 if (D.getDeclSpec().isModulePrivateSpecified())
19790 NewPD->setModulePrivate();
19791
19792 if (NewPD->isInvalidDecl() && PrevDecl) {
19793 // Don't introduce NewFD into scope; there's already something
19794 // with the same name in the same scope.
19795 } else if (II) {
19796 PushOnScopeChains(D: NewPD, S);
19797 } else
19798 Record->addDecl(D: NewPD);
19799
19800 return NewPD;
19801}
19802
19803void Sema::ActOnStartFunctionDeclarationDeclarator(
19804 Declarator &Declarator, unsigned TemplateParameterDepth) {
19805 auto &Info = InventedParameterInfos.emplace_back();
19806 TemplateParameterList *ExplicitParams = nullptr;
19807 ArrayRef<TemplateParameterList *> ExplicitLists =
19808 Declarator.getTemplateParameterLists();
19809 if (!ExplicitLists.empty()) {
19810 bool IsMemberSpecialization, IsInvalid;
19811 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19812 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19813 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19814 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19815 /*SuppressDiagnostic=*/true);
19816 }
19817 // C++23 [dcl.fct]p23:
19818 // An abbreviated function template can have a template-head. The invented
19819 // template-parameters are appended to the template-parameter-list after
19820 // the explicitly declared template-parameters.
19821 //
19822 // A template-head must have one or more template-parameters (read:
19823 // 'template<>' is *not* a template-head). Only append the invented
19824 // template parameters if we matched the nested-name-specifier to a non-empty
19825 // TemplateParameterList.
19826 if (ExplicitParams && !ExplicitParams->empty()) {
19827 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19828 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19829 Info.NumExplicitTemplateParams = ExplicitParams->size();
19830 } else {
19831 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19832 Info.NumExplicitTemplateParams = 0;
19833 }
19834}
19835
19836void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19837 auto &FSI = InventedParameterInfos.back();
19838 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19839 if (FSI.NumExplicitTemplateParams != 0) {
19840 TemplateParameterList *ExplicitParams =
19841 Declarator.getTemplateParameterLists().back();
19842 Declarator.setInventedTemplateParameterList(
19843 TemplateParameterList::Create(
19844 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19845 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19846 RAngleLoc: ExplicitParams->getRAngleLoc(),
19847 RequiresClause: ExplicitParams->getRequiresClause()));
19848 } else {
19849 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
19850 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
19851 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
19852 /*RequiresClause=*/nullptr));
19853 }
19854 }
19855 InventedParameterInfos.pop_back();
19856}
19857
19858bool Sema::BuildCtorClosureDefaultArgs(SourceLocation Loc,
19859 CXXConstructorDecl *Ctor, bool IsCopy) {
19860 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
19861
19862 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
19863 // If we build args for default constructor closures, those will have
19864 // been generated *before* building args for any copy constructor closures.
19865 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
19866 return false;
19867 }
19868
19869 unsigned NumParams = Ctor->getNumParams();
19870 if (NumParams == 0)
19871 return false;
19872
19873 CXXDefaultArgExpr **Args =
19874 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
19875
19876 if (IsCopy)
19877 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
19878
19879 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
19880 ExprResult R = BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Ctor, Param: Ctor->getParamDecl(i: I));
19881 CleanupVarDeclMarking();
19882 if (R.isInvalid())
19883 return true;
19884 Args[I] = cast<CXXDefaultArgExpr>(Val: R.get());
19885 }
19886
19887 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
19888 return false;
19889}
19890