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/SemaProxy.h"
50#include "clang/Sema/Template.h"
51#include "clang/Sema/TemplateDeduction.h"
52#include "llvm/ADT/ArrayRef.h"
53#include "llvm/ADT/STLExtras.h"
54#include "llvm/ADT/StringExtras.h"
55#include "llvm/Support/ConvertUTF.h"
56#include "llvm/Support/SaveAndRestore.h"
57#include <map>
58#include <optional>
59#include <set>
60
61using namespace clang;
62
63//===----------------------------------------------------------------------===//
64// CheckDefaultArgumentVisitor
65//===----------------------------------------------------------------------===//
66
67namespace {
68/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
69/// the default argument of a parameter to determine whether it
70/// contains any ill-formed subexpressions. For example, this will
71/// diagnose the use of local variables or parameters within the
72/// default argument expression.
73class CheckDefaultArgumentVisitor
74 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
75 Sema &S;
76 const Expr *DefaultArg;
77
78public:
79 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
80 : S(S), DefaultArg(DefaultArg) {}
81
82 bool VisitExpr(const Expr *Node);
83 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
84 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
85 bool VisitLambdaExpr(const LambdaExpr *Lambda);
86 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
87 bool VisitCoawaitExpr(const CoawaitExpr *E);
88 bool VisitCoyieldExpr(const CoyieldExpr *E);
89};
90
91/// VisitExpr - Visit all of the children of this expression.
92bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
93 bool IsInvalid = false;
94 for (const Stmt *SubStmt : Node->children())
95 if (SubStmt)
96 IsInvalid |= Visit(S: SubStmt);
97 return IsInvalid;
98}
99
100/// VisitDeclRefExpr - Visit a reference to a declaration, to
101/// determine whether this declaration can be used in the default
102/// argument expression.
103bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
104 const ValueDecl *Decl = DRE->getDecl();
105
106 if (!isa<VarDecl, BindingDecl>(Val: Decl))
107 return false;
108
109 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
110 // C++ [dcl.fct.default]p9:
111 // [...] parameters of a function shall not be used in default
112 // argument expressions, even if they are not evaluated. [...]
113 //
114 // C++17 [dcl.fct.default]p9 (by CWG 2082):
115 // [...] A parameter shall not appear as a potentially-evaluated
116 // expression in a default argument. [...]
117 //
118 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
119 return S.Diag(Loc: DRE->getBeginLoc(),
120 DiagID: diag::err_param_default_argument_references_param)
121 << Param->getDeclName() << DefaultArg->getSourceRange();
122 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
123 // C++ [dcl.fct.default]p7:
124 // Local variables shall not be used in default argument
125 // expressions.
126 //
127 // C++17 [dcl.fct.default]p7 (by CWG 2082):
128 // A local variable shall not appear as a potentially-evaluated
129 // expression in a default argument.
130 //
131 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
132 // Note: A local variable cannot be odr-used (6.3) in a default
133 // argument.
134 //
135 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
136 return S.Diag(Loc: DRE->getBeginLoc(),
137 DiagID: diag::err_param_default_argument_references_local)
138 << Decl << DefaultArg->getSourceRange();
139 }
140 return false;
141}
142
143/// VisitCXXThisExpr - Visit a C++ "this" expression.
144bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
145 // C++ [dcl.fct.default]p8:
146 // The keyword this shall not be used in a default argument of a
147 // member function.
148 return S.Diag(Loc: ThisE->getBeginLoc(),
149 DiagID: diag::err_param_default_argument_references_this)
150 << ThisE->getSourceRange();
151}
152
153bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
154 const PseudoObjectExpr *POE) {
155 bool Invalid = false;
156 for (const Expr *E : POE->semantics()) {
157 // Look through bindings.
158 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
159 E = OVE->getSourceExpr();
160 assert(E && "pseudo-object binding without source expression?");
161 }
162
163 Invalid |= Visit(S: E);
164 }
165 return Invalid;
166}
167
168bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
169 // [expr.prim.lambda.capture]p9
170 // a lambda-expression appearing in a default argument cannot implicitly or
171 // explicitly capture any local entity. Such a lambda-expression can still
172 // have an init-capture if any full-expression in its initializer satisfies
173 // the constraints of an expression appearing in a default argument.
174 bool Invalid = false;
175 for (const LambdaCapture &LC : Lambda->captures()) {
176 if (!Lambda->isInitCapture(Capture: &LC))
177 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
178 // Init captures are always VarDecl.
179 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
180 Invalid |= Visit(S: D->getInit());
181 }
182 return Invalid;
183}
184
185bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
186 // [expr.await] An await-expression shall not appear in a default argument.
187 // Note that this is generally diagnosed by isValidCoroutineContext,
188 // however isValidCoroutineContext misses default argument in nested
189 // function declarations.
190 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
191 << "co_await" << E->getSourceRange();
192 return true;
193}
194
195bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
196 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
197 << "co_yield" << E->getSourceRange();
198 return true;
199}
200
201} // namespace
202
203void
204Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
205 const CXXMethodDecl *Method) {
206 // If we have an MSAny spec already, don't bother.
207 if (!Method || ComputedEST == EST_MSAny)
208 return;
209
210 const FunctionProtoType *Proto
211 = Method->getType()->getAs<FunctionProtoType>();
212 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
213 if (!Proto)
214 return;
215
216 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
217
218 // If we have a throw-all spec at this point, ignore the function.
219 if (ComputedEST == EST_None)
220 return;
221
222 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
223 EST = EST_BasicNoexcept;
224
225 switch (EST) {
226 case EST_Unparsed:
227 case EST_Uninstantiated:
228 case EST_Unevaluated:
229 llvm_unreachable("should not see unresolved exception specs here");
230
231 // If this function can throw any exceptions, make a note of that.
232 case EST_MSAny:
233 case EST_None:
234 // FIXME: Whichever we see last of MSAny and None determines our result.
235 // We should make a consistent, order-independent choice here.
236 ClearExceptions();
237 ComputedEST = EST;
238 return;
239 case EST_NoexceptFalse:
240 ClearExceptions();
241 ComputedEST = EST_None;
242 return;
243 // FIXME: If the call to this decl is using any of its default arguments, we
244 // need to search them for potentially-throwing calls.
245 // If this function has a basic noexcept, it doesn't affect the outcome.
246 case EST_BasicNoexcept:
247 case EST_NoexceptTrue:
248 case EST_NoThrow:
249 return;
250 // If we're still at noexcept(true) and there's a throw() callee,
251 // change to that specification.
252 case EST_DynamicNone:
253 if (ComputedEST == EST_BasicNoexcept)
254 ComputedEST = EST_DynamicNone;
255 return;
256 case EST_DependentNoexcept:
257 llvm_unreachable(
258 "should not generate implicit declarations for dependent cases");
259 case EST_Dynamic:
260 break;
261 }
262 assert(EST == EST_Dynamic && "EST case not considered earlier.");
263 assert(ComputedEST != EST_None &&
264 "Shouldn't collect exceptions when throw-all is guaranteed.");
265 ComputedEST = EST_Dynamic;
266 // Record the exceptions in this function's exception specification.
267 for (const auto &E : Proto->exceptions())
268 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
269 Exceptions.push_back(Elt: E);
270}
271
272void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
273 if (!S || ComputedEST == EST_MSAny)
274 return;
275
276 // FIXME:
277 //
278 // C++0x [except.spec]p14:
279 // [An] implicit exception-specification specifies the type-id T if and
280 // only if T is allowed by the exception-specification of a function directly
281 // invoked by f's implicit definition; f shall allow all exceptions if any
282 // function it directly invokes allows all exceptions, and f shall allow no
283 // exceptions if every function it directly invokes allows no exceptions.
284 //
285 // Note in particular that if an implicit exception-specification is generated
286 // for a function containing a throw-expression, that specification can still
287 // be noexcept(true).
288 //
289 // Note also that 'directly invoked' is not defined in the standard, and there
290 // is no indication that we should only consider potentially-evaluated calls.
291 //
292 // Ultimately we should implement the intent of the standard: the exception
293 // specification should be the set of exceptions which can be thrown by the
294 // implicit definition. For now, we assume that any non-nothrow expression can
295 // throw any exception.
296
297 if (Self->canThrow(E: S))
298 ComputedEST = EST_None;
299}
300
301ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
302 SourceLocation EqualLoc) {
303 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
304 DiagID: diag::err_typecheck_decl_incomplete_type))
305 return true;
306
307 // C++ [dcl.fct.default]p5
308 // A default argument expression is implicitly converted (clause
309 // 4) to the parameter type. The default argument expression has
310 // the same semantic constraints as the initializer expression in
311 // a declaration of a variable of the parameter type, using the
312 // copy-initialization semantics (8.5).
313 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
314 Parm: Param);
315 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
316 EqualLoc);
317 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
318 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
319 if (Result.isInvalid())
320 return true;
321 Arg = Result.getAs<Expr>();
322
323 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
324 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
325
326 return Arg;
327}
328
329void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
330 SourceLocation EqualLoc) {
331 // Add the default argument to the parameter
332 Param->setDefaultArg(Arg);
333
334 // We have already instantiated this parameter; provide each of the
335 // instantiations with the uninstantiated default argument.
336 UnparsedDefaultArgInstantiationsMap::iterator InstPos
337 = UnparsedDefaultArgInstantiations.find(Val: Param);
338 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
339 for (auto &Instantiation : InstPos->second)
340 Instantiation->setUninstantiatedDefaultArg(Arg);
341
342 // We're done tracking this parameter's instantiations.
343 UnparsedDefaultArgInstantiations.erase(I: InstPos);
344 }
345}
346
347void
348Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
349 Expr *DefaultArg) {
350 if (!param || !DefaultArg)
351 return;
352
353 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
354 UnparsedDefaultArgLocs.erase(Val: Param);
355
356 // Default arguments are only permitted in C++
357 if (!getLangOpts().CPlusPlus) {
358 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
359 << DefaultArg->getSourceRange();
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361 }
362
363 // C++11 [dcl.fct.default]p3
364 // A default argument expression [...] shall not be specified for a
365 // parameter pack.
366 //
367 // Check this before looking for unexpanded parameter packs in DefaultArg:
368 // if DefaultArg references a pack from an enclosing lambda/block, that
369 // check would (incorrectly) mark the lambda as containing an unexpanded
370 // pack that never actually appears in the final AST once we discard
371 // DefaultArg below.
372 if (Param->isParameterPack()) {
373 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
374 << DefaultArg->getSourceRange();
375 // Recover by discarding the default argument.
376 Param->setDefaultArg(nullptr);
377 return;
378 }
379
380 // Check for unexpanded parameter packs.
381 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
382 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
383
384 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
385 if (Result.isInvalid())
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 DefaultArg = Result.getAs<Expr>();
389
390 // Check that the default argument is well-formed
391 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
392 if (DefaultArgChecker.Visit(S: DefaultArg))
393 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
394
395 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
396}
397
398void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
399 SourceLocation EqualLoc,
400 SourceLocation ArgLoc) {
401 if (!param)
402 return;
403
404 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
405 Param->setUnparsedDefaultArg();
406 UnparsedDefaultArgLocs[Param] = ArgLoc;
407}
408
409void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
410 Expr *DefaultArg) {
411 if (!param)
412 return;
413
414 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
415 Param->setInvalidDecl();
416 UnparsedDefaultArgLocs.erase(Val: Param);
417 ExprResult RE;
418 if (DefaultArg) {
419 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
420 T: Param->getType().getNonReferenceType());
421 } else {
422 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
423 T: Param->getType().getNonReferenceType());
424 }
425 Param->setDefaultArg(RE.get());
426}
427
428void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
429 // C++ [dcl.fct.default]p3
430 // A default argument expression shall be specified only in the
431 // parameter-declaration-clause of a function declaration or in a
432 // template-parameter (14.1). It shall not be specified for a
433 // parameter pack. If it is specified in a
434 // parameter-declaration-clause, it shall not occur within a
435 // declarator or abstract-declarator of a parameter-declaration.
436 bool MightBeFunction = D.isFunctionDeclarationContext();
437 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
438 DeclaratorChunk &chunk = D.getTypeObject(i);
439 if (chunk.Kind == DeclaratorChunk::Function) {
440 if (MightBeFunction) {
441 // This is a function declaration. It can have default arguments, but
442 // keep looking in case its return type is a function type with default
443 // arguments.
444 MightBeFunction = false;
445 continue;
446 }
447 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
448 ++argIdx) {
449 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
450 if (Param->hasUnparsedDefaultArg()) {
451 std::unique_ptr<CachedTokens> Toks =
452 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
453 SourceRange SR;
454 if (Toks->size() > 1)
455 SR = SourceRange((*Toks)[1].getLocation(),
456 Toks->back().getLocation());
457 else
458 SR = UnparsedDefaultArgLocs[Param];
459 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
460 << SR;
461 } else if (Param->getDefaultArg()) {
462 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
463 << Param->getDefaultArg()->getSourceRange();
464 Param->setDefaultArg(nullptr);
465 }
466 }
467 } else if (chunk.Kind != DeclaratorChunk::Paren) {
468 MightBeFunction = false;
469 }
470 }
471}
472
473static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
474 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
475 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
476 });
477}
478
479bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
480 Scope *S) {
481 bool Invalid = false;
482
483 // The declaration context corresponding to the scope is the semantic
484 // parent, unless this is a local function declaration, in which case
485 // it is that surrounding function.
486 DeclContext *ScopeDC = New->isLocalExternDecl()
487 ? New->getLexicalDeclContext()
488 : New->getDeclContext();
489
490 // Find the previous declaration for the purpose of default arguments.
491 FunctionDecl *PrevForDefaultArgs = Old;
492 for (/**/; PrevForDefaultArgs;
493 // Don't bother looking back past the latest decl if this is a local
494 // extern declaration; nothing else could work.
495 PrevForDefaultArgs = New->isLocalExternDecl()
496 ? nullptr
497 : PrevForDefaultArgs->getPreviousDecl()) {
498 // Ignore hidden declarations.
499 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
500 continue;
501
502 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
503 !New->isCXXClassMember()) {
504 // Ignore default arguments of old decl if they are not in
505 // the same scope and this is not an out-of-line definition of
506 // a member function.
507 continue;
508 }
509
510 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
511 // If only one of these is a local function declaration, then they are
512 // declared in different scopes, even though isDeclInScope may think
513 // they're in the same scope. (If both are local, the scope check is
514 // sufficient, and if neither is local, then they are in the same scope.)
515 continue;
516 }
517
518 if (PrevForDefaultArgs->getFriendObjectKind()) {
519 // Don't inherit default arguments from a friend declaration. It's invalid
520 // to redeclare such a function at all if it owns the default arguments;
521 // we check for that later. Otherwise, it's not the declaration that we're
522 // inheriting them from.
523 continue;
524 }
525
526 // We found the right previous declaration.
527 break;
528 }
529
530 // C++ [dcl.fct.default]p4:
531 // For non-template functions, default arguments can be added in
532 // later declarations of a function in the same
533 // scope. Declarations in different scopes have completely
534 // distinct sets of default arguments. That is, declarations in
535 // inner scopes do not acquire default arguments from
536 // declarations in outer scopes, and vice versa. In a given
537 // function declaration, all parameters subsequent to a
538 // parameter with a default argument shall have default
539 // arguments supplied in this or previous declarations. A
540 // default argument shall not be redefined by a later
541 // declaration (not even to the same value).
542 //
543 // C++ [dcl.fct.default]p6:
544 // Except for member functions of class templates, the default arguments
545 // in a member function definition that appears outside of the class
546 // definition are added to the set of default arguments provided by the
547 // member function declaration in the class definition.
548 for (unsigned p = 0, NumParams = PrevForDefaultArgs
549 ? PrevForDefaultArgs->getNumParams()
550 : 0;
551 p < NumParams; ++p) {
552 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
553 ParmVarDecl *NewParam = New->getParamDecl(i: p);
554
555 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
556 bool NewParamHasDfl = NewParam->hasDefaultArg();
557
558 if (OldParamHasDfl && NewParamHasDfl) {
559 unsigned DiagDefaultParamID =
560 diag::err_param_default_argument_redefinition;
561
562 // MSVC accepts that default parameters be redefined for member functions
563 // of template class. The new default parameter's value is ignored.
564 Invalid = true;
565 if (getLangOpts().MicrosoftExt) {
566 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
567 if (MD && MD->getParent()->getDescribedClassTemplate()) {
568 // Merge the old default argument into the new parameter.
569 NewParam->setHasInheritedDefaultArg();
570 if (OldParam->hasUninstantiatedDefaultArg())
571 NewParam->setUninstantiatedDefaultArg(
572 OldParam->getUninstantiatedDefaultArg());
573 else
574 NewParam->setDefaultArg(OldParam->getInit());
575 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
576 Invalid = false;
577 }
578 }
579
580 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
581 // hint here. Alternatively, we could walk the type-source information
582 // for NewParam to find the last source location in the type... but it
583 // isn't worth the effort right now. This is the kind of test case that
584 // is hard to get right:
585 // int f(int);
586 // void g(int (*fp)(int) = f);
587 // void g(int (*fp)(int) = &f);
588 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
589 << NewParam->getDefaultArgRange();
590
591 // Look for the function declaration where the default argument was
592 // actually written, which may be a declaration prior to Old.
593 for (auto Older = PrevForDefaultArgs;
594 OldParam->hasInheritedDefaultArg(); /**/) {
595 Older = Older->getPreviousDecl();
596 OldParam = Older->getParamDecl(i: p);
597 }
598
599 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
600 << OldParam->getDefaultArgRange();
601 } else if (OldParamHasDfl) {
602 // Merge the old default argument into the new parameter unless the new
603 // function is a friend declaration in a template class. In the latter
604 // case the default arguments will be inherited when the friend
605 // declaration will be instantiated.
606 if (New->getFriendObjectKind() == Decl::FOK_None ||
607 !New->getLexicalDeclContext()->isDependentContext()) {
608 // It's important to use getInit() here; getDefaultArg()
609 // strips off any top-level ExprWithCleanups.
610 NewParam->setHasInheritedDefaultArg();
611 if (OldParam->hasUnparsedDefaultArg())
612 NewParam->setUnparsedDefaultArg();
613 else if (OldParam->hasUninstantiatedDefaultArg())
614 NewParam->setUninstantiatedDefaultArg(
615 OldParam->getUninstantiatedDefaultArg());
616 else
617 NewParam->setDefaultArg(OldParam->getInit());
618 }
619 } else if (NewParamHasDfl) {
620 if (New->getDescribedFunctionTemplate()) {
621 // Paragraph 4, quoted above, only applies to non-template functions.
622 Diag(Loc: NewParam->getLocation(),
623 DiagID: diag::err_param_default_argument_template_redecl)
624 << NewParam->getDefaultArgRange();
625 Diag(Loc: PrevForDefaultArgs->getLocation(),
626 DiagID: diag::note_template_prev_declaration)
627 << false;
628 } else if (New->getTemplateSpecializationKind()
629 != TSK_ImplicitInstantiation &&
630 New->getTemplateSpecializationKind() != TSK_Undeclared) {
631 // C++ [temp.expr.spec]p21:
632 // Default function arguments shall not be specified in a declaration
633 // or a definition for one of the following explicit specializations:
634 // - the explicit specialization of a function template;
635 // - the explicit specialization of a member function template;
636 // - the explicit specialization of a member function of a class
637 // template where the class template specialization to which the
638 // member function specialization belongs is implicitly
639 // instantiated.
640 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
641 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
642 << New->getDeclName()
643 << NewParam->getDefaultArgRange();
644 } else if (New->getDeclContext()
645 ->getEnclosingNonExpansionStatementContext()
646 ->isDependentContext()) {
647 // C++ [dcl.fct.default]p6 (DR217):
648 // Default arguments for a member function of a class template shall
649 // be specified on the initial declaration of the member function
650 // within the class template.
651 //
652 // Reading the tea leaves a bit in DR217 and its reference to DR205
653 // leads me to the conclusion that one cannot add default function
654 // arguments for an out-of-line definition of a member function of a
655 // dependent type.
656 int WhichKind = 2;
657 if (CXXRecordDecl *Record
658 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
659 if (Record->getDescribedClassTemplate())
660 WhichKind = 0;
661 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
662 WhichKind = 1;
663 else
664 WhichKind = 2;
665 }
666
667 Diag(Loc: NewParam->getLocation(),
668 DiagID: diag::err_param_default_argument_member_template_redecl)
669 << WhichKind
670 << NewParam->getDefaultArgRange();
671 }
672 }
673 }
674
675 // DR1344: If a default argument is added outside a class definition and that
676 // default argument makes the function a special member function, the program
677 // is ill-formed. This can only happen for constructors.
678 if (isa<CXXConstructorDecl>(Val: New) &&
679 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
680 CXXSpecialMemberKind NewSM =
681 cast<CXXMethodDecl>(Val: New)->getSpecialMemberKind(),
682 OldSM =
683 cast<CXXMethodDecl>(Val: Old)->getSpecialMemberKind();
684 if (NewSM != OldSM) {
685 auto It = llvm::find_if(Range: New->parameters(), P: [](const ParmVarDecl *P) {
686 return P->hasDefaultArg();
687 });
688 assert(It != New->param_end());
689 ParmVarDecl *NewParam = *It;
690 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
691 << NewParam->getDefaultArgRange() << NewSM;
692 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
693 }
694 }
695
696 const FunctionDecl *Def;
697 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
698 // template has a constexpr specifier then all its declarations shall
699 // contain the constexpr specifier.
700 if (New->getConstexprKind() != Old->getConstexprKind()) {
701 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
702 << New << static_cast<int>(New->getConstexprKind())
703 << static_cast<int>(Old->getConstexprKind());
704 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
705 Invalid = true;
706 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
707 Old->isDefined(Definition&: Def) &&
708 // If a friend function is inlined but does not have 'inline'
709 // specifier, it is a definition. Do not report attribute conflict
710 // in this case, redefinition will be diagnosed later.
711 (New->isInlineSpecified() ||
712 New->getFriendObjectKind() == Decl::FOK_None)) {
713 // C++11 [dcl.fcn.spec]p4:
714 // If the definition of a function appears in a translation unit before its
715 // first declaration as inline, the program is ill-formed.
716 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
717 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
718 Invalid = true;
719 }
720
721 // C++17 [temp.deduct.guide]p3:
722 // Two deduction guide declarations in the same translation unit
723 // for the same class template shall not have equivalent
724 // parameter-declaration-clauses.
725 if (isa<CXXDeductionGuideDecl>(Val: New) &&
726 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
727 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
728 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
729 }
730
731 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
732 // argument expression, that declaration shall be a definition and shall be
733 // the only declaration of the function or function template in the
734 // translation unit.
735 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
736 functionDeclHasDefaultArgument(FD: Old)) {
737 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
738 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
739 Invalid = true;
740 }
741
742 // C++11 [temp.friend]p4 (DR329):
743 // When a function is defined in a friend function declaration in a class
744 // template, the function is instantiated when the function is odr-used.
745 // The same restrictions on multiple declarations and definitions that
746 // apply to non-template function declarations and definitions also apply
747 // to these implicit definitions.
748 const FunctionDecl *OldDefinition = nullptr;
749 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
750 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
751 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
752
753 return Invalid;
754}
755
756void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
757 DiagCompat(Loc, CompatDiagId: diag_compat::placeholder_var_definition);
758}
759
760NamedDecl *
761Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
762 MultiTemplateParamsArg TemplateParamLists) {
763 assert(D.isDecompositionDeclarator());
764 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
765
766 // The syntax only allows a decomposition declarator as a simple-declaration,
767 // a for-range-declaration, or a condition in Clang, but we parse it in more
768 // cases than that.
769 if (!D.mayHaveDecompositionDeclarator()) {
770 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
771 << Decomp.getSourceRange();
772 return nullptr;
773 }
774
775 if (!TemplateParamLists.empty()) {
776 // C++17 [temp]/1:
777 // A template defines a family of class, functions, or variables, or an
778 // alias for a family of types.
779 //
780 // Structured bindings are not included.
781 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
782 DiagID: diag::err_decomp_decl_template);
783 return nullptr;
784 }
785
786 unsigned DiagID;
787 if (!getLangOpts().CPlusPlus17)
788 DiagID = diag::compat_pre_cxx17_decomp_decl;
789 else if (D.getContext() == DeclaratorContext::Condition)
790 DiagID = getLangOpts().CPlusPlus26
791 ? diag::compat_cxx26_decomp_decl_cond
792 : diag::compat_pre_cxx26_decomp_decl_cond;
793 else
794 DiagID = diag::compat_cxx17_decomp_decl;
795
796 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
797
798 // The semantic context is always just the current context.
799 DeclContext *const DC = CurContext;
800
801 // C++17 [dcl.dcl]/8:
802 // The decl-specifier-seq shall contain only the type-specifier auto
803 // and cv-qualifiers.
804 // C++20 [dcl.dcl]/8:
805 // If decl-specifier-seq contains any decl-specifier other than static,
806 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
807 // C++23 [dcl.pre]/6:
808 // Each decl-specifier in the decl-specifier-seq shall be static,
809 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
810 // C++23 [dcl.pre]/7:
811 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
812 // constinit, static, thread_local, auto, or a cv-qualifier
813 auto &DS = D.getDeclSpec();
814 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
815 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
816 };
817
818 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
819 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
820 };
821
822 if (auto SCS = DS.getStorageClassSpec()) {
823 if (SCS == DeclSpec::SCS_static)
824 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
825 DS.getStorageClassSpecLoc());
826 else
827 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
828 DS.getStorageClassSpecLoc());
829 }
830 if (auto TSCS = DS.getThreadStorageClassSpec())
831 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
832 DS.getThreadStorageClassSpecLoc());
833
834 if (DS.isInlineSpecified())
835 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
836
837 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
838 ConstexprSpec != ConstexprSpecKind::Unspecified) {
839 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
840 !getLangOpts().CPlusPlus26)
841 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
842 DS.getConstexprSpecLoc());
843 }
844
845 // We can't recover from it being declared as a typedef.
846 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
847 return nullptr;
848
849 // C++2a [dcl.struct.bind]p1:
850 // A cv that includes volatile is deprecated
851 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
852 getLangOpts().CPlusPlus20)
853 Diag(Loc: DS.getVolatileSpecLoc(),
854 DiagID: diag::warn_deprecated_volatile_structured_binding);
855
856 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
857 QualType R = TInfo->getType();
858
859 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
860 UPPC: UPPC_DeclarationType))
861 D.setInvalidType();
862
863 // The syntax only allows a single ref-qualifier prior to the decomposition
864 // declarator. No other declarator chunks are permitted. Also check the type
865 // specifier here.
866 if (DS.getTypeSpecType() != DeclSpec::TST_auto || D.hasGroupingParens() ||
867 D.getNumTypeObjects() > 1 ||
868 (D.getNumTypeObjects() == 1 &&
869 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
870 Diag(Loc: Decomp.getLSquareLoc(),
871 DiagID: (D.hasGroupingParens() ||
872 (D.getNumTypeObjects() &&
873 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
874 ? diag::err_decomp_decl_parens
875 : diag::err_decomp_decl_type)
876 << R;
877
878 // In most cases, there's no actual problem with an explicitly-specified
879 // type, but a function type won't work here, and ActOnVariableDeclarator
880 // shouldn't be called for such a type.
881 if (R->isFunctionType())
882 D.setInvalidType();
883
884 // Recover from an invalid 'auto *' structured binding by removing the
885 // pointer declarator. This allows type deduction to proceed and keeps
886 // the bindings usable in subsequent code.
887 if (D.getNumTypeObjects() == 1 &&
888 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Pointer &&
889 D.getTypeObject(i: 0).Ptr.TypeQuals == 0) {
890 D.DropFirstTypeObject();
891 TInfo = GetTypeForDeclarator(D);
892 R = TInfo->getType();
893 }
894 }
895
896 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
897 if (DS.isConstrainedAuto()) {
898 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
899 assert(TemplRep->Kind == TNK_Concept_template &&
900 "No other template kind should be possible for a constrained auto");
901
902 SourceRange TemplRange{TemplRep->TemplateNameLoc,
903 TemplRep->RAngleLoc.isValid()
904 ? TemplRep->RAngleLoc
905 : TemplRep->TemplateNameLoc};
906 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
907 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
908 }
909
910 // Build the BindingDecls.
911 SmallVector<BindingDecl*, 8> Bindings;
912
913 // Build the BindingDecls.
914 for (auto &B : D.getDecompositionDeclarator().bindings()) {
915 // Check for name conflicts.
916 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
917 IdentifierInfo *VarName = B.Name;
918 assert(VarName && "Cannot have an unnamed binding declaration");
919
920 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
921 RedeclarationKind::ForVisibleRedeclaration);
922 LookupName(R&: Previous, S,
923 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
924
925 // It's not permitted to shadow a template parameter name.
926 if (Previous.isSingleResult() &&
927 Previous.getFoundDecl()->isTemplateParameter()) {
928 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
929 Previous.clear();
930 }
931
932 QualType QT;
933 if (B.EllipsisLoc.isValid()) {
934 if (!cast<Decl>(Val: DC)->isTemplated())
935 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
936 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
937 /*ExpectsPackInType=*/ExpectPackInType: false);
938 }
939
940 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
941
942 if (BD->isParameterPack()) {
943 if (sema::CapturingScopeInfo *CSI = getEnclosingLambdaOrBlock())
944 CSI->LocalPacks.push_back(Elt: BD);
945 }
946
947 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
948
949 // Find the shadowed declaration before filtering for scope.
950 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
951 ? getShadowedDeclaration(D: BD, R: Previous)
952 : nullptr;
953
954 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
955 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
956 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
957 /*AllowInlineNamespace*/false);
958
959 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
960 DC->isFunctionOrMethod() && VarName->isPlaceholder();
961 if (!Previous.empty()) {
962 if (IsPlaceholder) {
963 bool sameDC = (Previous.end() - 1)
964 ->getDeclContext()
965 ->getRedeclContext()
966 ->Equals(DC: DC->getRedeclContext());
967 if (sameDC &&
968 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
969 Previous.clear();
970 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
971 }
972 } else {
973 auto *Old = Previous.getRepresentativeDecl();
974 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
975 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
976 }
977 } else if (ShadowedDecl && !D.isRedeclaration()) {
978 CheckShadow(D: BD, ShadowedDecl, R: Previous);
979 }
980 PushOnScopeChains(D: BD, S, AddToContext: true);
981 Bindings.push_back(Elt: BD);
982 ParsingInitForAutoVars.insert(Ptr: BD);
983 }
984
985 // There are no prior lookup results for the variable itself, because it
986 // is unnamed.
987 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
988 Decomp.getLSquareLoc());
989 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
990 RedeclarationKind::ForVisibleRedeclaration);
991
992 // Build the variable that holds the non-decomposed object.
993 bool AddToScope = true;
994 NamedDecl *New =
995 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
996 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
997 if (AddToScope) {
998 S->AddDecl(D: New);
999 CurContext->addHiddenDecl(D: New);
1000 }
1001
1002 if (OpenMP().isInOpenMPDeclareTargetContext())
1003 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
1004
1005 return New;
1006}
1007
1008// Check the arity of the structured bindings.
1009// Create the resolved pack expr if needed.
1010static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
1011 QualType DecompType,
1012 ArrayRef<BindingDecl *> Bindings,
1013 unsigned MemberCount) {
1014 auto BindingWithPackItr = llvm::find_if(
1015 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1016 bool HasPack = BindingWithPackItr != Bindings.end();
1017 bool IsValid;
1018 if (!HasPack) {
1019 IsValid = Bindings.size() == MemberCount;
1020 } else {
1021 // There may not be more members than non-pack bindings.
1022 IsValid = MemberCount >= Bindings.size() - 1;
1023 }
1024
1025 if (IsValid && HasPack) {
1026 // Create the pack expr and assign it to the binding.
1027 unsigned PackSize = MemberCount - Bindings.size() + 1;
1028
1029 BindingDecl *BPack = *BindingWithPackItr;
1030 BPack->setDecomposedDecl(DD);
1031 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1032 // Create the nested BindingDecls.
1033 for (unsigned I = 0; I < PackSize; ++I) {
1034 BindingDecl *NestedBD = BindingDecl::Create(
1035 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
1036 Id: BPack->getIdentifier(), T: QualType());
1037 NestedBD->setDecomposedDecl(DD);
1038 NestedBDs[I] = NestedBD;
1039 }
1040
1041 QualType PackType = S.Context.getPackExpansionType(
1042 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
1043 auto *PackExpr = FunctionParmPackExpr::Create(
1044 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
1045 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
1046 }
1047
1048 if (IsValid)
1049 return false;
1050
1051 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
1052 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1053 << (MemberCount < Bindings.size());
1054 return true;
1055}
1056
1057static bool checkSimpleDecomposition(
1058 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1059 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1060 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1061 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1062 auto *DD = cast<DecompositionDecl>(Val: Src);
1063
1064 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1065 return true;
1066
1067 unsigned I = 0;
1068 for (auto *B : DD->flat_bindings()) {
1069 SourceLocation Loc = B->getLocation();
1070 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1071 if (E.isInvalid())
1072 return true;
1073 E = GetInit(Loc, E.get(), I++);
1074 if (E.isInvalid())
1075 return true;
1076 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1077 }
1078
1079 return false;
1080}
1081
1082static bool checkArrayLikeDecomposition(Sema &S,
1083 ArrayRef<BindingDecl *> Bindings,
1084 ValueDecl *Src, QualType DecompType,
1085 const llvm::APSInt &NumElems,
1086 QualType ElemType) {
1087 return checkSimpleDecomposition(
1088 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1089 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1090 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1091 if (E.isInvalid())
1092 return ExprError();
1093 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1094 });
1095}
1096
1097static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1098 ValueDecl *Src, QualType DecompType,
1099 const ConstantArrayType *CAT) {
1100 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1101 NumElems: llvm::APSInt(CAT->getSize()),
1102 ElemType: CAT->getElementType());
1103}
1104
1105static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1106 ValueDecl *Src, QualType DecompType,
1107 const VectorType *VT) {
1108 return checkArrayLikeDecomposition(
1109 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1110 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1111 Qs: DecompType.getQualifiers()));
1112}
1113
1114static bool checkComplexDecomposition(Sema &S,
1115 ArrayRef<BindingDecl *> Bindings,
1116 ValueDecl *Src, QualType DecompType,
1117 const ComplexType *CT) {
1118 return checkSimpleDecomposition(
1119 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1120 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1121 Qs: DecompType.getQualifiers()),
1122 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1123 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1124 });
1125}
1126
1127static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1128 TemplateArgumentListInfo &Args,
1129 const TemplateParameterList *Params) {
1130 SmallString<128> SS;
1131 llvm::raw_svector_ostream OS(SS);
1132 bool First = true;
1133 unsigned I = 0;
1134 for (auto &Arg : Args.arguments()) {
1135 if (!First)
1136 OS << ", ";
1137 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1138 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1139 Policy: PrintingPolicy, TPL: Params, Idx: I));
1140 First = false;
1141 I++;
1142 }
1143 return std::string(OS.str());
1144}
1145
1146static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1147 TemplateArgumentListInfo &Args, unsigned DiagID) {
1148 auto DiagnoseMissing = [&] {
1149 if (DiagID)
1150 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1151 Args, /*Params*/ nullptr);
1152 return QualType();
1153 };
1154
1155 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1156 NamespaceDecl *Std = S.getStdNamespace();
1157 if (!Std)
1158 return DiagnoseMissing();
1159
1160 // Look up the trait itself, within namespace std. We can diagnose various
1161 // problems with this lookup even if we've been asked to not diagnose a
1162 // missing specialization, because this can only fail if the user has been
1163 // declaring their own names in namespace std or we don't support the
1164 // standard library implementation in use.
1165 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1166 Sema::LookupOrdinaryName);
1167 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1168 return DiagnoseMissing();
1169 if (Result.isAmbiguous())
1170 return QualType();
1171
1172 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1173 if (!TraitTD) {
1174 Result.suppressDiagnostics();
1175 NamedDecl *Found = *Result.begin();
1176 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1177 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1178 return QualType();
1179 }
1180
1181 // Build the template-id.
1182 QualType TraitTy = S.CheckTemplateIdType(
1183 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1184 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1185 if (TraitTy.isNull())
1186 return QualType();
1187
1188 if (!S.isCompleteType(Loc, T: TraitTy)) {
1189 if (DiagID)
1190 S.RequireCompleteType(
1191 Loc, T: TraitTy, DiagID,
1192 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1193 Params: TraitTD->getTemplateParameters()));
1194 return QualType();
1195 }
1196 return TraitTy;
1197}
1198
1199static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1200 LookupResult &MemberLookup) {
1201 assert(RD && "specialization of class template is not a class?");
1202 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1203 return MemberLookup.isAmbiguous();
1204}
1205
1206static TemplateArgumentLoc
1207getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1208 uint64_t I) {
1209 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1210 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1211}
1212
1213static TemplateArgumentLoc
1214getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1215 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1216}
1217
1218namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1219
1220static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1221 unsigned &OutSize) {
1222 EnterExpressionEvaluationContext ContextRAII(
1223 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1224
1225 // Form template argument list for tuple_size<T>.
1226 TemplateArgumentListInfo Args(Loc, Loc);
1227 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1228
1229 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1230 if (TraitTy.isNull())
1231 return IsTupleLike::NotTupleLike;
1232
1233 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1234 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1235
1236 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1237 // it's not tuple-like.
1238 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1239 return IsTupleLike::NotTupleLike;
1240
1241 // If we get this far, we've committed to the tuple interpretation, but
1242 // we can still fail if there actually isn't a usable ::value.
1243
1244 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1245 LookupResult &R;
1246 TemplateArgumentListInfo &Args;
1247 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1248 : R(R), Args(Args) {}
1249 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1250 SourceLocation Loc) override {
1251 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1252 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1253 /*Params*/ nullptr);
1254 }
1255 } Diagnoser(R, Args);
1256
1257 ExprResult E =
1258 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1259 if (E.isInvalid())
1260 return IsTupleLike::Error;
1261
1262 llvm::APSInt Size;
1263 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1264 if (E.isInvalid())
1265 return IsTupleLike::Error;
1266
1267 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1268 // an UnsignedOrNone.
1269 if (Size < 0 || Size >= UINT_MAX) {
1270 llvm::SmallVector<char, 16> Str;
1271 Size.toString(Str);
1272 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1273 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1274 /*Params=*/nullptr)
1275 << StringRef(Str.data(), Str.size());
1276 return IsTupleLike::Error;
1277 }
1278
1279 OutSize = Size.getExtValue();
1280 return IsTupleLike::TupleLike;
1281}
1282
1283/// \return std::tuple_element<I, T>::type.
1284static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1285 unsigned I, QualType T) {
1286 // Form template argument list for tuple_element<I, T>.
1287 TemplateArgumentListInfo Args(Loc, Loc);
1288 Args.addArgument(
1289 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1290 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1291
1292 QualType TraitTy =
1293 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1294 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1295 if (TraitTy.isNull())
1296 return QualType();
1297
1298 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1299 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1300 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1301 return QualType();
1302
1303 auto *TD = R.getAsSingle<TypeDecl>();
1304 if (!TD) {
1305 R.suppressDiagnostics();
1306 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1307 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1308 /*Params*/ nullptr);
1309 if (!R.empty())
1310 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1311 return QualType();
1312 }
1313
1314 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1315 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1316}
1317
1318namespace {
1319struct InitializingBinding {
1320 Sema &S;
1321 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1322 Sema::CodeSynthesisContext Ctx;
1323 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1324 Ctx.PointOfInstantiation = BD->getLocation();
1325 Ctx.Entity = BD;
1326 S.pushCodeSynthesisContext(Ctx);
1327 }
1328 ~InitializingBinding() {
1329 S.popCodeSynthesisContext();
1330 }
1331};
1332}
1333
1334static bool checkTupleLikeDecomposition(Sema &S,
1335 ArrayRef<BindingDecl *> Bindings,
1336 VarDecl *Src, QualType DecompType,
1337 unsigned NumElems) {
1338 auto *DD = cast<DecompositionDecl>(Val: Src);
1339 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1340 return true;
1341
1342 if (Bindings.empty())
1343 return false;
1344
1345 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1346
1347 // [dcl.decomp]p3:
1348 // The unqualified-id get is looked up in the scope of E by class member
1349 // access lookup ...
1350 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1351 bool UseMemberGet = false;
1352 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1353 if (auto *RD = DecompType->getAsCXXRecordDecl())
1354 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1355 if (MemberGet.isAmbiguous())
1356 return true;
1357 // ... and if that finds at least one declaration that is a function
1358 // template whose first template parameter is a non-type parameter ...
1359 for (NamedDecl *D : MemberGet) {
1360 if (FunctionTemplateDecl *FTD =
1361 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1362 TemplateParameterList *TPL = FTD->getTemplateParameters();
1363 if (TPL->size() != 0 &&
1364 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1365 // ... the initializer is e.get<i>().
1366 UseMemberGet = true;
1367 break;
1368 }
1369 }
1370 }
1371 }
1372
1373 unsigned I = 0;
1374 for (auto *B : DD->flat_bindings()) {
1375 InitializingBinding InitContext(S, B);
1376 SourceLocation Loc = B->getLocation();
1377
1378 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1379 if (E.isInvalid())
1380 return true;
1381
1382 // e is an lvalue if the type of the entity is an lvalue reference and
1383 // an xvalue otherwise
1384 if (!Src->getType()->isLValueReferenceType())
1385 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1386 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1387 FPO: FPOptionsOverride());
1388
1389 TemplateArgumentListInfo Args(Loc, Loc);
1390 Args.addArgument(
1391 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1392
1393 if (UseMemberGet) {
1394 // if [lookup of member get] finds at least one declaration, the
1395 // initializer is e.get<i-1>().
1396 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1397 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1398 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1399 if (E.isInvalid())
1400 return true;
1401
1402 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1403 } else {
1404 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1405 // in the associated namespaces.
1406 Expr *Get = UnresolvedLookupExpr::Create(
1407 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1408 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1409 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1410 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1411
1412 Expr *Arg = E.get();
1413 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1414 }
1415 if (E.isInvalid())
1416 return true;
1417 Expr *Init = E.get();
1418
1419 // Given the type T designated by std::tuple_element<i - 1, E>::type
1420 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1421 if (T.isNull())
1422 return true;
1423
1424 // C++26 [dcl.struct.bind]p7:
1425 // and the type Ui, defined as Ti if the initializer is a prvalue,
1426 // as "lvalue reference to Ti" if the initializer is an lvalue,
1427 // or as "rvalue reference to Ti" otherwise
1428 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1429 QualType U = E.get()->isPRValue()
1430 ? T
1431 : S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc,
1432 Entity: B->getDeclName());
1433 if (U.isNull())
1434 return true;
1435
1436 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1437 // entity and this type was never written in source code.
1438 auto *BindingVD =
1439 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1440 Id: B->getDeclName().getAsIdentifierInfo(), T: U,
1441 /*TInfo=*/nullptr, S: Src->getStorageClass());
1442 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1443 BindingVD->setTSCSpec(Src->getTSCSpec());
1444 BindingVD->setConstexpr(Src->isConstexpr());
1445 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1446 BindingVD->addAttr(A: CIAttr->clone(C&: S.Context));
1447 BindingVD->setImplicit();
1448 if (Src->isInlineSpecified())
1449 BindingVD->setInlineSpecified();
1450 BindingVD->getLexicalDeclContext()->addHiddenDecl(D: BindingVD);
1451
1452 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: BindingVD);
1453 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1454 InitializationSequence Seq(S, Entity, Kind, Init);
1455 E = Seq.Perform(S, Entity, Kind, Args: Init);
1456 if (E.isInvalid())
1457 return true;
1458 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1459 if (E.isInvalid())
1460 return true;
1461 BindingVD->setInit(E.get());
1462 S.CheckCompleteVariableDeclaration(VD: BindingVD);
1463
1464 E = S.BuildDeclarationNameExpr(
1465 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(B->getDeclName(), Loc), D: BindingVD);
1466 if (E.isInvalid())
1467 return true;
1468
1469 B->setBinding(DeclaredType: T, Binding: E.get());
1470 I++;
1471 }
1472
1473 return false;
1474}
1475
1476/// Find the base class to decompose in a built-in decomposition of a class type.
1477/// This base class search is, unfortunately, not quite like any other that we
1478/// perform anywhere else in C++.
1479static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1480 const CXXRecordDecl *RD,
1481 CXXCastPath &BasePath) {
1482 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1483 CXXBasePath &Path) {
1484 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1485 };
1486
1487 const CXXRecordDecl *ClassWithFields = nullptr;
1488 AccessSpecifier AS = AS_public;
1489 if (RD->hasDirectFields())
1490 // [dcl.decomp]p4:
1491 // Otherwise, all of E's non-static data members shall be public direct
1492 // members of E ...
1493 ClassWithFields = RD;
1494 else {
1495 // ... or of ...
1496 CXXBasePaths Paths;
1497 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1498 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1499 // If no classes have fields, just decompose RD itself. (This will work
1500 // if and only if zero bindings were provided.)
1501 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1502 }
1503
1504 CXXBasePath *BestPath = nullptr;
1505 for (auto &P : Paths) {
1506 if (!BestPath)
1507 BestPath = &P;
1508 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1509 T2: BestPath->back().Base->getType())) {
1510 // ... the same ...
1511 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1512 << false << RD << BestPath->back().Base->getType()
1513 << P.back().Base->getType();
1514 return DeclAccessPair();
1515 } else if (P.Access < BestPath->Access) {
1516 BestPath = &P;
1517 }
1518 }
1519
1520 // ... unambiguous ...
1521 QualType BaseType = BestPath->back().Base->getType();
1522 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1523 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1524 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1525 return DeclAccessPair();
1526 }
1527
1528 // ... [accessible, implied by other rules] base class of E.
1529 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1530 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1531 AS = BestPath->Access;
1532
1533 ClassWithFields = BaseType->getAsCXXRecordDecl();
1534 S.BuildBasePathArray(Paths, BasePath);
1535 }
1536
1537 // The above search did not check whether the selected class itself has base
1538 // classes with fields, so check that now.
1539 CXXBasePaths Paths;
1540 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1541 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1542 << (ClassWithFields == RD) << RD << ClassWithFields
1543 << Paths.front().back().Base->getType();
1544 return DeclAccessPair();
1545 }
1546
1547 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1548}
1549
1550static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1551 const CXXRecordDecl *OrigRD,
1552 QualType DecompType,
1553 DeclAccessPair BasePair) {
1554 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1555 if (!RD)
1556 return true;
1557
1558 for (auto *FD : RD->fields()) {
1559 if (FD->isUnnamedBitField())
1560 continue;
1561
1562 // All the non-static data members are required to be nameable, so they
1563 // must all have names.
1564 if (!FD->getDeclName()) {
1565 if (RD->isLambda()) {
1566 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1567 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1568 return true;
1569 }
1570
1571 if (FD->isAnonymousStructOrUnion()) {
1572 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1573 << DecompType << FD->getType()->isUnionType();
1574 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1575 return true;
1576 }
1577
1578 // FIXME: Are there any other ways we could have an anonymous member?
1579 }
1580 // The field must be accessible in the context of the structured binding.
1581 // We already checked that the base class is accessible.
1582 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1583 // const_cast here.
1584 S.CheckStructuredBindingMemberAccess(
1585 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1586 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1587 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1588 }
1589 return false;
1590}
1591
1592static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1593 ValueDecl *Src, QualType DecompType,
1594 const CXXRecordDecl *OrigRD) {
1595 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1596 DiagID: diag::err_incomplete_type))
1597 return true;
1598
1599 CXXCastPath BasePath;
1600 DeclAccessPair BasePair =
1601 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1602 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1603 if (!RD)
1604 return true;
1605 QualType BaseType = S.Context.getQualifiedType(
1606 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1607
1608 auto *DD = cast<DecompositionDecl>(Val: Src);
1609 unsigned NumFields = llvm::count_if(
1610 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1611 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1612 return true;
1613
1614 // all of E's non-static data members shall be [...] well-formed
1615 // when named as e.name in the context of the structured binding,
1616 // E shall not have an anonymous union member, ...
1617 auto FlatBindings = DD->flat_bindings();
1618 assert(llvm::range_size(FlatBindings) == NumFields);
1619 auto FlatBindingsItr = FlatBindings.begin();
1620
1621 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1622 BasePair))
1623 return true;
1624
1625 for (auto *FD : RD->fields()) {
1626 if (FD->isUnnamedBitField())
1627 continue;
1628
1629 // We have a real field to bind.
1630 assert(FlatBindingsItr != FlatBindings.end());
1631 BindingDecl *B = *(FlatBindingsItr++);
1632 SourceLocation Loc = B->getLocation();
1633
1634 // Initialize the binding to Src.FD.
1635 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1636 if (E.isInvalid())
1637 return true;
1638 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1639 VK: VK_LValue, BasePath: &BasePath);
1640 if (E.isInvalid())
1641 return true;
1642 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1643 SS: CXXScopeSpec(), Field: FD,
1644 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1645 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1646 if (E.isInvalid())
1647 return true;
1648
1649 // If the type of the member is T, the referenced type is cv T, where cv is
1650 // the cv-qualification of the decomposition expression.
1651 //
1652 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1653 // 'const' to the type of the field.
1654 Qualifiers Q = DecompType.getQualifiers();
1655 if (FD->isMutable())
1656 Q.removeConst();
1657 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1658 }
1659
1660 return false;
1661}
1662
1663void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1664 QualType DecompType = DD->getType();
1665
1666 // If the type of the decomposition is dependent, then so is the type of
1667 // each binding.
1668 if (DecompType->isDependentType()) {
1669 // Note that all of the types are still Null or PackExpansionType.
1670 for (auto *B : DD->bindings()) {
1671 // Do not overwrite any pack type.
1672 if (B->getType().isNull())
1673 B->setType(Context.DependentTy);
1674 }
1675 return;
1676 }
1677
1678 DecompType = DecompType.getNonReferenceType();
1679 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1680
1681 // C++1z [dcl.decomp]/2:
1682 // If E is an array type [...]
1683 // As an extension, we also support decomposition of built-in complex and
1684 // vector types.
1685 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1686 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1687 DD->setInvalidDecl();
1688 return;
1689 }
1690 if (auto *VT = DecompType->getAs<VectorType>()) {
1691 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1692 DD->setInvalidDecl();
1693 return;
1694 }
1695 if (auto *CT = DecompType->getAs<ComplexType>()) {
1696 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1697 DD->setInvalidDecl();
1698 return;
1699 }
1700
1701 // C++1z [dcl.decomp]/3:
1702 // if the expression std::tuple_size<E>::value is a well-formed integral
1703 // constant expression, [...]
1704 unsigned TupleSize;
1705 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1706 case IsTupleLike::Error:
1707 DD->setInvalidDecl();
1708 return;
1709
1710 case IsTupleLike::TupleLike:
1711 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1712 DD->setInvalidDecl();
1713 return;
1714
1715 case IsTupleLike::NotTupleLike:
1716 break;
1717 }
1718
1719 // C++1z [dcl.dcl]/8:
1720 // [E shall be of array or non-union class type]
1721 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1722 if (!RD || RD->isUnion()) {
1723 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1724 << DD << !RD << DecompType;
1725 DD->setInvalidDecl();
1726 return;
1727 }
1728
1729 // C++1z [dcl.decomp]/4:
1730 // all of E's non-static data members shall be [...] direct members of
1731 // E or of the same unambiguous public base class of E, ...
1732 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1733 DD->setInvalidDecl();
1734}
1735
1736UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1737 SourceLocation Loc) {
1738 const ASTContext &Ctx = getASTContext();
1739 assert(!T->isDependentType());
1740
1741 Qualifiers Quals;
1742 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1743 Quals.removeCVRQualifiers();
1744 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1745
1746 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1747 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1748 if (auto *VT = T->getAs<VectorType>())
1749 return VT->getNumElements();
1750 if (T->getAs<ComplexType>())
1751 return 2u;
1752
1753 unsigned TupleSize;
1754 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1755 case IsTupleLike::Error:
1756 return std::nullopt;
1757 case IsTupleLike::TupleLike:
1758 return TupleSize;
1759 case IsTupleLike::NotTupleLike:
1760 break;
1761 }
1762
1763 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1764 if (!OrigRD || OrigRD->isUnion())
1765 return std::nullopt;
1766
1767 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1768 return std::nullopt;
1769
1770 CXXCastPath BasePath;
1771 DeclAccessPair BasePair =
1772 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1773 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1774 if (!RD)
1775 return std::nullopt;
1776
1777 unsigned NumFields = llvm::count_if(
1778 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1779
1780 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1781 return std::nullopt;
1782
1783 return NumFields;
1784}
1785
1786void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1787 // Shortcut if exceptions are disabled.
1788 if (!getLangOpts().CXXExceptions)
1789 return;
1790
1791 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1792 "Should only be called if types are otherwise the same.");
1793
1794 QualType NewType = New->getType();
1795 QualType OldType = Old->getType();
1796
1797 // We're only interested in pointers and references to functions, as well
1798 // as pointers to member functions.
1799 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1800 NewType = R->getPointeeType();
1801 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1802 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1803 NewType = P->getPointeeType();
1804 OldType = OldType->castAs<PointerType>()->getPointeeType();
1805 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1806 NewType = M->getPointeeType();
1807 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1808 }
1809
1810 if (!NewType->isFunctionProtoType())
1811 return;
1812
1813 // There's lots of special cases for functions. For function pointers, system
1814 // libraries are hopefully not as broken so that we don't need these
1815 // workarounds.
1816 if (CheckEquivalentExceptionSpec(
1817 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1818 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1819 New->setInvalidDecl();
1820 }
1821}
1822
1823/// CheckCXXDefaultArguments - Verify that the default arguments for a
1824/// function declaration are well-formed according to C++
1825/// [dcl.fct.default].
1826void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1827 // This checking doesn't make sense for explicit specializations; their
1828 // default arguments are determined by the declaration we're specializing,
1829 // not by FD.
1830 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1831 return;
1832 if (auto *FTD = FD->getDescribedFunctionTemplate())
1833 if (FTD->isMemberSpecialization())
1834 return;
1835
1836 unsigned NumParams = FD->getNumParams();
1837 unsigned ParamIdx = 0;
1838
1839 // Find first parameter with a default argument
1840 for (; ParamIdx < NumParams; ++ParamIdx) {
1841 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1842 if (Param->hasDefaultArg())
1843 break;
1844 }
1845
1846 // C++20 [dcl.fct.default]p4:
1847 // In a given function declaration, each parameter subsequent to a parameter
1848 // with a default argument shall have a default argument supplied in this or
1849 // a previous declaration, unless the parameter was expanded from a
1850 // parameter pack, or shall be a function parameter pack.
1851 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1852 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1853 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1854 (CurrentInstantiationScope &&
1855 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1856 continue;
1857 if (Param->isInvalidDecl())
1858 /* We already complained about this parameter. */;
1859 else if (Param->getIdentifier())
1860 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1861 << Param->getIdentifier();
1862 else
1863 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1864 }
1865}
1866
1867/// Check that the given type is a literal type. Issue a diagnostic if not,
1868/// if Kind is Diagnose.
1869/// \return \c true if a problem has been found (and optionally diagnosed).
1870template <typename... Ts>
1871static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1872 SourceLocation Loc, QualType T, unsigned DiagID,
1873 Ts &&...DiagArgs) {
1874 if (T->isDependentType())
1875 return false;
1876
1877 switch (Kind) {
1878 case Sema::CheckConstexprKind::Diagnose:
1879 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1880 std::forward<Ts>(DiagArgs)...);
1881
1882 case Sema::CheckConstexprKind::CheckValid:
1883 return !T->isLiteralType(Ctx: SemaRef.Context);
1884 }
1885
1886 llvm_unreachable("unknown CheckConstexprKind");
1887}
1888
1889/// Determine whether a destructor cannot be constexpr due to
1890static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1891 const CXXDestructorDecl *DD,
1892 Sema::CheckConstexprKind Kind) {
1893 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1894 "this check is obsolete for C++23");
1895 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1896 const CXXRecordDecl *RD =
1897 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1898 if (!RD || RD->hasConstexprDestructor())
1899 return true;
1900
1901 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1902 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1903 << static_cast<int>(DD->getConstexprKind()) << !FD
1904 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1905 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1906 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1907 }
1908 return false;
1909 };
1910
1911 const CXXRecordDecl *RD = DD->getParent();
1912 for (const CXXBaseSpecifier &B : RD->bases())
1913 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1914 return false;
1915 for (const FieldDecl *FD : RD->fields())
1916 if (!Check(FD->getLocation(), FD->getType(), FD))
1917 return false;
1918 return true;
1919}
1920
1921/// Check whether a function's parameter types are all literal types. If so,
1922/// return true. If not, produce a suitable diagnostic and return false.
1923static bool CheckConstexprParameterTypes(Sema &SemaRef,
1924 const FunctionDecl *FD,
1925 Sema::CheckConstexprKind Kind) {
1926 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1927 "this check is obsolete for C++23");
1928 unsigned ArgIndex = 0;
1929 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1930 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1931 e = FT->param_type_end();
1932 i != e; ++i, ++ArgIndex) {
1933 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1934 assert(PD && "null in a parameter list");
1935 SourceLocation ParamLoc = PD->getLocation();
1936 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1937 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1938 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1939 DiagArgs: FD->isConsteval()))
1940 return false;
1941 }
1942 return true;
1943}
1944
1945/// Check whether a function's return type is a literal type. If so, return
1946/// true. If not, produce a suitable diagnostic and return false.
1947static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1948 Sema::CheckConstexprKind Kind) {
1949 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1950 "this check is obsolete for C++23");
1951 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1952 DiagID: diag::err_constexpr_non_literal_return,
1953 DiagArgs: FD->isConsteval()))
1954 return false;
1955 return true;
1956}
1957
1958/// Get diagnostic %select index for tag kind for
1959/// record diagnostic message.
1960/// WARNING: Indexes apply to particular diagnostics only!
1961///
1962/// \returns diagnostic %select index.
1963static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1964 switch (Tag) {
1965 case TagTypeKind::Struct:
1966 return 0;
1967 case TagTypeKind::Interface:
1968 return 1;
1969 case TagTypeKind::Class:
1970 return 2;
1971 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1972 }
1973}
1974
1975static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1976 Stmt *Body,
1977 Sema::CheckConstexprKind Kind);
1978static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1979
1980bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1981 CheckConstexprKind Kind) {
1982 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1983 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1984 // C++11 [dcl.constexpr]p4:
1985 // The definition of a constexpr constructor shall satisfy the following
1986 // constraints:
1987 // - the class shall not have any virtual base classes;
1988 //
1989 // FIXME: This only applies to constructors and destructors, not arbitrary
1990 // member functions.
1991 const CXXRecordDecl *RD = MD->getParent();
1992 if (RD->getNumVBases()) {
1993 if (Kind == CheckConstexprKind::CheckValid)
1994 return false;
1995
1996 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1997 << isa<CXXConstructorDecl>(Val: NewFD)
1998 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1999 for (const auto &I : RD->vbases())
2000 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
2001 << I.getSourceRange();
2002 return false;
2003 }
2004 }
2005
2006 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
2007 // C++11 [dcl.constexpr]p3:
2008 // The definition of a constexpr function shall satisfy the following
2009 // constraints:
2010 // - it shall not be virtual; (removed in C++20)
2011 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
2012 if (Method && Method->isVirtual()) {
2013 if (getLangOpts().CPlusPlus20) {
2014 if (Kind == CheckConstexprKind::Diagnose)
2015 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
2016 } else {
2017 if (Kind == CheckConstexprKind::CheckValid)
2018 return false;
2019
2020 Method = Method->getCanonicalDecl();
2021 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
2022
2023 // If it's not obvious why this function is virtual, find an overridden
2024 // function which uses the 'virtual' keyword.
2025 const CXXMethodDecl *WrittenVirtual = Method;
2026 while (!WrittenVirtual->isVirtualAsWritten())
2027 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2028 if (WrittenVirtual != Method)
2029 Diag(Loc: WrittenVirtual->getLocation(),
2030 DiagID: diag::note_overridden_virtual_function);
2031 return false;
2032 }
2033 }
2034
2035 // - its return type shall be a literal type; (removed in C++23)
2036 if (!getLangOpts().CPlusPlus23 &&
2037 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
2038 return false;
2039 }
2040
2041 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
2042 // A destructor can be constexpr only if the defaulted destructor could be;
2043 // we don't need to check the members and bases if we already know they all
2044 // have constexpr destructors. (removed in C++23)
2045 if (!getLangOpts().CPlusPlus23 &&
2046 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2047 if (Kind == CheckConstexprKind::CheckValid)
2048 return false;
2049 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
2050 return false;
2051 }
2052 }
2053
2054 // - each of its parameter types shall be a literal type; (removed in C++23)
2055 if (!getLangOpts().CPlusPlus23 &&
2056 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
2057 return false;
2058
2059 Stmt *Body = NewFD->getBody();
2060 assert(Body &&
2061 "CheckConstexprFunctionDefinition called on function with no body");
2062 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2063}
2064
2065/// Check the given declaration statement is legal within a constexpr function
2066/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2067///
2068/// \return true if the body is OK (maybe only as an extension), false if we
2069/// have diagnosed a problem.
2070static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2071 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2072 Sema::CheckConstexprKind Kind) {
2073 // C++11 [dcl.constexpr]p3 and p4:
2074 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2075 // contain only
2076 for (const auto *DclIt : DS->decls()) {
2077 switch (DclIt->getKind()) {
2078 case Decl::StaticAssert:
2079 case Decl::Using:
2080 case Decl::UsingShadow:
2081 case Decl::UsingDirective:
2082 case Decl::UnresolvedUsingTypename:
2083 case Decl::UnresolvedUsingValue:
2084 case Decl::UsingEnum:
2085 // - static_assert-declarations
2086 // - using-declarations,
2087 // - using-directives,
2088 // - using-enum-declaration
2089 continue;
2090
2091 case Decl::Typedef:
2092 case Decl::TypeAlias: {
2093 // - typedef declarations and alias-declarations that do not define
2094 // classes or enumerations,
2095 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2096 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2097 // Don't allow variably-modified types in constexpr functions.
2098 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2099 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2100 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2101 << TL.getSourceRange() << TL.getType()
2102 << isa<CXXConstructorDecl>(Val: Dcl);
2103 }
2104 return false;
2105 }
2106 continue;
2107 }
2108
2109 case Decl::Enum:
2110 case Decl::CXXRecord:
2111 // C++1y allows types to be defined, not just declared.
2112 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2113 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2114 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2115 CompatDiagId: diag_compat::constexpr_type_definition)
2116 << isa<CXXConstructorDecl>(Val: Dcl);
2117 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2118 return false;
2119 }
2120 }
2121 continue;
2122
2123 case Decl::EnumConstant:
2124 case Decl::IndirectField:
2125 case Decl::ParmVar:
2126 // These can only appear with other declarations which are banned in
2127 // C++11 and permitted in C++1y, so ignore them.
2128 continue;
2129
2130 case Decl::Var:
2131 case Decl::Decomposition: {
2132 // C++1y [dcl.constexpr]p3 allows anything except:
2133 // a definition of a variable of non-literal type or of static or
2134 // thread storage duration or [before C++2a] for which no
2135 // initialization is performed.
2136 const auto *VD = cast<VarDecl>(Val: DclIt);
2137 if (VD->isThisDeclarationADefinition()) {
2138 if (VD->isStaticLocal()) {
2139 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2140 SemaRef.DiagCompat(Loc: VD->getLocation(),
2141 CompatDiagId: diag_compat::constexpr_static_var)
2142 << isa<CXXConstructorDecl>(Val: Dcl)
2143 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2144 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2145 return false;
2146 }
2147 }
2148 if (SemaRef.LangOpts.CPlusPlus23) {
2149 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2150 DiagID: diag::warn_cxx20_compat_constexpr_var,
2151 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2152 } else if (CheckLiteralType(
2153 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2154 DiagID: diag::err_constexpr_local_var_non_literal_type,
2155 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2156 return false;
2157 }
2158 if (!VD->getType()->isDependentType() &&
2159 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2160 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2161 SemaRef.DiagCompat(Loc: VD->getLocation(),
2162 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2163 << isa<CXXConstructorDecl>(Val: Dcl);
2164 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2165 return false;
2166 }
2167 continue;
2168 }
2169 }
2170 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2171 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2172 << isa<CXXConstructorDecl>(Val: Dcl);
2173 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2174 return false;
2175 }
2176 continue;
2177 }
2178
2179 case Decl::NamespaceAlias:
2180 case Decl::Function:
2181 // These are disallowed in C++11 and permitted in C++1y. Allow them
2182 // everywhere as an extension.
2183 if (!Cxx1yLoc.isValid())
2184 Cxx1yLoc = DS->getBeginLoc();
2185 continue;
2186
2187 default:
2188 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2189 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2190 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2191 }
2192 return false;
2193 }
2194 }
2195
2196 return true;
2197}
2198
2199/// Check that the given field is initialized within a constexpr constructor.
2200///
2201/// \param Dcl The constexpr constructor being checked.
2202/// \param Field The field being checked. This may be a member of an anonymous
2203/// struct or union nested within the class being checked.
2204/// \param Inits All declarations, including anonymous struct/union members and
2205/// indirect members, for which any initialization was provided.
2206/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2207/// multiple notes for different members to the same error.
2208/// \param Kind Whether we're diagnosing a constructor as written or determining
2209/// whether the formal requirements are satisfied.
2210/// \return \c false if we're checking for validity and the constructor does
2211/// not satisfy the requirements on a constexpr constructor.
2212static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2213 const FunctionDecl *Dcl,
2214 FieldDecl *Field,
2215 llvm::SmallPtrSet<Decl *, 16> &Inits,
2216 bool &Diagnosed,
2217 Sema::CheckConstexprKind Kind) {
2218 // In C++20 onwards, there's nothing to check for validity.
2219 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2220 SemaRef.getLangOpts().CPlusPlus20)
2221 return true;
2222
2223 if (Field->isInvalidDecl())
2224 return true;
2225
2226 if (Field->isUnnamedBitField())
2227 return true;
2228
2229 // Anonymous unions with no variant members and empty anonymous structs do not
2230 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2231 // indirect fields don't need initializing.
2232 if (Field->isAnonymousStructOrUnion() &&
2233 (Field->getType()->isUnionType()
2234 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2235 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2236 return true;
2237
2238 if (!Inits.count(Ptr: Field)) {
2239 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2240 if (!Diagnosed) {
2241 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2242 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2243 Diagnosed = true;
2244 }
2245 SemaRef.Diag(Loc: Field->getLocation(),
2246 DiagID: diag::note_constexpr_ctor_missing_init);
2247 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2248 return false;
2249 }
2250 } else if (Field->isAnonymousStructOrUnion()) {
2251 const auto *RD = Field->getType()->castAsRecordDecl();
2252 for (auto *I : RD->fields())
2253 // If an anonymous union contains an anonymous struct of which any member
2254 // is initialized, all members must be initialized.
2255 if (!RD->isUnion() || Inits.count(Ptr: I))
2256 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2257 Kind))
2258 return false;
2259 }
2260 return true;
2261}
2262
2263/// Check the provided statement is allowed in a constexpr function
2264/// definition.
2265static bool
2266CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2267 SmallVectorImpl<SourceLocation> &ReturnStmts,
2268 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2269 SourceLocation &Cxx2bLoc,
2270 Sema::CheckConstexprKind Kind) {
2271 auto CheckChildren = [&] {
2272 for (Stmt *SubStmt : S->children()) {
2273 if (SubStmt &&
2274 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2275 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2276 return false;
2277 }
2278 return true;
2279 };
2280
2281 // - its function-body shall be [...] a compound-statement that contains only
2282 switch (S->getStmtClass()) {
2283 case Stmt::NullStmtClass:
2284 // - null statements,
2285 return true;
2286
2287 case Stmt::DeclStmtClass: {
2288 auto *DS = cast<DeclStmt>(Val: S);
2289
2290 // Expansion statement 'declarations' have substatements, so we need to
2291 // handle them separately.
2292 if (DS->isSingleDecl()) {
2293 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(Val: DS->getSingleDecl())) {
2294 // Don't check unexpanded expansion statements.
2295 if (!ESD->getInstantiations())
2296 return true;
2297 for (auto *BodyIt : ESD->getInstantiations()->getInstantiations()) {
2298 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2299 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2300 return false;
2301 }
2302 return true;
2303 }
2304 }
2305
2306 // - static_assert-declarations
2307 // - using-declarations,
2308 // - using-directives,
2309 // - typedef declarations and alias-declarations that do not define
2310 // classes or enumerations,
2311 return CheckConstexprDeclStmt(SemaRef, Dcl, DS, Cxx1yLoc, Kind);
2312 }
2313
2314 case Stmt::ReturnStmtClass:
2315 // - and exactly one return statement;
2316 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2317 // C++1y allows return statements in constexpr constructors.
2318 if (!Cxx1yLoc.isValid())
2319 Cxx1yLoc = S->getBeginLoc();
2320 return true;
2321 }
2322
2323 ReturnStmts.push_back(Elt: S->getBeginLoc());
2324 return true;
2325
2326 case Stmt::AttributedStmtClass:
2327 // Attributes on a statement don't affect its formal kind and hence don't
2328 // affect its validity in a constexpr function.
2329 return CheckConstexprFunctionStmt(
2330 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2332
2333 case Stmt::CompoundStmtClass:
2334 // C++1y allows compound-statements.
2335 if (!Cxx1yLoc.isValid())
2336 Cxx1yLoc = S->getBeginLoc();
2337 return CheckChildren();
2338
2339 case Stmt::IfStmtClass: {
2340 // C++1y allows if-statements.
2341 if (!Cxx1yLoc.isValid())
2342 Cxx1yLoc = S->getBeginLoc();
2343
2344 IfStmt *If = cast<IfStmt>(Val: S);
2345 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2346 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2347 return false;
2348 if (If->getElse() &&
2349 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2350 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2351 return false;
2352 return true;
2353 }
2354
2355 case Stmt::WhileStmtClass:
2356 case Stmt::DoStmtClass:
2357 case Stmt::ForStmtClass:
2358 case Stmt::CXXForRangeStmtClass:
2359 case Stmt::ContinueStmtClass:
2360 // C++1y allows all of these. We don't allow them as extensions in C++11,
2361 // because they don't make sense without variable mutation.
2362 if (!SemaRef.getLangOpts().CPlusPlus14)
2363 break;
2364 [[fallthrough]];
2365
2366 case Stmt::SwitchStmtClass:
2367 case Stmt::CaseStmtClass:
2368 case Stmt::DefaultStmtClass:
2369 case Stmt::BreakStmtClass:
2370 // C++1y allows switch-statements, and since they don't need variable
2371 // mutation, we can reasonably allow them in C++11 as an extension.
2372 if (!Cxx1yLoc.isValid())
2373 Cxx1yLoc = S->getBeginLoc();
2374 return CheckChildren();
2375
2376 case Stmt::LabelStmtClass:
2377 case Stmt::GotoStmtClass:
2378 case Stmt::IndirectGotoStmtClass:
2379 if (Cxx2bLoc.isInvalid())
2380 Cxx2bLoc = S->getBeginLoc();
2381 return CheckChildren();
2382
2383 case Stmt::GCCAsmStmtClass:
2384 case Stmt::MSAsmStmtClass:
2385 // C++2a allows inline assembly statements.
2386 case Stmt::CXXTryStmtClass:
2387 if (Cxx2aLoc.isInvalid())
2388 Cxx2aLoc = S->getBeginLoc();
2389 return CheckChildren();
2390
2391 case Stmt::CXXCatchStmtClass:
2392 // Do not bother checking the language mode (already covered by the
2393 // try block check).
2394 return CheckConstexprFunctionStmt(
2395 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2396 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2397
2398 default:
2399 if (!isa<Expr>(Val: S))
2400 break;
2401
2402 // C++1y allows expression-statements.
2403 if (!Cxx1yLoc.isValid())
2404 Cxx1yLoc = S->getBeginLoc();
2405 return true;
2406 }
2407
2408 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2409 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2410 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2411 }
2412 return false;
2413}
2414
2415/// Check the body for the given constexpr function declaration only contains
2416/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2417///
2418/// \return true if the body is OK, false if we have found or diagnosed a
2419/// problem.
2420static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2421 Stmt *Body,
2422 Sema::CheckConstexprKind Kind) {
2423 SmallVector<SourceLocation, 4> ReturnStmts;
2424
2425 if (isa<CXXTryStmt>(Val: Body)) {
2426 // C++11 [dcl.constexpr]p3:
2427 // The definition of a constexpr function shall satisfy the following
2428 // constraints: [...]
2429 // - its function-body shall be = delete, = default, or a
2430 // compound-statement
2431 //
2432 // C++11 [dcl.constexpr]p4:
2433 // In the definition of a constexpr constructor, [...]
2434 // - its function-body shall not be a function-try-block;
2435 //
2436 // This restriction is lifted in C++2a, as long as inner statements also
2437 // apply the general constexpr rules.
2438 switch (Kind) {
2439 case Sema::CheckConstexprKind::CheckValid:
2440 if (!SemaRef.getLangOpts().CPlusPlus20)
2441 return false;
2442 break;
2443
2444 case Sema::CheckConstexprKind::Diagnose:
2445 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2446 CompatDiagId: diag_compat::constexpr_function_try_block)
2447 << isa<CXXConstructorDecl>(Val: Dcl);
2448 break;
2449 }
2450 }
2451
2452 // - its function-body shall be [...] a compound-statement that contains only
2453 // [... list of cases ...]
2454 //
2455 // Note that walking the children here is enough to properly check for
2456 // CompoundStmt and CXXTryStmt body.
2457 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2458 for (Stmt *SubStmt : Body->children()) {
2459 if (SubStmt &&
2460 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2461 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2462 return false;
2463 }
2464
2465 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2466 // If this is only valid as an extension, report that we don't satisfy the
2467 // constraints of the current language.
2468 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2469 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2470 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2471 return false;
2472 } else if (Cxx2bLoc.isValid()) {
2473 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2474 << isa<CXXConstructorDecl>(Val: Dcl);
2475 } else if (Cxx2aLoc.isValid()) {
2476 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2477 << isa<CXXConstructorDecl>(Val: Dcl);
2478 } else if (Cxx1yLoc.isValid()) {
2479 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2480 << isa<CXXConstructorDecl>(Val: Dcl);
2481 }
2482
2483 if (const CXXConstructorDecl *Constructor
2484 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2485 const CXXRecordDecl *RD = Constructor->getParent();
2486 // DR1359:
2487 // - every non-variant non-static data member and base class sub-object
2488 // shall be initialized;
2489 // DR1460:
2490 // - if the class is a union having variant members, exactly one of them
2491 // shall be initialized;
2492 if (RD->isUnion()) {
2493 if (Constructor->getNumCtorInitializers() == 0 &&
2494 RD->hasVariantMembers()) {
2495 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2496 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2497 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2498 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2499 return false;
2500 }
2501 }
2502 } else if (!Constructor->isDependentContext() &&
2503 !Constructor->isDelegatingConstructor()) {
2504 // Skip detailed checking if we have enough initializers, and we would
2505 // allow at most one initializer per member.
2506 bool AnyAnonStructUnionMembers = false;
2507 unsigned Fields = 0;
2508 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2509 E = RD->field_end(); I != E; ++I, ++Fields) {
2510 if (I->isAnonymousStructOrUnion()) {
2511 AnyAnonStructUnionMembers = true;
2512 break;
2513 }
2514 }
2515 // DR1460:
2516 // - if the class is a union-like class, but is not a union, for each of
2517 // its anonymous union members having variant members, exactly one of
2518 // them shall be initialized;
2519 if (AnyAnonStructUnionMembers ||
2520 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2521 // Check initialization of non-static data members. Base classes are
2522 // always initialized so do not need to be checked. Dependent bases
2523 // might not have initializers in the member initializer list.
2524 llvm::SmallPtrSet<Decl *, 16> Inits;
2525 for (const auto *I: Constructor->inits()) {
2526 if (FieldDecl *FD = I->getMember())
2527 Inits.insert(Ptr: FD);
2528 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2529 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2530 }
2531
2532 bool Diagnosed = false;
2533 for (auto *I : RD->fields())
2534 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2535 Kind))
2536 return false;
2537 }
2538 }
2539 } else {
2540 if (ReturnStmts.empty()) {
2541 switch (Kind) {
2542 case Sema::CheckConstexprKind::Diagnose:
2543 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2544 return false;
2545 break;
2546
2547 case Sema::CheckConstexprKind::CheckValid:
2548 // The formal requirements don't include this rule in C++14, even
2549 // though the "must be able to produce a constant expression" rules
2550 // still imply it in some cases.
2551 if (!SemaRef.getLangOpts().CPlusPlus14)
2552 return false;
2553 break;
2554 }
2555 } else if (ReturnStmts.size() > 1) {
2556 switch (Kind) {
2557 case Sema::CheckConstexprKind::Diagnose:
2558 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2559 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2560 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2561 SemaRef.Diag(Loc: ReturnStmts[I],
2562 DiagID: diag::note_constexpr_body_previous_return);
2563 break;
2564
2565 case Sema::CheckConstexprKind::CheckValid:
2566 if (!SemaRef.getLangOpts().CPlusPlus14)
2567 return false;
2568 break;
2569 }
2570 }
2571 }
2572
2573 // C++11 [dcl.constexpr]p5:
2574 // if no function argument values exist such that the function invocation
2575 // substitution would produce a constant expression, the program is
2576 // ill-formed; no diagnostic required.
2577 // C++11 [dcl.constexpr]p3:
2578 // - every constructor call and implicit conversion used in initializing the
2579 // return value shall be one of those allowed in a constant expression.
2580 // C++11 [dcl.constexpr]p4:
2581 // - every constructor involved in initializing non-static data members and
2582 // base class sub-objects shall be a constexpr constructor.
2583 //
2584 // Note that this rule is distinct from the "requirements for a constexpr
2585 // function", so is not checked in CheckValid mode. Because the check for
2586 // constexpr potential is expensive, skip the check if the diagnostic is
2587 // disabled, the function is declared in a system header, or we're in C++23
2588 // or later mode (see https://wg21.link/P2448).
2589 bool SkipCheck =
2590 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2591 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2592 SemaRef.getDiagnostics().isIgnored(
2593 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2594 SmallVector<PartialDiagnosticAt, 8> Diags;
2595 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2596 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2597 SemaRef.Diag(Loc: Dcl->getLocation(),
2598 DiagID: diag::ext_constexpr_function_never_constant_expr)
2599 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2600 << Dcl->getNameInfo().getSourceRange();
2601 for (const auto &Diag : Diags)
2602 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2603 // Don't return false here: we allow this for compatibility in
2604 // system headers.
2605 }
2606
2607 return true;
2608}
2609
2610static bool CheckConstexprMissingReturn(Sema &SemaRef,
2611 const FunctionDecl *Dcl) {
2612 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2613 Dcl->getReturnType()->isDependentType();
2614 // Skip emitting a missing return error diagnostic for non-void functions
2615 // since C++23 no longer mandates constexpr functions to yield constant
2616 // expressions.
2617 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2618 return true;
2619
2620 // C++14 doesn't require constexpr functions to contain a 'return'
2621 // statement. We still do, unless the return type might be void, because
2622 // otherwise if there's no return statement, the function cannot
2623 // be used in a core constant expression.
2624 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2625 SemaRef.Diag(Loc: Dcl->getLocation(),
2626 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2627 : diag::err_constexpr_body_no_return)
2628 << Dcl->isConsteval();
2629 return OK;
2630}
2631
2632bool Sema::CheckImmediateEscalatingFunctionDefinition(
2633 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2634 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2635 return true;
2636 FD->setBodyContainsImmediateEscalatingExpressions(
2637 FSI->FoundImmediateEscalatingExpression);
2638 if (FSI->FoundImmediateEscalatingExpression) {
2639 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2640 if (it != UndefinedButUsed.end()) {
2641 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2642 << it->first;
2643 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2644 if (FD->isImmediateFunction() && !FD->isConsteval())
2645 DiagnoseImmediateEscalatingReason(FD);
2646 return false;
2647 }
2648 }
2649 return true;
2650}
2651
2652void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2653 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2654 "expected an immediate function");
2655 assert(FD->hasBody() && "expected the function to have a body");
2656 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2657 Sema &SemaRef;
2658
2659 const FunctionDecl *ImmediateFn;
2660 bool ImmediateFnIsConstructor;
2661 CXXConstructorDecl *CurrentConstructor = nullptr;
2662 CXXCtorInitializer *CurrentInit = nullptr;
2663
2664 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2665 : SemaRef(SemaRef), ImmediateFn(FD),
2666 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2667 ShouldVisitImplicitCode = true;
2668 ShouldVisitLambdaBody = false;
2669 }
2670
2671 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2672 SourceLocation Loc = E->getBeginLoc();
2673 SourceRange Range = E->getSourceRange();
2674 if (CurrentConstructor && CurrentInit) {
2675 Loc = CurrentConstructor->getLocation();
2676 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2677 : SourceRange();
2678 }
2679
2680 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2681
2682 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2683 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2684 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2685 << (InitializedField != nullptr)
2686 << (CurrentInit && !CurrentInit->isWritten())
2687 << InitializedField << Range;
2688 }
2689 bool TraverseCallExpr(CallExpr *E) override {
2690 if (const auto *DR =
2691 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2692 DR && DR->isImmediateEscalating()) {
2693 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2694 return false;
2695 }
2696
2697 for (Expr *A : E->arguments())
2698 if (!TraverseStmt(S: A))
2699 return false;
2700
2701 return true;
2702 }
2703
2704 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2705 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2706 ReferencedFn && E->isImmediateEscalating()) {
2707 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2708 return false;
2709 }
2710
2711 return true;
2712 }
2713
2714 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2715 CXXConstructorDecl *D = E->getConstructor();
2716 if (E->isImmediateEscalating()) {
2717 Diag(E, Fn: D, /*IsCall=*/true);
2718 return false;
2719 }
2720 return true;
2721 }
2722
2723 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2724 llvm::SaveAndRestore RAII(CurrentInit, Init);
2725 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2726 }
2727
2728 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2729 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2730 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2731 }
2732
2733 bool TraverseType(QualType T, bool TraverseQualifier) override {
2734 return true;
2735 }
2736 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2737
2738 } Visitor(*this, FD);
2739 Visitor.TraverseDecl(D: FD);
2740}
2741
2742CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2743 assert(getLangOpts().CPlusPlus && "No class names in C!");
2744
2745 if (SS && SS->isInvalid())
2746 return nullptr;
2747
2748 if (SS && SS->isNotEmpty()) {
2749 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2750 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2751 }
2752
2753 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2754}
2755
2756bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2757 const CXXScopeSpec *SS) {
2758 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2759 return CurDecl && &II == CurDecl->getIdentifier();
2760}
2761
2762bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2763 assert(getLangOpts().CPlusPlus && "No class names in C!");
2764
2765 if (!getLangOpts().SpellChecking)
2766 return false;
2767
2768 CXXRecordDecl *CurDecl;
2769 if (SS && SS->isSet() && !SS->isInvalid()) {
2770 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2771 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2772 } else
2773 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2774
2775 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2776 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2777 < II->getLength()) {
2778 II = CurDecl->getIdentifier();
2779 return true;
2780 }
2781
2782 return false;
2783}
2784
2785CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2786 SourceRange SpecifierRange,
2787 bool Virtual, AccessSpecifier Access,
2788 TypeSourceInfo *TInfo,
2789 SourceLocation EllipsisLoc) {
2790 QualType BaseType = TInfo->getType();
2791 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2792 if (BaseType->containsErrors()) {
2793 // Already emitted a diagnostic when parsing the error type.
2794 return nullptr;
2795 }
2796
2797 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2798 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2799 << TInfo->getTypeLoc().getSourceRange();
2800 EllipsisLoc = SourceLocation();
2801 }
2802
2803 auto *BaseDecl =
2804 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2805 // C++ [class.derived.general]p2:
2806 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2807 // that is not an incompletely defined class; any cv-qualifiers are
2808 // ignored.
2809 if (BaseDecl) {
2810 // C++ [class.union.general]p4:
2811 // [...] A union shall not be used as a base class.
2812 if (BaseDecl->isUnion()) {
2813 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2814 return nullptr;
2815 }
2816
2817 if (BaseType.hasQualifiers()) {
2818 std::string Quals =
2819 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2820 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2821 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2822 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2823 }
2824
2825 // For the MS ABI, propagate DLL attributes to base class templates.
2826 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2827 Context.getTargetInfo().getTriple().isPS()) {
2828 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2829 if (auto *BaseSpec =
2830 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2831 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2832 BaseLoc);
2833 }
2834 }
2835 }
2836
2837 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2838 Args: SpecifierRange)) {
2839 Class->setInvalidDecl();
2840 return nullptr;
2841 }
2842
2843 BaseDecl = BaseDecl->getDefinition();
2844 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2845
2846 // Microsoft docs say:
2847 // "If a base-class has a code_seg attribute, derived classes must have the
2848 // same attribute."
2849 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2850 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2851 if ((DerivedCSA || BaseCSA) &&
2852 (!BaseCSA || !DerivedCSA ||
2853 BaseCSA->getName() != DerivedCSA->getName())) {
2854 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2855 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2856 << BaseDecl;
2857 return nullptr;
2858 }
2859
2860 // A class which contains a flexible array member is not suitable for use as
2861 // a base class:
2862 // - If the layout determines that a base comes before another base,
2863 // the flexible array member would index into the subsequent base.
2864 // - If the layout determines that base comes before the derived class,
2865 // the flexible array member would index into the derived class.
2866 if (BaseDecl->hasFlexibleArrayMember()) {
2867 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2868 << BaseDecl->getDeclName();
2869 return nullptr;
2870 }
2871
2872 // C++ [class]p3:
2873 // If a class is marked final and it appears as a base-type-specifier in
2874 // base-clause, the program is ill-formed.
2875 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2876 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2877 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2878 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2879 << BaseDecl->getDeclName() << FA->getRange();
2880 return nullptr;
2881 }
2882
2883 // If the base class is invalid the derived class is as well.
2884 if (BaseDecl->isInvalidDecl())
2885 Class->setInvalidDecl();
2886 } else if (BaseType->isDependentType()) {
2887 // Make sure that we don't make an ill-formed AST where the type of the
2888 // Class is non-dependent and its attached base class specifier is an
2889 // dependent type, which violates invariants in many clang code paths (e.g.
2890 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2891 // explicitly mark the Class decl invalid. The diagnostic was already
2892 // emitted.
2893 if (!Class->isDependentContext())
2894 Class->setInvalidDecl();
2895 } else {
2896 // The base class is some non-dependent non-class type.
2897 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2898 return nullptr;
2899 }
2900
2901 // In HLSL, unspecified class access is public rather than private.
2902 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2903 Access == AS_none)
2904 Access = AS_public;
2905
2906 // Create the base specifier.
2907 return new (Context) CXXBaseSpecifier(
2908 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2909 Access, TInfo, EllipsisLoc);
2910}
2911
2912BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2913 const ParsedAttributesView &Attributes,
2914 bool Virtual, AccessSpecifier Access,
2915 ParsedType basetype, SourceLocation BaseLoc,
2916 SourceLocation EllipsisLoc) {
2917 if (!classdecl)
2918 return true;
2919
2920 AdjustDeclIfTemplate(Decl&: classdecl);
2921 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2922 if (!Class)
2923 return true;
2924
2925 // We haven't yet attached the base specifiers.
2926 Class->setIsParsingBaseSpecifiers();
2927
2928 // We do not support any C++11 attributes on base-specifiers yet.
2929 // Diagnose any attributes we see.
2930 for (const ParsedAttr &AL : Attributes) {
2931 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2932 continue;
2933 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2934 DiagnoseUnknownAttribute(AL);
2935 else
2936 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2937 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2938 }
2939
2940 TypeSourceInfo *TInfo = nullptr;
2941 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2942
2943 if (EllipsisLoc.isInvalid() &&
2944 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2945 UPPC: UPPC_BaseType))
2946 return true;
2947
2948 // C++ [class.union.general]p4:
2949 // [...] A union shall not have base classes.
2950 if (Class->isUnion()) {
2951 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2952 << SpecifierRange;
2953 return true;
2954 }
2955
2956 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2957 Virtual, Access, TInfo,
2958 EllipsisLoc))
2959 return BaseSpec;
2960
2961 Class->setInvalidDecl();
2962 return true;
2963}
2964
2965/// Use small set to collect indirect bases. As this is only used
2966/// locally, there's no need to abstract the small size parameter.
2967typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2968
2969/// Recursively add the bases of Type. Don't add Type itself.
2970static void
2971NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2972 const QualType &Type)
2973{
2974 // Even though the incoming type is a base, it might not be
2975 // a class -- it could be a template parm, for instance.
2976 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2977 // Iterate over its bases.
2978 for (const auto &BaseSpec : Decl->bases()) {
2979 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2980 .getUnqualifiedType();
2981 if (Set.insert(Ptr: Base).second)
2982 // If we've not already seen it, recurse.
2983 NoteIndirectBases(Context, Set, Type: Base);
2984 }
2985 }
2986}
2987
2988bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2989 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2990 if (Bases.empty())
2991 return false;
2992
2993 // Used to keep track of which base types we have already seen, so
2994 // that we can properly diagnose redundant direct base types. Note
2995 // that the key is always the unqualified canonical type of the base
2996 // class.
2997 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2998
2999 // Used to track indirect bases so we can see if a direct base is
3000 // ambiguous.
3001 IndirectBaseSet IndirectBaseTypes;
3002
3003 // Copy non-redundant base specifiers into permanent storage.
3004 unsigned NumGoodBases = 0;
3005 bool Invalid = false;
3006
3007 if (getLangOpts().HLSL && Bases.size() > 1) {
3008 Diag(Loc: Bases[1]->getBeginLoc(), DiagID: diag::err_hlsl_mult_inheritance);
3009 // To prevent producing error messages about the additional base classes
3010 Bases = Bases.take_front();
3011 Invalid = true;
3012 }
3013
3014 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3015 QualType NewBaseType
3016 = Context.getCanonicalType(T: Bases[idx]->getType());
3017 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3018
3019 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3020 if (KnownBase) {
3021 // C++ [class.mi]p3:
3022 // A class shall not be specified as a direct base class of a
3023 // derived class more than once.
3024 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
3025 << KnownBase->getType() << Bases[idx]->getSourceRange();
3026
3027 // Delete the duplicate base class specifier; we're going to
3028 // overwrite its pointer later.
3029 Context.Deallocate(Ptr: Bases[idx]);
3030
3031 Invalid = true;
3032 } else {
3033 // Okay, add this new base class.
3034 KnownBase = Bases[idx];
3035 Bases[NumGoodBases++] = Bases[idx];
3036
3037 if (NewBaseType->isDependentType())
3038 continue;
3039 // Note this base's direct & indirect bases, if there could be ambiguity.
3040 if (Bases.size() > 1)
3041 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
3042
3043 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3044 if (Class->isInterface() &&
3045 (!RD->isInterfaceLike() ||
3046 KnownBase->getAccessSpecifier() != AS_public)) {
3047 // The Microsoft extension __interface does not permit bases that
3048 // are not themselves public interfaces.
3049 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
3050 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
3051 << RD->getSourceRange();
3052 Invalid = true;
3053 }
3054 if (RD->hasAttr<WeakAttr>())
3055 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
3056 }
3057 }
3058 }
3059
3060 // Attach the remaining base class specifiers to the derived class.
3061 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3062
3063 // Check that the only base classes that are duplicate are virtual.
3064 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3065 // Check whether this direct base is inaccessible due to ambiguity.
3066 QualType BaseType = Bases[idx]->getType();
3067
3068 // Skip all dependent types in templates being used as base specifiers.
3069 // Checks below assume that the base specifier is a CXXRecord.
3070 if (BaseType->isDependentType())
3071 continue;
3072
3073 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3074 .getUnqualifiedType();
3075
3076 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3077 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3078 /*DetectVirtual=*/true);
3079 bool found
3080 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3081 assert(found);
3082 (void)found;
3083
3084 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3085 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3086 << BaseType << getAmbiguousPathsDisplayString(Paths)
3087 << Bases[idx]->getSourceRange();
3088 else
3089 assert(Bases[idx]->isVirtual());
3090 }
3091
3092 // Delete the base class specifier, since its data has been copied
3093 // into the CXXRecordDecl.
3094 Context.Deallocate(Ptr: Bases[idx]);
3095 }
3096
3097 return Invalid;
3098}
3099
3100void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3101 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3102 if (!ClassDecl || Bases.empty())
3103 return;
3104
3105 AdjustDeclIfTemplate(Decl&: ClassDecl);
3106 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3107}
3108
3109bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3110 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3111 if (!getLangOpts().CPlusPlus)
3112 return false;
3113
3114 if (!Base || !Derived)
3115 return false;
3116
3117 // If either the base or the derived type is invalid, don't try to
3118 // check whether one is derived from the other.
3119 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3120 return false;
3121
3122 // FIXME: In a modules build, do we need the entire path to be visible for us
3123 // to be able to use the inheritance relationship?
3124 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3125 !Derived->isBeingDefined())
3126 return false;
3127
3128 return Derived->isDerivedFrom(Base, Paths);
3129}
3130
3131bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3132 CXXRecordDecl *Base) {
3133 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3134 /*DetectVirtual=*/false);
3135 return IsDerivedFrom(Loc, Derived, Base, Paths);
3136}
3137
3138bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3139 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3140 /*DetectVirtual=*/false);
3141 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3142 Base: Base->getAsCXXRecordDecl(), Paths);
3143}
3144
3145bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3146 CXXBasePaths &Paths) {
3147 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3148 Base: Base->getAsCXXRecordDecl(), Paths);
3149}
3150
3151static void BuildBasePathArray(const CXXBasePath &Path,
3152 CXXCastPath &BasePathArray) {
3153 // We first go backward and check if we have a virtual base.
3154 // FIXME: It would be better if CXXBasePath had the base specifier for
3155 // the nearest virtual base.
3156 unsigned Start = 0;
3157 for (unsigned I = Path.size(); I != 0; --I) {
3158 if (Path[I - 1].Base->isVirtual()) {
3159 Start = I - 1;
3160 break;
3161 }
3162 }
3163
3164 // Now add all bases.
3165 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3166 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3167}
3168
3169
3170void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3171 CXXCastPath &BasePathArray) {
3172 assert(BasePathArray.empty() && "Base path array must be empty!");
3173 assert(Paths.isRecordingPaths() && "Must record paths!");
3174 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3175}
3176
3177bool
3178Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3179 unsigned InaccessibleBaseID,
3180 unsigned AmbiguousBaseConvID,
3181 SourceLocation Loc, SourceRange Range,
3182 DeclarationName Name,
3183 CXXCastPath *BasePath,
3184 bool IgnoreAccess) {
3185 // First, determine whether the path from Derived to Base is
3186 // ambiguous. This is slightly more expensive than checking whether
3187 // the Derived to Base conversion exists, because here we need to
3188 // explore multiple paths to determine if there is an ambiguity.
3189 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3190 /*DetectVirtual=*/false);
3191 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3192 if (!DerivationOkay)
3193 return true;
3194
3195 const CXXBasePath *Path = nullptr;
3196 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3197 Path = &Paths.front();
3198
3199 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3200 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3201 // user to access such bases.
3202 if (!Path && getLangOpts().MSVCCompat) {
3203 for (const CXXBasePath &PossiblePath : Paths) {
3204 if (PossiblePath.size() == 1) {
3205 Path = &PossiblePath;
3206 if (AmbiguousBaseConvID)
3207 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3208 << Base << Derived << Range;
3209 break;
3210 }
3211 }
3212 }
3213
3214 if (Path) {
3215 if (!IgnoreAccess) {
3216 // Check that the base class can be accessed.
3217 switch (
3218 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3219 case AR_inaccessible:
3220 return true;
3221 case AR_accessible:
3222 case AR_dependent:
3223 case AR_delayed:
3224 break;
3225 }
3226 }
3227
3228 // Build a base path if necessary.
3229 if (BasePath)
3230 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3231 return false;
3232 }
3233
3234 if (AmbiguousBaseConvID) {
3235 // We know that the derived-to-base conversion is ambiguous, and
3236 // we're going to produce a diagnostic. Perform the derived-to-base
3237 // search just one more time to compute all of the possible paths so
3238 // that we can print them out. This is more expensive than any of
3239 // the previous derived-to-base checks we've done, but at this point
3240 // performance isn't as much of an issue.
3241 Paths.clear();
3242 Paths.setRecordingPaths(true);
3243 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3244 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3245 (void)StillOkay;
3246
3247 // Build up a textual representation of the ambiguous paths, e.g.,
3248 // D -> B -> A, that will be used to illustrate the ambiguous
3249 // conversions in the diagnostic. We only print one of the paths
3250 // to each base class subobject.
3251 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3252
3253 Diag(Loc, DiagID: AmbiguousBaseConvID)
3254 << Derived << Base << PathDisplayStr << Range << Name;
3255 }
3256 return true;
3257}
3258
3259bool
3260Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3261 SourceLocation Loc, SourceRange Range,
3262 CXXCastPath *BasePath,
3263 bool IgnoreAccess) {
3264 return CheckDerivedToBaseConversion(
3265 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3266 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3267 BasePath, IgnoreAccess);
3268}
3269
3270std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3271 std::string PathDisplayStr;
3272 std::set<unsigned> DisplayedPaths;
3273 for (const CXXBasePath &Path : Paths) {
3274 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3275 // We haven't displayed a path to this particular base
3276 // class subobject yet.
3277 PathDisplayStr += "\n ";
3278 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3279 .getAsString();
3280 for (const CXXBasePathElement &Element : Path)
3281 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3282 }
3283 }
3284
3285 return PathDisplayStr;
3286}
3287
3288//===----------------------------------------------------------------------===//
3289// C++ class member Handling
3290//===----------------------------------------------------------------------===//
3291
3292bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3293 SourceLocation ColonLoc,
3294 const ParsedAttributesView &Attrs) {
3295 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3296 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3297 ASLoc, ColonLoc);
3298 CurContext->addHiddenDecl(D: ASDecl);
3299 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3300}
3301
3302void Sema::CheckOverrideControl(NamedDecl *D) {
3303 if (D->isInvalidDecl())
3304 return;
3305
3306 // We only care about "override" and "final" declarations.
3307 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3308 return;
3309
3310 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3311
3312 // We can't check dependent instance methods.
3313 if (MD && MD->isInstance() &&
3314 (MD->getParent()->hasAnyDependentBases() ||
3315 MD->getType()->isDependentType()))
3316 return;
3317
3318 if (MD && !MD->isVirtual()) {
3319 // If we have a non-virtual method, check if it hides a virtual method.
3320 // (In that case, it's most likely the method has the wrong type.)
3321 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3322 FindHiddenVirtualMethods(MD, OverloadedMethods);
3323
3324 if (!OverloadedMethods.empty()) {
3325 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3326 Diag(Loc: OA->getLocation(),
3327 DiagID: diag::override_keyword_hides_virtual_member_function)
3328 << "override" << (OverloadedMethods.size() > 1);
3329 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3330 Diag(Loc: FA->getLocation(),
3331 DiagID: diag::override_keyword_hides_virtual_member_function)
3332 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3333 << (OverloadedMethods.size() > 1);
3334 }
3335 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3336 MD->setInvalidDecl();
3337 return;
3338 }
3339 // Fall through into the general case diagnostic.
3340 // FIXME: We might want to attempt typo correction here.
3341 }
3342
3343 if (!MD || !MD->isVirtual()) {
3344 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3345 Diag(Loc: OA->getLocation(),
3346 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3347 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3348 D->dropAttr<OverrideAttr>();
3349 }
3350 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3351 Diag(Loc: FA->getLocation(),
3352 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3353 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3354 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3355 D->dropAttr<FinalAttr>();
3356 }
3357 return;
3358 }
3359
3360 // C++11 [class.virtual]p5:
3361 // If a function is marked with the virt-specifier override and
3362 // does not override a member function of a base class, the program is
3363 // ill-formed.
3364 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3365 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3366 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3367 << MD->getDeclName();
3368}
3369
3370void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3371 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3372 return;
3373 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3374 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3375 return;
3376
3377 SourceLocation Loc = MD->getLocation();
3378 SourceLocation SpellingLoc = Loc;
3379 if (getSourceManager().isMacroArgExpansion(Loc))
3380 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3381 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3382 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3383 return;
3384
3385 if (MD->size_overridden_methods() > 0) {
3386 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3387 unsigned DiagID =
3388 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3389 ? DiagInconsistent
3390 : DiagSuggest;
3391 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3392 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3393 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3394 };
3395 if (isa<CXXDestructorDecl>(Val: MD))
3396 EmitDiag(
3397 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3398 diag::warn_suggest_destructor_marked_not_override_overriding);
3399 else
3400 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3401 diag::warn_suggest_function_marked_not_override_overriding);
3402 }
3403}
3404
3405bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3406 const CXXMethodDecl *Old) {
3407 FinalAttr *FA = Old->getAttr<FinalAttr>();
3408 if (!FA)
3409 return false;
3410
3411 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3412 << New->getDeclName()
3413 << FA->isSpelledAsSealed();
3414 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3415 return true;
3416}
3417
3418static bool InitializationHasSideEffects(const FieldDecl &FD) {
3419 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3420 // FIXME: Destruction of ObjC lifetime types has side-effects.
3421 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3422 return !RD->isCompleteDefinition() || !RD->hasTrivialDefaultConstructor() ||
3423 !RD->hasTrivialDestructor();
3424 return false;
3425}
3426
3427void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3428 DeclarationName FieldName,
3429 const CXXRecordDecl *RD,
3430 bool DeclIsField) {
3431 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3432 return;
3433
3434 // To record a shadowed field in a base
3435 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3436 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3437 CXXBasePath &Path) {
3438 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3439 // Record an ambiguous path directly
3440 if (Bases.find(x: Base) != Bases.end())
3441 return true;
3442 for (const auto Field : Base->lookup(Name: FieldName)) {
3443 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3444 Field->getAccess() != AS_private) {
3445 assert(Field->getAccess() != AS_none);
3446 assert(Bases.find(Base) == Bases.end());
3447 Bases[Base] = Field;
3448 return true;
3449 }
3450 }
3451 return false;
3452 };
3453
3454 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3455 /*DetectVirtual=*/true);
3456 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3457 return;
3458
3459 for (const auto &P : Paths) {
3460 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3461 auto It = Bases.find(x: Base);
3462 // Skip duplicated bases
3463 if (It == Bases.end())
3464 continue;
3465 auto BaseField = It->second;
3466 assert(BaseField->getAccess() != AS_private);
3467 if (AS_none !=
3468 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3469 Diag(Loc, DiagID: diag::warn_shadow_field)
3470 << FieldName << RD << Base << DeclIsField;
3471 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3472 Bases.erase(position: It);
3473 }
3474 }
3475}
3476
3477template <typename AttrType>
3478inline static bool HasAttribute(const QualType &T) {
3479 if (const TagDecl *TD = T->getAsTagDecl())
3480 return TD->hasAttr<AttrType>();
3481 if (const TypedefType *TDT = T->getAs<TypedefType>())
3482 return TDT->getDecl()->hasAttr<AttrType>();
3483 return false;
3484}
3485
3486static bool IsUnusedPrivateField(const FieldDecl *FD) {
3487 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3488 QualType FieldType = FD->getType();
3489 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3490 return true;
3491
3492 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3493 !FD->getParent()->isDependentContext() &&
3494 !HasAttribute<UnusedAttr>(T: FieldType) &&
3495 !InitializationHasSideEffects(FD: *FD);
3496 }
3497 return false;
3498}
3499
3500NamedDecl *
3501Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3502 MultiTemplateParamsArg TemplateParameterLists,
3503 Expr *BitWidth, const VirtSpecifiers &VS,
3504 InClassInitStyle InitStyle) {
3505 const DeclSpec &DS = D.getDeclSpec();
3506 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3507 DeclarationName Name = NameInfo.getName();
3508 SourceLocation Loc = NameInfo.getLoc();
3509
3510 // For anonymous bitfields, the location should point to the type.
3511 if (Loc.isInvalid())
3512 Loc = D.getBeginLoc();
3513
3514 assert(isa<CXXRecordDecl>(CurContext));
3515 assert(!DS.isFriendSpecified());
3516
3517 bool isFunc = D.isDeclarationOfFunction();
3518 const ParsedAttr *MSPropertyAttr =
3519 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3520
3521 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3522 // The Microsoft extension __interface only permits public member functions
3523 // and prohibits constructors, destructors, operators, non-public member
3524 // functions, static methods and data members.
3525 unsigned InvalidDecl;
3526 bool ShowDeclName = true;
3527 if (!isFunc &&
3528 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3529 InvalidDecl = 0;
3530 else if (!isFunc)
3531 InvalidDecl = 1;
3532 else if (AS != AS_public)
3533 InvalidDecl = 2;
3534 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3535 InvalidDecl = 3;
3536 else switch (Name.getNameKind()) {
3537 case DeclarationName::CXXConstructorName:
3538 InvalidDecl = 4;
3539 ShowDeclName = false;
3540 break;
3541
3542 case DeclarationName::CXXDestructorName:
3543 InvalidDecl = 5;
3544 ShowDeclName = false;
3545 break;
3546
3547 case DeclarationName::CXXOperatorName:
3548 case DeclarationName::CXXConversionFunctionName:
3549 InvalidDecl = 6;
3550 break;
3551
3552 default:
3553 InvalidDecl = 0;
3554 break;
3555 }
3556
3557 if (InvalidDecl) {
3558 if (ShowDeclName)
3559 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3560 << (InvalidDecl-1) << Name;
3561 else
3562 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3563 << (InvalidDecl-1) << "";
3564 return nullptr;
3565 }
3566 }
3567
3568 // HLSL prohibits user defined constructors and destructors.
3569 if (getLangOpts().HLSL) {
3570 switch (Name.getNameKind()) {
3571 case DeclarationName::CXXConstructorName:
3572 case DeclarationName::CXXDestructorName:
3573 Diag(Loc, DiagID: diag::err_hlsl_cstor_dstor);
3574 return nullptr;
3575 default:
3576 break;
3577 }
3578 }
3579
3580 // C++ 9.2p6: A member shall not be declared to have automatic storage
3581 // duration (auto, register) or with the extern storage-class-specifier.
3582 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3583 // data members and cannot be applied to names declared const or static,
3584 // and cannot be applied to reference members.
3585 switch (DS.getStorageClassSpec()) {
3586 case DeclSpec::SCS_unspecified:
3587 case DeclSpec::SCS_typedef:
3588 case DeclSpec::SCS_static:
3589 break;
3590 case DeclSpec::SCS_mutable:
3591 if (isFunc) {
3592 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3593
3594 // FIXME: It would be nicer if the keyword was ignored only for this
3595 // declarator. Otherwise we could get follow-up errors.
3596 D.getMutableDeclSpec().ClearStorageClassSpecs();
3597 }
3598 break;
3599 default:
3600 Diag(Loc: DS.getStorageClassSpecLoc(),
3601 DiagID: diag::err_storageclass_invalid_for_member);
3602 D.getMutableDeclSpec().ClearStorageClassSpecs();
3603 break;
3604 }
3605
3606 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3607 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3608 !isFunc && TemplateParameterLists.empty();
3609
3610 if (DS.hasConstexprSpecifier() && isInstField) {
3611 SemaDiagnosticBuilder B =
3612 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3613 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3614 if (InitStyle == ICIS_NoInit) {
3615 B << 0 << 0;
3616 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3617 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3618 else {
3619 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3620 D.getMutableDeclSpec().ClearConstexprSpec();
3621 const char *PrevSpec;
3622 unsigned DiagID;
3623 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3624 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3625 (void)Failed;
3626 assert(!Failed && "Making a constexpr member const shouldn't fail");
3627 }
3628 } else {
3629 B << 1;
3630 const char *PrevSpec;
3631 unsigned DiagID;
3632 if (D.getMutableDeclSpec().SetStorageClassSpec(
3633 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3634 Policy: Context.getPrintingPolicy())) {
3635 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3636 "This is the only DeclSpec that should fail to be applied");
3637 B << 1;
3638 } else {
3639 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3640 isInstField = false;
3641 }
3642 }
3643 }
3644
3645 NamedDecl *Member;
3646 if (isInstField) {
3647 CXXScopeSpec &SS = D.getCXXScopeSpec();
3648
3649 // Data members must have identifiers for names.
3650 if (!Name.isIdentifier()) {
3651 Diag(Loc, DiagID: diag::err_bad_variable_name)
3652 << Name;
3653 return nullptr;
3654 }
3655
3656 IdentifierInfo *II = Name.getAsIdentifierInfo();
3657 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3658 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3659 << II
3660 << SourceRange(D.getName().TemplateId->LAngleLoc,
3661 D.getName().TemplateId->RAngleLoc)
3662 << D.getName().TemplateId->LAngleLoc;
3663 D.SetIdentifier(Id: II, IdLoc: Loc);
3664 }
3665
3666 if (SS.isSet() && !SS.isInvalid()) {
3667 // The user provided a superfluous scope specifier inside a class
3668 // definition:
3669 //
3670 // class X {
3671 // int X::member;
3672 // };
3673 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3674 TemplateIdAnnotation *TemplateId =
3675 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3676 ? D.getName().TemplateId
3677 : nullptr;
3678 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3679 TemplateId,
3680 /*IsMemberSpecialization=*/false);
3681 } else {
3682 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3683 << Name << SS.getRange();
3684 }
3685 SS.clear();
3686 }
3687
3688 if (MSPropertyAttr) {
3689 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3690 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3691 if (!Member)
3692 return nullptr;
3693 isInstField = false;
3694 } else {
3695 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3696 BitfieldWidth: BitWidth, InitStyle, AS);
3697 if (!Member)
3698 return nullptr;
3699 }
3700
3701 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3702 } else {
3703 Member = HandleDeclarator(S, D, TemplateParameterLists);
3704 if (!Member)
3705 return nullptr;
3706
3707 // Non-instance-fields can't have a bitfield.
3708 if (BitWidth) {
3709 if (Member->isInvalidDecl()) {
3710 // don't emit another diagnostic.
3711 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3712 // C++ 9.6p3: A bit-field shall not be a static member.
3713 // "static member 'A' cannot be a bit-field"
3714 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3715 << Name << BitWidth->getSourceRange();
3716 } else if (isa<TypedefDecl>(Val: Member)) {
3717 // "typedef member 'x' cannot be a bit-field"
3718 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3719 << Name << BitWidth->getSourceRange();
3720 } else {
3721 // A function typedef ("typedef int f(); f a;").
3722 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3723 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3724 << Name << cast<ValueDecl>(Val: Member)->getType()
3725 << BitWidth->getSourceRange();
3726 }
3727
3728 BitWidth = nullptr;
3729 Member->setInvalidDecl();
3730 }
3731
3732 NamedDecl *NonTemplateMember = Member;
3733 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3734 NonTemplateMember = FunTmpl->getTemplatedDecl();
3735 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3736 NonTemplateMember = VarTmpl->getTemplatedDecl();
3737
3738 Member->setAccess(AS);
3739
3740 // If we have declared a member function template or static data member
3741 // template, set the access of the templated declaration as well.
3742 if (NonTemplateMember != Member)
3743 NonTemplateMember->setAccess(AS);
3744
3745 // C++ [temp.deduct.guide]p3:
3746 // A deduction guide [...] for a member class template [shall be
3747 // declared] with the same access [as the template].
3748 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3749 auto *TD = DG->getDeducedTemplate();
3750 // Access specifiers are only meaningful if both the template and the
3751 // deduction guide are from the same scope.
3752 if (AS != TD->getAccess() &&
3753 TD->getDeclContext()->getRedeclContext()->Equals(
3754 DC: DG->getDeclContext()->getRedeclContext())) {
3755 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3756 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3757 << TD->getAccess();
3758 const AccessSpecDecl *LastAccessSpec = nullptr;
3759 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3760 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3761 LastAccessSpec = AccessSpec;
3762 }
3763 assert(LastAccessSpec && "differing access with no access specifier");
3764 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3765 << AS;
3766 }
3767 }
3768 }
3769
3770 if (VS.isOverrideSpecified())
3771 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3772 if (VS.isFinalSpecified())
3773 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3774 S: VS.isFinalSpelledSealed()
3775 ? FinalAttr::Keyword_sealed
3776 : FinalAttr::Keyword_final));
3777
3778 if (VS.getLastLocation().isValid()) {
3779 // Update the end location of a method that has a virt-specifiers.
3780 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3781 MD->setRangeEnd(VS.getLastLocation());
3782 }
3783
3784 CheckOverrideControl(D: Member);
3785
3786 assert((Name || isInstField) && "No identifier for non-field ?");
3787
3788 if (isInstField) {
3789 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3790 FieldCollector->Add(D: FD);
3791
3792 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3793 IsUnusedPrivateField(FD)) {
3794 // Remember all explicit private FieldDecls that have a name, no side
3795 // effects and are not part of a dependent type declaration.
3796 UnusedPrivateFields.insert(X: FD);
3797 }
3798 }
3799
3800 return Member;
3801}
3802
3803namespace {
3804 class UninitializedFieldVisitor
3805 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3806 Sema &S;
3807 // List of Decls to generate a warning on. Also remove Decls that become
3808 // initialized.
3809 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3810 // List of base classes of the record. Classes are removed after their
3811 // initializers.
3812 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3813 // Vector of decls to be removed from the Decl set prior to visiting the
3814 // nodes. These Decls may have been initialized in the prior initializer.
3815 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3816 // If non-null, add a note to the warning pointing back to the constructor.
3817 const CXXConstructorDecl *Constructor;
3818 // Variables to hold state when processing an initializer list. When
3819 // InitList is true, special case initialization of FieldDecls matching
3820 // InitListFieldDecl.
3821 bool InitList;
3822 FieldDecl *InitListFieldDecl;
3823 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3824
3825 public:
3826 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3827 UninitializedFieldVisitor(Sema &S,
3828 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3829 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3830 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3831 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3832
3833 // Returns true if the use of ME is not an uninitialized use.
3834 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3835 bool CheckReferenceOnly) {
3836 llvm::SmallVector<FieldDecl*, 4> Fields;
3837 bool ReferenceField = false;
3838 while (ME) {
3839 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3840 if (!FD)
3841 return false;
3842 Fields.push_back(Elt: FD);
3843 if (FD->getType()->isReferenceType())
3844 ReferenceField = true;
3845 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3846 }
3847
3848 // Binding a reference to an uninitialized field is not an
3849 // uninitialized use.
3850 if (CheckReferenceOnly && !ReferenceField)
3851 return true;
3852
3853 // Discard the first field since it is the field decl that is being
3854 // initialized.
3855 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3856 auto UsedIter = UsedFields.begin();
3857 const auto UsedEnd = UsedFields.end();
3858
3859 for (const unsigned Orig : InitFieldIndex) {
3860 if (UsedIter == UsedEnd)
3861 break;
3862 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3863 if (UsedIndex < Orig)
3864 return true;
3865 if (UsedIndex > Orig)
3866 break;
3867 ++UsedIter;
3868 }
3869
3870 return false;
3871 }
3872
3873 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3874 bool AddressOf) {
3875 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3876 return;
3877
3878 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3879 // or union.
3880 MemberExpr *FieldME = ME;
3881
3882 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3883
3884 Expr *Base = ME;
3885 while (MemberExpr *SubME =
3886 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3887
3888 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3889 return;
3890
3891 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3892 if (!FD->isAnonymousStructOrUnion())
3893 FieldME = SubME;
3894
3895 if (!FieldME->getType().isPODType(Context: S.Context))
3896 AllPODFields = false;
3897
3898 Base = SubME->getBase();
3899 }
3900
3901 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3902 Visit(S: Base);
3903 return;
3904 }
3905
3906 if (AddressOf && AllPODFields)
3907 return;
3908
3909 ValueDecl* FoundVD = FieldME->getMemberDecl();
3910
3911 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3912 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3913 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3914 }
3915
3916 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3917 QualType T = BaseCast->getType();
3918 if (T->isPointerType() &&
3919 BaseClasses.count(Ptr: T->getPointeeType())) {
3920 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3921 << T->getPointeeType() << FoundVD;
3922 }
3923 }
3924 }
3925
3926 if (!Decls.count(Ptr: FoundVD))
3927 return;
3928
3929 const bool IsReference = FoundVD->getType()->isReferenceType();
3930
3931 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3932 // Special checking for initializer lists.
3933 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3934 return;
3935 }
3936 } else {
3937 // Prevent double warnings on use of unbounded references.
3938 if (CheckReferenceOnly && !IsReference)
3939 return;
3940 }
3941
3942 unsigned diag = IsReference
3943 ? diag::warn_reference_field_is_uninit
3944 : diag::warn_field_is_uninit;
3945 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3946 if (Constructor)
3947 S.Diag(Loc: Constructor->getLocation(),
3948 DiagID: diag::note_uninit_in_this_constructor)
3949 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3950
3951 }
3952
3953 void HandleValue(Expr *E, bool AddressOf) {
3954 E = E->IgnoreParens();
3955
3956 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3957 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3958 AddressOf /*AddressOf*/);
3959 return;
3960 }
3961
3962 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3963 Visit(S: CO->getCond());
3964 HandleValue(E: CO->getTrueExpr(), AddressOf);
3965 HandleValue(E: CO->getFalseExpr(), AddressOf);
3966 return;
3967 }
3968
3969 if (BinaryConditionalOperator *BCO =
3970 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3971 Visit(S: BCO->getCond());
3972 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3973 return;
3974 }
3975
3976 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3977 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3978 return;
3979 }
3980
3981 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3982 switch (BO->getOpcode()) {
3983 default:
3984 break;
3985 case(BO_PtrMemD):
3986 case(BO_PtrMemI):
3987 HandleValue(E: BO->getLHS(), AddressOf);
3988 Visit(S: BO->getRHS());
3989 return;
3990 case(BO_Comma):
3991 Visit(S: BO->getLHS());
3992 HandleValue(E: BO->getRHS(), AddressOf);
3993 return;
3994 }
3995 }
3996
3997 Visit(S: E);
3998 }
3999
4000 void CheckInitListExpr(InitListExpr *ILE) {
4001 InitFieldIndex.push_back(Elt: 0);
4002 for (auto *Child : ILE->children()) {
4003 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
4004 CheckInitListExpr(ILE: SubList);
4005 } else {
4006 Visit(S: Child);
4007 }
4008 ++InitFieldIndex.back();
4009 }
4010 InitFieldIndex.pop_back();
4011 }
4012
4013 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4014 FieldDecl *Field, const Type *BaseClass) {
4015 // Remove Decls that may have been initialized in the previous
4016 // initializer.
4017 for (ValueDecl* VD : DeclsToRemove)
4018 Decls.erase(Ptr: VD);
4019 DeclsToRemove.clear();
4020
4021 Constructor = FieldConstructor;
4022 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
4023
4024 if (ILE && Field) {
4025 InitList = true;
4026 InitListFieldDecl = Field;
4027 InitFieldIndex.clear();
4028 CheckInitListExpr(ILE);
4029 } else {
4030 InitList = false;
4031 Visit(S: E);
4032 }
4033
4034 if (Field)
4035 Decls.erase(Ptr: Field);
4036 if (BaseClass)
4037 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4038 }
4039
4040 void VisitMemberExpr(MemberExpr *ME) {
4041 // All uses of unbounded reference fields will warn.
4042 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4043 }
4044
4045 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4046 if (E->getCastKind() == CK_LValueToRValue) {
4047 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4048 return;
4049 }
4050
4051 Inherited::VisitImplicitCastExpr(S: E);
4052 }
4053
4054 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4055 if (E->getConstructor()->isCopyConstructor()) {
4056 Expr *ArgExpr = E->getArg(Arg: 0);
4057 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4058 if (ILE->getNumInits() == 1)
4059 ArgExpr = ILE->getInit(Init: 0);
4060 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4061 if (ICE->getCastKind() == CK_NoOp)
4062 ArgExpr = ICE->getSubExpr();
4063 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4064 return;
4065 }
4066 Inherited::VisitCXXConstructExpr(S: E);
4067 }
4068
4069 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4070 Expr *Callee = E->getCallee();
4071 if (isa<MemberExpr>(Val: Callee)) {
4072 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4073 for (auto *Arg : E->arguments())
4074 Visit(S: Arg);
4075 return;
4076 }
4077
4078 Inherited::VisitCXXMemberCallExpr(S: E);
4079 }
4080
4081 void VisitCallExpr(CallExpr *E) {
4082 // Treat std::move as a use.
4083 if (E->isCallToStdMove()) {
4084 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4085 return;
4086 }
4087
4088 Inherited::VisitCallExpr(CE: E);
4089 }
4090
4091 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4092 Expr *Callee = E->getCallee();
4093
4094 if (isa<UnresolvedLookupExpr>(Val: Callee))
4095 return Inherited::VisitCXXOperatorCallExpr(S: E);
4096
4097 Visit(S: Callee);
4098 for (auto *Arg : E->arguments())
4099 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4100 }
4101
4102 void VisitBinaryOperator(BinaryOperator *E) {
4103 // If a field assignment is detected, remove the field from the
4104 // uninitiailized field set.
4105 if (E->getOpcode() == BO_Assign)
4106 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4107 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4108 if (!FD->getType()->isReferenceType())
4109 DeclsToRemove.push_back(Elt: FD);
4110
4111 if (E->isCompoundAssignmentOp()) {
4112 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4113 Visit(S: E->getRHS());
4114 return;
4115 }
4116
4117 Inherited::VisitBinaryOperator(S: E);
4118 }
4119
4120 void VisitUnaryOperator(UnaryOperator *E) {
4121 if (E->isIncrementDecrementOp()) {
4122 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4123 return;
4124 }
4125 if (E->getOpcode() == UO_AddrOf) {
4126 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4127 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4128 return;
4129 }
4130 }
4131
4132 Inherited::VisitUnaryOperator(S: E);
4133 }
4134 };
4135
4136 // Diagnose value-uses of fields to initialize themselves, e.g.
4137 // foo(foo)
4138 // where foo is not also a parameter to the constructor.
4139 // Also diagnose across field uninitialized use such as
4140 // x(y), y(x)
4141 // TODO: implement -Wuninitialized and fold this into that framework.
4142 static void DiagnoseUninitializedFields(
4143 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4144
4145 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4146 Loc: Constructor->getLocation())) {
4147 return;
4148 }
4149
4150 if (Constructor->isInvalidDecl())
4151 return;
4152
4153 const CXXRecordDecl *RD = Constructor->getParent();
4154
4155 if (RD->isDependentContext())
4156 return;
4157
4158 // Holds fields that are uninitialized.
4159 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4160
4161 // At the beginning, all fields are uninitialized.
4162 for (auto *I : RD->decls()) {
4163 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4164 UninitializedFields.insert(Ptr: FD);
4165 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4166 UninitializedFields.insert(Ptr: IFD->getAnonField());
4167 }
4168 }
4169
4170 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4171 for (const auto &I : RD->bases()) {
4172 // Virtual bases are initialized from the most derived class, so an
4173 // abstract base class constructor can assume it to be initialized.
4174 if (I.isVirtual() && RD->isAbstract())
4175 continue;
4176 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4177 }
4178
4179 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4180 return;
4181
4182 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4183 UninitializedFields,
4184 UninitializedBaseClasses);
4185
4186 for (const auto *FieldInit : Constructor->inits()) {
4187 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4188 break;
4189
4190 Expr *InitExpr = FieldInit->getInit();
4191 if (!InitExpr)
4192 continue;
4193
4194 if (CXXDefaultInitExpr *Default =
4195 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4196 InitExpr = Default->getExpr();
4197 if (!InitExpr)
4198 continue;
4199 // In class initializers will point to the constructor.
4200 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4201 Field: FieldInit->getAnyMember(),
4202 BaseClass: FieldInit->getBaseClass());
4203 } else {
4204 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4205 Field: FieldInit->getAnyMember(),
4206 BaseClass: FieldInit->getBaseClass());
4207 }
4208 }
4209 }
4210} // namespace
4211
4212void Sema::ActOnStartCXXInClassMemberInitializer() {
4213 // Create a synthetic function scope to represent the call to the constructor
4214 // that notionally surrounds a use of this initializer.
4215 PushFunctionScope();
4216}
4217
4218void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4219 if (!D.isFunctionDeclarator())
4220 return;
4221 auto &FTI = D.getFunctionTypeInfo();
4222 if (!FTI.Params)
4223 return;
4224 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4225 FTI.NumParams)) {
4226 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4227 if (ParamDecl->getDeclName())
4228 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4229 }
4230}
4231
4232ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4233 return ActOnRequiresClause(ConstraintExpr);
4234}
4235
4236ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4237 if (ConstraintExpr.isInvalid())
4238 return ExprError();
4239
4240 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4241 UPPC: UPPC_RequiresClause))
4242 return ExprError();
4243
4244 return ConstraintExpr;
4245}
4246
4247ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4248 Expr *InitExpr,
4249 SourceLocation InitLoc) {
4250 InitializedEntity Entity =
4251 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4252 return ConvertMemberDefaultInitExpression(FD, Entity, InitExpr, InitLoc);
4253}
4254
4255ExprResult Sema::ConvertMemberDefaultInitExpression(
4256 FieldDecl *FD, const InitializedEntity &Entity, Expr *InitExpr,
4257 SourceLocation InitLoc) {
4258 InitializationKind Kind =
4259 FD->getInClassInitStyle() == ICIS_ListInit
4260 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4261 LBraceLoc: InitExpr->getBeginLoc(),
4262 RBraceLoc: InitExpr->getEndLoc())
4263 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4264 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4265 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4266}
4267
4268void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4269 SourceLocation InitLoc,
4270 ExprResult InitExpr) {
4271 // Pop the notional constructor scope we created earlier.
4272 PopFunctionScopeInfo(WP: nullptr, D);
4273
4274 // Microsoft C++'s property declaration cannot have a default member
4275 // initializer.
4276 if (isa<MSPropertyDecl>(Val: D)) {
4277 D->setInvalidDecl();
4278 return;
4279 }
4280
4281 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4282 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4283 "must set init style when field is created");
4284
4285 if (!InitExpr.isUsable() ||
4286 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4287 FD->setInvalidDecl();
4288 ExprResult RecoveryInit =
4289 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4290 if (RecoveryInit.isUsable())
4291 FD->setInClassInitializer(RecoveryInit.get());
4292 return;
4293 }
4294
4295 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4296 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4297 // C++11 [class.base.init]p7:
4298 // The initialization of each base and member constitutes a
4299 // full-expression.
4300 if (!InitExpr.isInvalid())
4301 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4302 if (InitExpr.isInvalid()) {
4303 FD->setInvalidDecl();
4304 return;
4305 }
4306 }
4307
4308 FD->setInClassInitializer(InitExpr.get());
4309}
4310
4311/// Find the direct and/or virtual base specifiers that
4312/// correspond to the given base type, for use in base initialization
4313/// within a constructor.
4314static bool FindBaseInitializer(Sema &SemaRef,
4315 CXXRecordDecl *ClassDecl,
4316 QualType BaseType,
4317 const CXXBaseSpecifier *&DirectBaseSpec,
4318 const CXXBaseSpecifier *&VirtualBaseSpec) {
4319 // First, check for a direct base class.
4320 DirectBaseSpec = nullptr;
4321 for (const auto &Base : ClassDecl->bases()) {
4322 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4323 // We found a direct base of this type. That's what we're
4324 // initializing.
4325 DirectBaseSpec = &Base;
4326 break;
4327 }
4328 }
4329
4330 // Check for a virtual base class.
4331 // FIXME: We might be able to short-circuit this if we know in advance that
4332 // there are no virtual bases.
4333 VirtualBaseSpec = nullptr;
4334 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4335 // We haven't found a base yet; search the class hierarchy for a
4336 // virtual base class.
4337 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4338 /*DetectVirtual=*/false);
4339 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4340 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4341 Base: BaseType, Paths)) {
4342 for (const CXXBasePath &Path : Paths) {
4343 if (Path.back().Base->isVirtual()) {
4344 VirtualBaseSpec = Path.back().Base;
4345 break;
4346 }
4347 }
4348 }
4349 }
4350
4351 return DirectBaseSpec || VirtualBaseSpec;
4352}
4353
4354MemInitResult
4355Sema::ActOnMemInitializer(Decl *ConstructorD,
4356 Scope *S,
4357 CXXScopeSpec &SS,
4358 IdentifierInfo *MemberOrBase,
4359 ParsedType TemplateTypeTy,
4360 const DeclSpec &DS,
4361 SourceLocation IdLoc,
4362 Expr *InitList,
4363 SourceLocation EllipsisLoc) {
4364 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4365 DS, IdLoc, Init: InitList,
4366 EllipsisLoc);
4367}
4368
4369MemInitResult
4370Sema::ActOnMemInitializer(Decl *ConstructorD,
4371 Scope *S,
4372 CXXScopeSpec &SS,
4373 IdentifierInfo *MemberOrBase,
4374 ParsedType TemplateTypeTy,
4375 const DeclSpec &DS,
4376 SourceLocation IdLoc,
4377 SourceLocation LParenLoc,
4378 ArrayRef<Expr *> Args,
4379 SourceLocation RParenLoc,
4380 SourceLocation EllipsisLoc) {
4381 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4382 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4383 DS, IdLoc, Init: List, EllipsisLoc);
4384}
4385
4386namespace {
4387
4388// Callback to only accept typo corrections that can be a valid C++ member
4389// initializer: either a non-static field member or a base class.
4390class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4391public:
4392 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4393 : ClassDecl(ClassDecl) {}
4394
4395 bool ValidateCandidate(const TypoCorrection &candidate) override {
4396 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4397 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4398 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4399 return isa<TypeDecl>(Val: ND);
4400 }
4401 return false;
4402 }
4403
4404 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4405 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4406 }
4407
4408private:
4409 CXXRecordDecl *ClassDecl;
4410};
4411
4412}
4413
4414bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4415 RecordDecl *ClassDecl,
4416 const IdentifierInfo *Name) {
4417 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4418 DeclContextLookupResult::iterator Found =
4419 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4420 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4421 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4422 });
4423 // We did not find a placeholder variable
4424 if (Found == Result.end())
4425 return false;
4426 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4427 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4428 const NamedDecl *ND = *It;
4429 if (ND->getDeclContext() != ND->getDeclContext())
4430 break;
4431 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4432 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4433 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4434 }
4435 return true;
4436}
4437
4438ValueDecl *
4439Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4440 const IdentifierInfo *MemberOrBase) {
4441 ValueDecl *ND = nullptr;
4442 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4443 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4444 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4445 if (ND) {
4446 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4447 return nullptr;
4448 break;
4449 }
4450 if (!IsPlaceholder)
4451 return cast<ValueDecl>(Val: D);
4452 ND = cast<ValueDecl>(Val: D);
4453 }
4454 }
4455 return ND;
4456}
4457
4458ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4459 CXXScopeSpec &SS,
4460 ParsedType TemplateTypeTy,
4461 IdentifierInfo *MemberOrBase) {
4462 if (SS.getScopeRep() || TemplateTypeTy)
4463 return nullptr;
4464 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4465}
4466
4467MemInitResult
4468Sema::BuildMemInitializer(Decl *ConstructorD,
4469 Scope *S,
4470 CXXScopeSpec &SS,
4471 IdentifierInfo *MemberOrBase,
4472 ParsedType TemplateTypeTy,
4473 const DeclSpec &DS,
4474 SourceLocation IdLoc,
4475 Expr *Init,
4476 SourceLocation EllipsisLoc) {
4477 if (!ConstructorD || !Init)
4478 return true;
4479
4480 AdjustDeclIfTemplate(Decl&: ConstructorD);
4481
4482 CXXConstructorDecl *Constructor
4483 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4484 if (!Constructor) {
4485 // The user wrote a constructor initializer on a function that is
4486 // not a C++ constructor. Ignore the error for now, because we may
4487 // have more member initializers coming; we'll diagnose it just
4488 // once in ActOnMemInitializers.
4489 return true;
4490 }
4491
4492 CXXRecordDecl *ClassDecl = Constructor->getParent();
4493
4494 // C++ [class.base.init]p2:
4495 // Names in a mem-initializer-id are looked up in the scope of the
4496 // constructor's class and, if not found in that scope, are looked
4497 // up in the scope containing the constructor's definition.
4498 // [Note: if the constructor's class contains a member with the
4499 // same name as a direct or virtual base class of the class, a
4500 // mem-initializer-id naming the member or base class and composed
4501 // of a single identifier refers to the class member. A
4502 // mem-initializer-id for the hidden base class may be specified
4503 // using a qualified name. ]
4504
4505 // Look for a member, first.
4506 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4507 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4508 if (EllipsisLoc.isValid())
4509 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4510 << MemberOrBase
4511 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4512
4513 return BuildMemberInitializer(Member, Init, IdLoc);
4514 }
4515 // It didn't name a member, so see if it names a class.
4516 QualType BaseType;
4517 TypeSourceInfo *TInfo = nullptr;
4518
4519 if (TemplateTypeTy) {
4520 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4521 if (BaseType.isNull())
4522 return true;
4523 } else if (DS.getTypeSpecType() == TST_decltype) {
4524 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4525 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4526 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4527 return true;
4528 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4529 BaseType = GetTypeFromParser(Ty: DS.getRepAsType(), TInfo: &TInfo);
4530 if (BaseType.isNull())
4531 return true;
4532 } else {
4533 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4534 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4535
4536 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4537 if (!TyD) {
4538 if (R.isAmbiguous()) return true;
4539
4540 // We don't want access-control diagnostics here.
4541 R.suppressDiagnostics();
4542
4543 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4544 bool NotUnknownSpecialization = false;
4545 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4546 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4547 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4548
4549 if (!NotUnknownSpecialization) {
4550 // When the scope specifier can refer to a member of an unknown
4551 // specialization, we take it as a type name.
4552 BaseType = CheckTypenameType(
4553 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4554 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4555 if (BaseType.isNull())
4556 return true;
4557
4558 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4559 DependentNameTypeLoc TL =
4560 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4561 if (!TL.isNull()) {
4562 TL.setNameLoc(IdLoc);
4563 TL.setElaboratedKeywordLoc(SourceLocation());
4564 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4565 }
4566
4567 R.clear();
4568 R.setLookupName(MemberOrBase);
4569 }
4570 }
4571
4572 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4573 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4574 auto *TempSpec = cast<TemplateSpecializationType>(
4575 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4576 TemplateName TN = TempSpec->getTemplateName();
4577 for (auto const &Base : ClassDecl->bases()) {
4578 auto BaseTemplate =
4579 Base.getType()->getAs<TemplateSpecializationType>();
4580 if (BaseTemplate &&
4581 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4582 /*IgnoreDeduced=*/true)) {
4583 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4584 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4585 BaseType = Base.getType();
4586 break;
4587 }
4588 }
4589 }
4590 }
4591
4592 // If no results were found, try to correct typos.
4593 TypoCorrection Corr;
4594 MemInitializerValidatorCCC CCC(ClassDecl);
4595 if (R.empty() && BaseType.isNull() &&
4596 (Corr =
4597 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4598 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4599 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4600 // We have found a non-static data member with a similar
4601 // name to what was typed; complain and initialize that
4602 // member.
4603 diagnoseTypo(Correction: Corr,
4604 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4605 << MemberOrBase << true);
4606 return BuildMemberInitializer(Member, Init, IdLoc);
4607 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4608 const CXXBaseSpecifier *DirectBaseSpec;
4609 const CXXBaseSpecifier *VirtualBaseSpec;
4610 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4611 BaseType: Context.getTypeDeclType(Decl: Type),
4612 DirectBaseSpec, VirtualBaseSpec)) {
4613 // We have found a direct or virtual base class with a
4614 // similar name to what was typed; complain and initialize
4615 // that base class.
4616 diagnoseTypo(Correction: Corr,
4617 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4618 << MemberOrBase << false,
4619 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4620
4621 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4622 : VirtualBaseSpec;
4623 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4624 << BaseSpec->getType() << BaseSpec->getSourceRange();
4625
4626 TyD = Type;
4627 }
4628 }
4629 }
4630
4631 if (!TyD && BaseType.isNull()) {
4632 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4633 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4634 return true;
4635 }
4636 }
4637
4638 if (BaseType.isNull()) {
4639 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4640
4641 TypeLocBuilder TLB;
4642 // FIXME: This is missing building the UsingType for TyD, if any.
4643 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4644 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4645 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4646 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4647 TL.setElaboratedKeywordLoc(SourceLocation());
4648 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4649 TL.setNameLoc(IdLoc);
4650 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4651 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4652 Qualifier: SS.getScopeRep(), Decl: TN);
4653 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4654 /*ElaboratedKeywordLoc=*/SourceLocation(),
4655 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4656 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4657 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4658 Qualifier: SS.getScopeRep(), D: UD);
4659 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4660 /*ElaboratedKeywordLoc=*/SourceLocation(),
4661 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4662 } else {
4663 // FIXME: What else can appear here?
4664 assert(SS.isEmpty());
4665 BaseType = Context.getTypeDeclType(Decl: TyD);
4666 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4667 }
4668 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4669 }
4670 }
4671
4672 if (!TInfo)
4673 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4674
4675 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4676}
4677
4678MemInitResult
4679Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4680 SourceLocation IdLoc) {
4681 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4682 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4683 assert((DirectMember || IndirectMember) &&
4684 "Member must be a FieldDecl or IndirectFieldDecl");
4685
4686 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4687 return true;
4688
4689 if (Member->isInvalidDecl())
4690 return true;
4691
4692 MultiExprArg Args;
4693 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4694 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4695 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4696 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4697 } else if (auto *ParenListInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
4698 // Template instantiation reverts the elements to their syntactic form;
4699 // redo the initialization from the written arguments.
4700 Args = ParenListInit->getUserSpecifiedInitExprs();
4701 } else {
4702 // Template instantiation doesn't reconstruct ParenListExprs for us.
4703 Args = Init;
4704 }
4705
4706 SourceRange InitRange = Init->getSourceRange();
4707
4708 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4709 // Can't check initialization for a member of dependent type or when
4710 // any of the arguments are type-dependent expressions.
4711 DiscardCleanupsInEvaluationContext();
4712 } else {
4713 bool InitList = false;
4714 if (isa<InitListExpr>(Val: Init)) {
4715 InitList = true;
4716 Args = Init;
4717 }
4718
4719 // Initialize the member.
4720 InitializedEntity MemberEntity =
4721 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4722 : InitializedEntity::InitializeMember(Member: IndirectMember,
4723 Parent: nullptr);
4724 InitializationKind Kind =
4725 InitList ? InitializationKind::CreateDirectList(
4726 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4727 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4728 RParenLoc: InitRange.getEnd());
4729
4730 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4731 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4732 ResultType: nullptr);
4733 if (!MemberInit.isInvalid()) {
4734 // C++11 [class.base.init]p7:
4735 // The initialization of each base and member constitutes a
4736 // full-expression.
4737 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4738 /*DiscardedValue*/ false);
4739 }
4740
4741 if (MemberInit.isInvalid()) {
4742 // Args were sensible expressions but we couldn't initialize the member
4743 // from them. Preserve them in a RecoveryExpr instead.
4744 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4745 T: Member->getType())
4746 .get();
4747 if (!Init)
4748 return true;
4749 } else {
4750 Init = MemberInit.get();
4751 }
4752 }
4753
4754 if (DirectMember) {
4755 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4756 InitRange.getBegin(), Init,
4757 InitRange.getEnd());
4758 } else {
4759 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4760 InitRange.getBegin(), Init,
4761 InitRange.getEnd());
4762 }
4763}
4764
4765MemInitResult
4766Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4767 CXXRecordDecl *ClassDecl) {
4768 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4769 if (!LangOpts.CPlusPlus11)
4770 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4771 << TInfo->getTypeLoc().getSourceRange();
4772 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4773
4774 bool InitList = true;
4775 MultiExprArg Args = Init;
4776 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4777 InitList = false;
4778 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4779 }
4780
4781 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4782
4783 SourceRange InitRange = Init->getSourceRange();
4784 // Initialize the object.
4785 InitializedEntity DelegationEntity =
4786 InitializedEntity::InitializeDelegation(Type: ClassType);
4787 InitializationKind Kind =
4788 InitList ? InitializationKind::CreateDirectList(
4789 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4790 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4791 RParenLoc: InitRange.getEnd());
4792 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4793 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4794 Args, ResultType: nullptr);
4795 if (!DelegationInit.isInvalid()) {
4796 assert((DelegationInit.get()->containsErrors() ||
4797 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4798 "Delegating constructor with no target?");
4799
4800 // C++11 [class.base.init]p7:
4801 // The initialization of each base and member constitutes a
4802 // full-expression.
4803 DelegationInit = ActOnFinishFullExpr(
4804 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4805 }
4806
4807 if (DelegationInit.isInvalid()) {
4808 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4809 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4810 if (DelegationInit.isInvalid())
4811 return true;
4812 } else {
4813 // If we are in a dependent context, template instantiation will
4814 // perform this type-checking again. Just save the arguments that we
4815 // received in a ParenListExpr.
4816 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4817 // of the information that we have about the base
4818 // initializer. However, deconstructing the ASTs is a dicey process,
4819 // and this approach is far more likely to get the corner cases right.
4820 if (CurContext->isDependentContext())
4821 DelegationInit = Init;
4822 }
4823
4824 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4825 DelegationInit.getAs<Expr>(),
4826 InitRange.getEnd());
4827}
4828
4829MemInitResult
4830Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4831 Expr *Init, CXXRecordDecl *ClassDecl,
4832 SourceLocation EllipsisLoc) {
4833 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4834
4835 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4836 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4837 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4838
4839 // C++ [class.base.init]p2:
4840 // [...] Unless the mem-initializer-id names a nonstatic data
4841 // member of the constructor's class or a direct or virtual base
4842 // of that class, the mem-initializer is ill-formed. A
4843 // mem-initializer-list can initialize a base class using any
4844 // name that denotes that base class type.
4845
4846 // We can store the initializers in "as-written" form and delay analysis until
4847 // instantiation if the constructor is dependent. But not for dependent
4848 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4849 bool Dependent = CurContext->isDependentContext() &&
4850 (BaseType->isDependentType() || Init->isTypeDependent());
4851
4852 SourceRange InitRange = Init->getSourceRange();
4853 if (EllipsisLoc.isValid()) {
4854 // This is a pack expansion.
4855 if (!BaseType->containsUnexpandedParameterPack()) {
4856 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4857 << SourceRange(BaseLoc, InitRange.getEnd());
4858
4859 EllipsisLoc = SourceLocation();
4860 }
4861 } else {
4862 // Check for any unexpanded parameter packs.
4863 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4864 return true;
4865
4866 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4867 return true;
4868 }
4869
4870 // Check for direct and virtual base classes.
4871 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4872 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4873 if (!Dependent) {
4874 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4875 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4876
4877 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4878 VirtualBaseSpec);
4879
4880 // C++ [base.class.init]p2:
4881 // Unless the mem-initializer-id names a nonstatic data member of the
4882 // constructor's class or a direct or virtual base of that class, the
4883 // mem-initializer is ill-formed.
4884 if (!DirectBaseSpec && !VirtualBaseSpec) {
4885 // If the class has any dependent bases, then it's possible that
4886 // one of those types will resolve to the same type as
4887 // BaseType. Therefore, just treat this as a dependent base
4888 // class initialization. FIXME: Should we try to check the
4889 // initialization anyway? It seems odd.
4890 if (ClassDecl->hasAnyDependentBases())
4891 Dependent = true;
4892 else
4893 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4894 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4895 << BaseTInfo->getTypeLoc().getSourceRange();
4896 }
4897 }
4898
4899 if (Dependent) {
4900 DiscardCleanupsInEvaluationContext();
4901
4902 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4903 /*IsVirtual=*/false,
4904 InitRange.getBegin(), Init,
4905 InitRange.getEnd(), EllipsisLoc);
4906 }
4907
4908 // C++ [base.class.init]p2:
4909 // If a mem-initializer-id is ambiguous because it designates both
4910 // a direct non-virtual base class and an inherited virtual base
4911 // class, the mem-initializer is ill-formed.
4912 if (DirectBaseSpec && VirtualBaseSpec)
4913 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4914 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4915
4916 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4917 if (!BaseSpec)
4918 BaseSpec = VirtualBaseSpec;
4919
4920 // Initialize the base.
4921 bool InitList = true;
4922 MultiExprArg Args = Init;
4923 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4924 InitList = false;
4925 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4926 }
4927
4928 InitializedEntity BaseEntity =
4929 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4930 InitializationKind Kind =
4931 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4932 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4933 RParenLoc: InitRange.getEnd());
4934 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4935 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4936 if (!BaseInit.isInvalid()) {
4937 // C++11 [class.base.init]p7:
4938 // The initialization of each base and member constitutes a
4939 // full-expression.
4940 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4941 /*DiscardedValue*/ false);
4942 }
4943
4944 if (BaseInit.isInvalid()) {
4945 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4946 SubExprs: Args, T: BaseType);
4947 if (BaseInit.isInvalid())
4948 return true;
4949 } else {
4950 // If we are in a dependent context, template instantiation will
4951 // perform this type-checking again. Just save the arguments that we
4952 // received in a ParenListExpr.
4953 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4954 // of the information that we have about the base
4955 // initializer. However, deconstructing the ASTs is a dicey process,
4956 // and this approach is far more likely to get the corner cases right.
4957 if (CurContext->isDependentContext())
4958 BaseInit = Init;
4959 }
4960
4961 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4962 BaseSpec->isVirtual(),
4963 InitRange.getBegin(),
4964 BaseInit.getAs<Expr>(),
4965 InitRange.getEnd(), EllipsisLoc);
4966}
4967
4968// Create a static_cast\<T&&>(expr).
4969static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4970 QualType TargetType =
4971 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4972 Loc: SourceLocation(), Entity: DeclarationName());
4973 SourceLocation ExprLoc = E->getBeginLoc();
4974 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4975 T: TargetType, Loc: ExprLoc);
4976
4977 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4978 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4979 Parens: E->getSourceRange()).get();
4980}
4981
4982/// ImplicitInitializerKind - How an implicit base or member initializer should
4983/// initialize its base or member.
4984enum ImplicitInitializerKind {
4985 IIK_Default,
4986 IIK_Copy,
4987 IIK_Move,
4988 IIK_Inherit
4989};
4990
4991static bool
4992BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4993 ImplicitInitializerKind ImplicitInitKind,
4994 CXXBaseSpecifier *BaseSpec,
4995 bool IsInheritedVirtualBase,
4996 CXXCtorInitializer *&CXXBaseInit) {
4997 InitializedEntity InitEntity
4998 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4999 IsInheritedVirtualBase);
5000
5001 ExprResult BaseInit;
5002
5003 switch (ImplicitInitKind) {
5004 case IIK_Inherit:
5005 case IIK_Default: {
5006 InitializationKind InitKind
5007 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
5008 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5009 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5010 break;
5011 }
5012
5013 case IIK_Move:
5014 case IIK_Copy: {
5015 bool Moving = ImplicitInitKind == IIK_Move;
5016 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5017 QualType ParamType = Param->getType().getNonReferenceType();
5018
5019 Expr *CopyCtorArg =
5020 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5021 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5022 NameLoc: Constructor->getLocation(), T: ParamType,
5023 VK: VK_LValue, FoundD: nullptr);
5024
5025 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
5026
5027 // Cast to the base class to avoid ambiguities.
5028 QualType ArgTy =
5029 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
5030 Qs: ParamType.getQualifiers());
5031
5032 if (Moving) {
5033 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
5034 }
5035
5036 CXXCastPath BasePath;
5037 BasePath.push_back(Elt: BaseSpec);
5038 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
5039 CK: CK_UncheckedDerivedToBase,
5040 VK: Moving ? VK_XValue : VK_LValue,
5041 BasePath: &BasePath).get();
5042
5043 InitializationKind InitKind
5044 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
5045 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5046 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5047 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
5048 break;
5049 }
5050 }
5051
5052 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
5053 if (BaseInit.isInvalid())
5054 return true;
5055
5056 CXXBaseInit =
5057 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5058 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5059 Loc: SourceLocation()),
5060 BaseSpec->isVirtual(),
5061 SourceLocation(),
5062 BaseInit.getAs<Expr>(),
5063 SourceLocation(),
5064 SourceLocation());
5065
5066 return false;
5067}
5068
5069static bool RefersToRValueRef(Expr *MemRef) {
5070 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5071 return Referenced->getType()->isRValueReferenceType();
5072}
5073
5074static bool
5075BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5076 ImplicitInitializerKind ImplicitInitKind,
5077 FieldDecl *Field, IndirectFieldDecl *Indirect,
5078 CXXCtorInitializer *&CXXMemberInit) {
5079 if (Field->isInvalidDecl())
5080 return true;
5081
5082 SourceLocation Loc = Constructor->getLocation();
5083
5084 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5085 bool Moving = ImplicitInitKind == IIK_Move;
5086 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5087 QualType ParamType = Param->getType().getNonReferenceType();
5088
5089 // Suppress copying zero-width bitfields.
5090 if (Field->isZeroLengthBitField())
5091 return false;
5092
5093 Expr *MemberExprBase =
5094 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5095 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5096 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5097
5098 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5099
5100 if (Moving) {
5101 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5102 }
5103
5104 // Build a reference to this field within the parameter.
5105 CXXScopeSpec SS;
5106 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5107 Sema::LookupMemberName);
5108 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5109 : cast<ValueDecl>(Val: Field), AS: AS_public);
5110 MemberLookup.resolveKind();
5111 ExprResult CtorArg
5112 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5113 BaseType: ParamType, OpLoc: Loc,
5114 /*IsArrow=*/false,
5115 SS,
5116 /*TemplateKWLoc=*/SourceLocation(),
5117 /*FirstQualifierInScope=*/nullptr,
5118 R&: MemberLookup,
5119 /*TemplateArgs=*/nullptr,
5120 /*S*/nullptr);
5121 if (CtorArg.isInvalid())
5122 return true;
5123
5124 // C++11 [class.copy]p15:
5125 // - if a member m has rvalue reference type T&&, it is direct-initialized
5126 // with static_cast<T&&>(x.m);
5127 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5128 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5129 }
5130
5131 InitializedEntity Entity =
5132 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5133 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5134
5135 // Direct-initialize to use the copy constructor.
5136 InitializationKind InitKind =
5137 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5138
5139 Expr *CtorArgE = CtorArg.getAs<Expr>();
5140 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5141 ExprResult MemberInit =
5142 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5143 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5144 if (MemberInit.isInvalid())
5145 return true;
5146
5147 if (Indirect)
5148 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5149 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5150 else
5151 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5152 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5153 return false;
5154 }
5155
5156 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5157 "Unhandled implicit init kind!");
5158
5159 QualType FieldBaseElementType =
5160 SemaRef.Context.getBaseElementType(QT: Field->getType());
5161
5162 if (FieldBaseElementType->isRecordType()) {
5163 InitializedEntity InitEntity =
5164 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5165 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5166 InitializationKind InitKind =
5167 InitializationKind::CreateDefault(InitLoc: Loc);
5168
5169 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5170 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5171
5172 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5173 if (MemberInit.isInvalid())
5174 return true;
5175
5176 if (Indirect)
5177 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5178 Indirect, Loc,
5179 Loc,
5180 MemberInit.get(),
5181 Loc);
5182 else
5183 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5184 Field, Loc, Loc,
5185 MemberInit.get(),
5186 Loc);
5187 return false;
5188 }
5189
5190 if (!Field->getParent()->isUnion()) {
5191 if (FieldBaseElementType->isReferenceType()) {
5192 SemaRef.Diag(Loc: Constructor->getLocation(),
5193 DiagID: diag::err_uninitialized_member_in_ctor)
5194 << (int)Constructor->isImplicit()
5195 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5196 << Field->getDeclName();
5197 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5198 return true;
5199 }
5200
5201 if (FieldBaseElementType.isConstQualified()) {
5202 SemaRef.Diag(Loc: Constructor->getLocation(),
5203 DiagID: diag::err_uninitialized_member_in_ctor)
5204 << (int)Constructor->isImplicit()
5205 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5206 << Field->getDeclName();
5207 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5208 return true;
5209 }
5210 }
5211
5212 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5213 // ARC and Weak:
5214 // Default-initialize Objective-C pointers to NULL.
5215 CXXMemberInit
5216 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5217 Loc, Loc,
5218 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5219 Loc);
5220 return false;
5221 }
5222
5223 // Nothing to initialize.
5224 CXXMemberInit = nullptr;
5225 return false;
5226}
5227
5228namespace {
5229struct BaseAndFieldInfo {
5230 Sema &S;
5231 CXXConstructorDecl *Ctor;
5232 bool AnyErrorsInInits;
5233 ImplicitInitializerKind IIK;
5234 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5235 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5236 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5237
5238 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5239 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5240 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5241 if (Ctor->getInheritedConstructor())
5242 IIK = IIK_Inherit;
5243 else if (Generated && Ctor->isCopyConstructor())
5244 IIK = IIK_Copy;
5245 else if (Generated && Ctor->isMoveConstructor())
5246 IIK = IIK_Move;
5247 else
5248 IIK = IIK_Default;
5249 }
5250
5251 bool isImplicitCopyOrMove() const {
5252 switch (IIK) {
5253 case IIK_Copy:
5254 case IIK_Move:
5255 return true;
5256
5257 case IIK_Default:
5258 case IIK_Inherit:
5259 return false;
5260 }
5261
5262 llvm_unreachable("Invalid ImplicitInitializerKind!");
5263 }
5264
5265 bool addFieldInitializer(CXXCtorInitializer *Init) {
5266 AllToInit.push_back(Elt: Init);
5267
5268 // Check whether this initializer makes the field "used".
5269 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5270 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5271
5272 return false;
5273 }
5274
5275 bool isInactiveUnionMember(FieldDecl *Field) {
5276 RecordDecl *Record = Field->getParent();
5277 if (!Record->isUnion())
5278 return false;
5279
5280 if (FieldDecl *Active =
5281 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5282 return Active != Field->getCanonicalDecl();
5283
5284 // In an implicit copy or move constructor, ignore any in-class initializer.
5285 if (isImplicitCopyOrMove())
5286 return true;
5287
5288 // If there's no explicit initialization, the field is active only if it
5289 // has an in-class initializer...
5290 if (Field->hasInClassInitializer())
5291 return false;
5292 // ... or it's an anonymous struct or union whose class has an in-class
5293 // initializer.
5294 if (!Field->isAnonymousStructOrUnion())
5295 return true;
5296 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5297 return !FieldRD->hasInClassInitializer();
5298 }
5299
5300 /// Determine whether the given field is, or is within, a union member
5301 /// that is inactive (because there was an initializer given for a different
5302 /// member of the union, or because the union was not initialized at all).
5303 bool isWithinInactiveUnionMember(FieldDecl *Field,
5304 IndirectFieldDecl *Indirect) {
5305 if (!Indirect)
5306 return isInactiveUnionMember(Field);
5307
5308 for (auto *C : Indirect->chain()) {
5309 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5310 if (Field && isInactiveUnionMember(Field))
5311 return true;
5312 }
5313 return false;
5314 }
5315};
5316}
5317
5318/// Determine whether the given type is an incomplete or zero-lenfgth
5319/// array type.
5320static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5321 if (T->isIncompleteArrayType())
5322 return true;
5323
5324 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5325 if (ArrayT->isZeroSize())
5326 return true;
5327
5328 T = ArrayT->getElementType();
5329 }
5330
5331 return false;
5332}
5333
5334static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5335 FieldDecl *Field,
5336 IndirectFieldDecl *Indirect = nullptr) {
5337 if (Field->isInvalidDecl())
5338 return false;
5339
5340 // Overwhelmingly common case: we have a direct initializer for this field.
5341 if (CXXCtorInitializer *Init =
5342 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5343 return Info.addFieldInitializer(Init);
5344
5345 // C++11 [class.base.init]p8:
5346 // if the entity is a non-static data member that has a
5347 // brace-or-equal-initializer and either
5348 // -- the constructor's class is a union and no other variant member of that
5349 // union is designated by a mem-initializer-id or
5350 // -- the constructor's class is not a union, and, if the entity is a member
5351 // of an anonymous union, no other member of that union is designated by
5352 // a mem-initializer-id,
5353 // the entity is initialized as specified in [dcl.init].
5354 //
5355 // We also apply the same rules to handle anonymous structs within anonymous
5356 // unions.
5357 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5358 return false;
5359
5360 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5361 ExprResult DIE =
5362 SemaRef.BuildCXXCtorDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5363 if (DIE.isInvalid())
5364 return true;
5365
5366 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5367 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5368
5369 CXXCtorInitializer *Init;
5370 if (Indirect)
5371 Init = new (SemaRef.Context)
5372 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5373 SourceLocation(), DIE.get(), SourceLocation());
5374 else
5375 Init = new (SemaRef.Context)
5376 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5377 SourceLocation(), DIE.get(), SourceLocation());
5378 return Info.addFieldInitializer(Init);
5379 }
5380
5381 // Don't initialize incomplete or zero-length arrays.
5382 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5383 return false;
5384
5385 // Don't try to build an implicit initializer if there were semantic
5386 // errors in any of the initializers (and therefore we might be
5387 // missing some that the user actually wrote).
5388 if (Info.AnyErrorsInInits)
5389 return false;
5390
5391 CXXCtorInitializer *Init = nullptr;
5392 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5393 Indirect, CXXMemberInit&: Init))
5394 return true;
5395
5396 if (!Init)
5397 return false;
5398
5399 return Info.addFieldInitializer(Init);
5400}
5401
5402bool
5403Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5404 CXXCtorInitializer *Initializer) {
5405 assert(Initializer->isDelegatingInitializer());
5406 Constructor->setNumCtorInitializers(1);
5407 CXXCtorInitializer **initializer =
5408 new (Context) CXXCtorInitializer*[1];
5409 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5410 Constructor->setCtorInitializers(initializer);
5411
5412 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5413 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5414 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5415 }
5416
5417 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5418
5419 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5420
5421 return false;
5422}
5423
5424static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5425 CXXRecordDecl *Class) {
5426 if (Class->isInvalidDecl())
5427 return nullptr;
5428 if (Class->hasIrrelevantDestructor())
5429 return nullptr;
5430
5431 // Dtor might still be missing, e.g because it's invalid.
5432 return S.LookupDestructor(Class);
5433}
5434
5435static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5436 FieldDecl *Field) {
5437 if (Field->isInvalidDecl())
5438 return;
5439
5440 // Don't destroy incomplete or zero-length arrays.
5441 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5442 return;
5443
5444 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5445
5446 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5447 if (!FieldClassDecl)
5448 return;
5449
5450 // The destructor for an implicit anonymous union member is never invoked.
5451 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5452 return;
5453
5454 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5455 if (!Dtor)
5456 return;
5457
5458 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5459 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5460 << Field->getDeclName() << FieldType);
5461
5462 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5463 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5464}
5465
5466static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5467 CXXRecordDecl *ClassDecl) {
5468 if (ClassDecl->isDependentContext())
5469 return;
5470
5471 // We only potentially invoke the destructors of potentially constructed
5472 // subobjects.
5473 bool VisitVirtualBases = !ClassDecl->isAbstract();
5474
5475 // If the destructor exists and has already been marked used in the MS ABI,
5476 // then virtual base destructors have already been checked and marked used.
5477 // Skip checking them again to avoid duplicate diagnostics.
5478 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5479 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5480 if (Dtor && Dtor->isUsed())
5481 VisitVirtualBases = false;
5482 }
5483
5484 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5485
5486 // Bases.
5487 for (const auto &Base : ClassDecl->bases()) {
5488 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5489 if (!BaseClassDecl)
5490 continue;
5491
5492 // Remember direct virtual bases.
5493 if (Base.isVirtual()) {
5494 if (!VisitVirtualBases)
5495 continue;
5496 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5497 }
5498
5499 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5500 if (!Dtor)
5501 continue;
5502
5503 // FIXME: caret should be on the start of the class name
5504 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5505 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5506 << Base.getType() << Base.getSourceRange(),
5507 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5508
5509 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5510 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5511 }
5512
5513 if (VisitVirtualBases)
5514 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5515 DirectVirtualBases: &DirectVirtualBases);
5516}
5517
5518bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5519 ArrayRef<CXXCtorInitializer *> Initializers) {
5520 if (Constructor->isDependentContext()) {
5521 // Just store the initializers as written, they will be checked during
5522 // instantiation.
5523 if (!Initializers.empty()) {
5524 Constructor->setNumCtorInitializers(Initializers.size());
5525 CXXCtorInitializer **baseOrMemberInitializers =
5526 new (Context) CXXCtorInitializer*[Initializers.size()];
5527 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5528 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5529 Constructor->setCtorInitializers(baseOrMemberInitializers);
5530 }
5531
5532 // Let template instantiation know whether we had errors.
5533 if (AnyErrors)
5534 Constructor->setInvalidDecl();
5535
5536 return false;
5537 }
5538
5539 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5540
5541 // We need to build the initializer AST according to order of construction
5542 // and not what user specified in the Initializers list.
5543 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5544 if (!ClassDecl)
5545 return true;
5546
5547 bool HadError = false;
5548
5549 for (CXXCtorInitializer *Member : Initializers) {
5550 if (Member->isBaseInitializer())
5551 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5552 Member;
5553 else {
5554 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5555
5556 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5557 for (auto *C : F->chain()) {
5558 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5559 if (FD && FD->getParent()->isUnion())
5560 Info.ActiveUnionMember.insert(KV: std::make_pair(
5561 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5562 }
5563 } else if (FieldDecl *FD = Member->getMember()) {
5564 if (FD->getParent()->isUnion())
5565 Info.ActiveUnionMember.insert(KV: std::make_pair(
5566 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5567 }
5568 }
5569 }
5570
5571 // Keep track of the direct virtual bases.
5572 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5573 for (auto &I : ClassDecl->bases()) {
5574 if (I.isVirtual())
5575 DirectVBases.insert(Ptr: &I);
5576 }
5577
5578 // Push virtual bases before others.
5579 for (auto &VBase : ClassDecl->vbases()) {
5580 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5581 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5582 // [class.base.init]p7, per DR257:
5583 // A mem-initializer where the mem-initializer-id names a virtual base
5584 // class is ignored during execution of a constructor of any class that
5585 // is not the most derived class.
5586 if (ClassDecl->isAbstract()) {
5587 // FIXME: Provide a fixit to remove the base specifier. This requires
5588 // tracking the location of the associated comma for a base specifier.
5589 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5590 << VBase.getType() << ClassDecl;
5591 DiagnoseAbstractType(RD: ClassDecl);
5592 }
5593
5594 Info.AllToInit.push_back(Elt: Value);
5595 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5596 // [class.base.init]p8, per DR257:
5597 // If a given [...] base class is not named by a mem-initializer-id
5598 // [...] and the entity is not a virtual base class of an abstract
5599 // class, then [...] the entity is default-initialized.
5600 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5601 CXXCtorInitializer *CXXBaseInit;
5602 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5603 BaseSpec: &VBase, IsInheritedVirtualBase,
5604 CXXBaseInit)) {
5605 HadError = true;
5606 continue;
5607 }
5608
5609 Info.AllToInit.push_back(Elt: CXXBaseInit);
5610 }
5611 }
5612
5613 // Non-virtual bases.
5614 for (auto &Base : ClassDecl->bases()) {
5615 // Virtuals are in the virtual base list and already constructed.
5616 if (Base.isVirtual())
5617 continue;
5618
5619 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5620 Val: Base.getType()->getAsCanonical<RecordType>())) {
5621 Info.AllToInit.push_back(Elt: Value);
5622 } else if (!AnyErrors) {
5623 CXXCtorInitializer *CXXBaseInit;
5624 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5625 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5626 CXXBaseInit)) {
5627 HadError = true;
5628 continue;
5629 }
5630
5631 Info.AllToInit.push_back(Elt: CXXBaseInit);
5632 }
5633 }
5634
5635 // Fields.
5636 for (auto *Mem : ClassDecl->decls()) {
5637 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5638 // C++ [class.bit]p2:
5639 // A declaration for a bit-field that omits the identifier declares an
5640 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5641 // initialized.
5642 if (F->isUnnamedBitField())
5643 continue;
5644
5645 // If we're not generating the implicit copy/move constructor, then we'll
5646 // handle anonymous struct/union fields based on their individual
5647 // indirect fields.
5648 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5649 continue;
5650
5651 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5652 HadError = true;
5653 continue;
5654 }
5655
5656 // Beyond this point, we only consider default initialization.
5657 if (Info.isImplicitCopyOrMove())
5658 continue;
5659
5660 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5661 if (F->getType()->isIncompleteArrayType()) {
5662 assert(ClassDecl->hasFlexibleArrayMember() &&
5663 "Incomplete array type is not valid");
5664 continue;
5665 }
5666
5667 // Initialize each field of an anonymous struct individually.
5668 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5669 HadError = true;
5670
5671 continue;
5672 }
5673 }
5674
5675 unsigned NumInitializers = Info.AllToInit.size();
5676 if (NumInitializers > 0) {
5677 Constructor->setNumCtorInitializers(NumInitializers);
5678 CXXCtorInitializer **baseOrMemberInitializers =
5679 new (Context) CXXCtorInitializer*[NumInitializers];
5680 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5681 n: NumInitializers * sizeof(CXXCtorInitializer*));
5682 Constructor->setCtorInitializers(baseOrMemberInitializers);
5683
5684 SourceLocation Location = Constructor->getLocation();
5685
5686 // Constructors implicitly reference the base and member
5687 // destructors.
5688
5689 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5690 FieldDecl *Field = Initializer->getAnyMember();
5691 if (!Field)
5692 continue;
5693
5694 // C++ [class.base.init]p12:
5695 // In a non-delegating constructor, the destructor for each
5696 // potentially constructed subobject of class type is potentially
5697 // invoked.
5698 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5699 }
5700
5701 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5702 }
5703
5704 return HadError;
5705}
5706
5707static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5708 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5709 const RecordDecl *RD = RT->getDecl();
5710 if (RD->isAnonymousStructOrUnion()) {
5711 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5712 PopulateKeysForFields(Field, IdealInits);
5713 return;
5714 }
5715 }
5716 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5717}
5718
5719static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5720 return Context.getCanonicalType(T: BaseType).getTypePtr();
5721}
5722
5723static const void *GetKeyForMember(ASTContext &Context,
5724 CXXCtorInitializer *Member) {
5725 if (!Member->isAnyMemberInitializer())
5726 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5727
5728 return Member->getAnyMember()->getCanonicalDecl();
5729}
5730
5731static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5732 const CXXCtorInitializer *Previous,
5733 const CXXCtorInitializer *Current) {
5734 if (Previous->isAnyMemberInitializer())
5735 Diag << 0 << Previous->getAnyMember();
5736 else
5737 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5738
5739 if (Current->isAnyMemberInitializer())
5740 Diag << 0 << Current->getAnyMember();
5741 else
5742 Diag << 1 << Current->getTypeSourceInfo()->getType();
5743}
5744
5745static void DiagnoseBaseOrMemInitializerOrder(
5746 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5747 ArrayRef<CXXCtorInitializer *> Inits) {
5748 if (Constructor->getDeclContext()->isDependentContext())
5749 return;
5750
5751 // Don't check initializers order unless the warning is enabled at the
5752 // location of at least one initializer.
5753 bool ShouldCheckOrder = false;
5754 for (const CXXCtorInitializer *Init : Inits) {
5755 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5756 Loc: Init->getSourceLocation())) {
5757 ShouldCheckOrder = true;
5758 break;
5759 }
5760 }
5761 if (!ShouldCheckOrder)
5762 return;
5763
5764 // Build the list of bases and members in the order that they'll
5765 // actually be initialized. The explicit initializers should be in
5766 // this same order but may be missing things.
5767 SmallVector<const void*, 32> IdealInitKeys;
5768
5769 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5770
5771 // 1. Virtual bases.
5772 for (const auto &VBase : ClassDecl->vbases())
5773 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5774
5775 // 2. Non-virtual bases.
5776 for (const auto &Base : ClassDecl->bases()) {
5777 if (Base.isVirtual())
5778 continue;
5779 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5780 }
5781
5782 // 3. Direct fields.
5783 for (auto *Field : ClassDecl->fields()) {
5784 if (Field->isUnnamedBitField())
5785 continue;
5786
5787 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5788 }
5789
5790 unsigned NumIdealInits = IdealInitKeys.size();
5791 unsigned IdealIndex = 0;
5792
5793 // Track initializers that are in an incorrect order for either a warning or
5794 // note if multiple ones occur.
5795 SmallVector<unsigned> WarnIndexes;
5796 // Correlates the index of an initializer in the init-list to the index of
5797 // the field/base in the class.
5798 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5799
5800 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5801 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5802
5803 // Scan forward to try to find this initializer in the idealized
5804 // initializers list.
5805 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5806 if (InitKey == IdealInitKeys[IdealIndex])
5807 break;
5808
5809 // If we didn't find this initializer, it must be because we
5810 // scanned past it on a previous iteration. That can only
5811 // happen if we're out of order; emit a warning.
5812 if (IdealIndex == NumIdealInits && InitIndex) {
5813 WarnIndexes.push_back(Elt: InitIndex);
5814
5815 // Move back to the initializer's location in the ideal list.
5816 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5817 if (InitKey == IdealInitKeys[IdealIndex])
5818 break;
5819
5820 assert(IdealIndex < NumIdealInits &&
5821 "initializer not found in initializer list");
5822 }
5823 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5824 }
5825
5826 if (WarnIndexes.empty())
5827 return;
5828
5829 // Sort based on the ideal order, first in the pair.
5830 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5831
5832 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5833 // emit the diagnostic before we can try adding notes.
5834 {
5835 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5836 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5837 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5838 : diag::warn_some_initializers_out_of_order);
5839
5840 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5841 if (CorrelatedInitOrder[I].second == I)
5842 continue;
5843 // Ideally we would be using InsertFromRange here, but clang doesn't
5844 // appear to handle InsertFromRange correctly when the source range is
5845 // modified by another fix-it.
5846 D << FixItHint::CreateReplacement(
5847 RemoveRange: Inits[I]->getSourceRange(),
5848 Code: Lexer::getSourceText(
5849 Range: CharSourceRange::getTokenRange(
5850 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5851 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5852 }
5853
5854 // If there is only 1 item out of order, the warning expects the name and
5855 // type of each being added to it.
5856 if (WarnIndexes.size() == 1) {
5857 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5858 Current: Inits[WarnIndexes.front()]);
5859 return;
5860 }
5861 }
5862 // More than 1 item to warn, create notes letting the user know which ones
5863 // are bad.
5864 for (unsigned WarnIndex : WarnIndexes) {
5865 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5866 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5867 DiagID: diag::note_initializer_out_of_order);
5868 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5869 D << PrevInit->getSourceRange();
5870 }
5871}
5872
5873namespace {
5874bool CheckRedundantInit(Sema &S,
5875 CXXCtorInitializer *Init,
5876 CXXCtorInitializer *&PrevInit) {
5877 if (!PrevInit) {
5878 PrevInit = Init;
5879 return false;
5880 }
5881
5882 if (FieldDecl *Field = Init->getAnyMember())
5883 S.Diag(Loc: Init->getSourceLocation(),
5884 DiagID: diag::err_multiple_mem_initialization)
5885 << Field->getDeclName()
5886 << Init->getSourceRange();
5887 else {
5888 const Type *BaseClass = Init->getBaseClass();
5889 assert(BaseClass && "neither field nor base");
5890 S.Diag(Loc: Init->getSourceLocation(),
5891 DiagID: diag::err_multiple_base_initialization)
5892 << QualType(BaseClass, 0)
5893 << Init->getSourceRange();
5894 }
5895 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5896 << 0 << PrevInit->getSourceRange();
5897
5898 return true;
5899}
5900
5901typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5902typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5903
5904bool CheckRedundantUnionInit(Sema &S,
5905 CXXCtorInitializer *Init,
5906 RedundantUnionMap &Unions) {
5907 FieldDecl *Field = Init->getAnyMember();
5908 RecordDecl *Parent = Field->getParent();
5909 NamedDecl *Child = Field;
5910
5911 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5912 if (Parent->isUnion()) {
5913 UnionEntry &En = Unions[Parent];
5914 if (En.first && En.first != Child) {
5915 S.Diag(Loc: Init->getSourceLocation(),
5916 DiagID: diag::err_multiple_mem_union_initialization)
5917 << Field->getDeclName()
5918 << Init->getSourceRange();
5919 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5920 << 0 << En.second->getSourceRange();
5921 return true;
5922 }
5923 if (!En.first) {
5924 En.first = Child;
5925 En.second = Init;
5926 }
5927 if (!Parent->isAnonymousStructOrUnion())
5928 return false;
5929 }
5930
5931 Child = Parent;
5932 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5933 }
5934
5935 return false;
5936}
5937} // namespace
5938
5939void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5940 SourceLocation ColonLoc,
5941 ArrayRef<CXXCtorInitializer*> MemInits,
5942 bool AnyErrors) {
5943 if (!ConstructorDecl)
5944 return;
5945
5946 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5947
5948 CXXConstructorDecl *Constructor
5949 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5950
5951 if (!Constructor) {
5952 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5953 return;
5954 }
5955
5956 // Mapping for the duplicate initializers check.
5957 // For member initializers, this is keyed with a FieldDecl*.
5958 // For base initializers, this is keyed with a Type*.
5959 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5960
5961 // Mapping for the inconsistent anonymous-union initializers check.
5962 RedundantUnionMap MemberUnions;
5963
5964 bool HadError = false;
5965 for (unsigned i = 0; i < MemInits.size(); i++) {
5966 CXXCtorInitializer *Init = MemInits[i];
5967
5968 // Set the source order index.
5969 Init->setSourceOrder(i);
5970
5971 if (Init->isAnyMemberInitializer()) {
5972 const void *Key = GetKeyForMember(Context, Member: Init);
5973 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5974 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5975 HadError = true;
5976 } else if (Init->isBaseInitializer()) {
5977 const void *Key = GetKeyForMember(Context, Member: Init);
5978 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5979 HadError = true;
5980 } else {
5981 assert(Init->isDelegatingInitializer());
5982 // This must be the only initializer
5983 if (MemInits.size() != 1) {
5984 Diag(Loc: Init->getSourceLocation(),
5985 DiagID: diag::err_delegating_initializer_alone)
5986 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5987 // We will treat this as being the only initializer.
5988 }
5989 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5990 // Return immediately as the initializer is set.
5991 return;
5992 }
5993 }
5994
5995 if (HadError)
5996 return;
5997
5998 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5999
6000 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
6001
6002 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6003}
6004
6005void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
6006 CXXRecordDecl *ClassDecl) {
6007 // Ignore dependent contexts. Also ignore unions, since their members never
6008 // have destructors implicitly called.
6009 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
6010 return;
6011
6012 // FIXME: all the access-control diagnostics are positioned on the
6013 // field/base declaration. That's probably good; that said, the
6014 // user might reasonably want to know why the destructor is being
6015 // emitted, and we currently don't say.
6016
6017 // Non-static data members.
6018 for (auto *Field : ClassDecl->fields()) {
6019 MarkFieldDestructorReferenced(S&: *this, Location, Field);
6020 }
6021
6022 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
6023}
6024
6025void Sema::MarkVirtualBaseDestructorsReferenced(
6026 SourceLocation Location, CXXRecordDecl *ClassDecl,
6027 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6028 // Virtual bases.
6029 for (const auto &VBase : ClassDecl->vbases()) {
6030 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6031 if (!BaseClassDecl)
6032 continue;
6033
6034 // Ignore already visited direct virtual bases.
6035 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
6036 continue;
6037
6038 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
6039 if (!Dtor)
6040 continue;
6041
6042 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
6043 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
6044 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
6045 << CT << VBase.getType(),
6046 objectType: CT) == AR_accessible) {
6047 CheckDerivedToBaseConversion(
6048 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
6049 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
6050 }
6051
6052 MarkFunctionReferenced(Loc: Location, Func: Dtor);
6053 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
6054 }
6055}
6056
6057void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
6058 if (!CDtorDecl)
6059 return;
6060
6061 if (CXXConstructorDecl *Constructor
6062 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6063 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6064 !ClassDecl || ClassDecl->isInvalidDecl()) {
6065 return;
6066 }
6067 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6068 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6069 }
6070}
6071
6072bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6073 if (!getLangOpts().CPlusPlus)
6074 return false;
6075
6076 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6077 if (!RD)
6078 return false;
6079
6080 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6081 // class template specialization here, but doing so breaks a lot of code.
6082
6083 // We can't answer whether something is abstract until it has a
6084 // definition. If it's currently being defined, we'll walk back
6085 // over all the declarations when we have a full definition.
6086 const CXXRecordDecl *Def = RD->getDefinition();
6087 if (!Def || Def->isBeingDefined())
6088 return false;
6089
6090 return RD->isAbstract();
6091}
6092
6093bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6094 TypeDiagnoser &Diagnoser) {
6095 if (!isAbstractType(Loc, T))
6096 return false;
6097
6098 T = Context.getBaseElementType(QT: T);
6099 Diagnoser.diagnose(S&: *this, Loc, T);
6100 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6101 return true;
6102}
6103
6104void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6105 // Check if we've already emitted the list of pure virtual functions
6106 // for this class.
6107 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6108 return;
6109
6110 // If the diagnostic is suppressed, don't emit the notes. We're only
6111 // going to emit them once, so try to attach them to a diagnostic we're
6112 // actually going to show.
6113 if (Diags.isLastDiagnosticIgnored())
6114 return;
6115
6116 CXXFinalOverriderMap FinalOverriders;
6117 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6118
6119 // Keep a set of seen pure methods so we won't diagnose the same method
6120 // more than once.
6121 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6122
6123 for (const auto &M : FinalOverriders) {
6124 for (const auto &SO : M.second) {
6125 // C++ [class.abstract]p4:
6126 // A class is abstract if it contains or inherits at least one
6127 // pure virtual function for which the final overrider is pure
6128 // virtual.
6129
6130 if (SO.second.size() != 1)
6131 continue;
6132 const CXXMethodDecl *Method = SO.second.front().Method;
6133
6134 if (!Method->isPureVirtual())
6135 continue;
6136
6137 if (!SeenPureMethods.insert(Ptr: Method).second)
6138 continue;
6139
6140 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6141 << Method->getDeclName() << RD->getDeclName();
6142 }
6143 }
6144
6145 if (!PureVirtualClassDiagSet)
6146 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6147 PureVirtualClassDiagSet->insert(Ptr: RD);
6148}
6149
6150namespace {
6151struct AbstractUsageInfo {
6152 Sema &S;
6153 CXXRecordDecl *Record;
6154 CanQualType AbstractType;
6155 bool Invalid;
6156
6157 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6158 : S(S), Record(Record),
6159 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6160
6161 void DiagnoseAbstractType() {
6162 if (Invalid) return;
6163 S.DiagnoseAbstractType(RD: Record);
6164 Invalid = true;
6165 }
6166
6167 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6168};
6169
6170struct CheckAbstractUsage {
6171 AbstractUsageInfo &Info;
6172 const NamedDecl *Ctx;
6173
6174 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6175 : Info(Info), Ctx(Ctx) {}
6176
6177 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6178 switch (TL.getTypeLocClass()) {
6179#define ABSTRACT_TYPELOC(CLASS, PARENT)
6180#define TYPELOC(CLASS, PARENT) \
6181 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6182#include "clang/AST/TypeLocNodes.def"
6183 }
6184 }
6185
6186 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6187 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6188 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6189 if (!TL.getParam(i: I))
6190 continue;
6191
6192 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6193 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6194 }
6195 }
6196
6197 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6198 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6199 }
6200
6201 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6202 // Visit the type parameters from a permissive context.
6203 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6204 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6205 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6206 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6207 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6208 // TODO: other template argument types?
6209 }
6210 }
6211
6212 // Visit pointee types from a permissive context.
6213#define CheckPolymorphic(Type) \
6214 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6215 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6216 }
6217 CheckPolymorphic(PointerTypeLoc)
6218 CheckPolymorphic(ReferenceTypeLoc)
6219 CheckPolymorphic(MemberPointerTypeLoc)
6220 CheckPolymorphic(BlockPointerTypeLoc)
6221 CheckPolymorphic(AtomicTypeLoc)
6222
6223 /// Handle all the types we haven't given a more specific
6224 /// implementation for above.
6225 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6226 // Every other kind of type that we haven't called out already
6227 // that has an inner type is either (1) sugar or (2) contains that
6228 // inner type in some way as a subobject.
6229 if (TypeLoc Next = TL.getNextTypeLoc())
6230 return Visit(TL: Next, Sel);
6231
6232 // If there's no inner type and we're in a permissive context,
6233 // don't diagnose.
6234 if (Sel == Sema::AbstractNone) return;
6235
6236 // Check whether the type matches the abstract type.
6237 QualType T = TL.getType();
6238 if (T->isArrayType()) {
6239 Sel = Sema::AbstractArrayType;
6240 T = Info.S.Context.getBaseElementType(QT: T);
6241 }
6242 CanQualType CT = T->getCanonicalTypeUnqualified();
6243 if (CT != Info.AbstractType) return;
6244
6245 // It matched; do some magic.
6246 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6247 if (Sel == Sema::AbstractArrayType) {
6248 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6249 << T << TL.getSourceRange();
6250 } else {
6251 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6252 << Sel << T << TL.getSourceRange();
6253 }
6254 Info.DiagnoseAbstractType();
6255 }
6256};
6257
6258void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6259 Sema::AbstractDiagSelID Sel) {
6260 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6261}
6262
6263}
6264
6265/// Check for invalid uses of an abstract type in a function declaration.
6266static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6267 FunctionDecl *FD) {
6268 // Only definitions are required to refer to complete and
6269 // non-abstract types.
6270 if (!FD->doesThisDeclarationHaveABody())
6271 return;
6272
6273 // For safety's sake, just ignore it if we don't have type source
6274 // information. This should never happen for non-implicit methods,
6275 // but...
6276 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6277 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6278}
6279
6280/// Check for invalid uses of an abstract type in a variable0 declaration.
6281static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6282 VarDecl *VD) {
6283 // No need to do the check on definitions, which require that
6284 // the type is complete.
6285 if (VD->isThisDeclarationADefinition())
6286 return;
6287
6288 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6289 Sel: Sema::AbstractVariableType);
6290}
6291
6292/// Check for invalid uses of an abstract type within a class definition.
6293static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6294 CXXRecordDecl *RD) {
6295 for (auto *D : RD->decls()) {
6296 if (D->isImplicit()) continue;
6297
6298 // Step through friends to the befriended declaration.
6299 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6300 D = FD->getFriendDecl();
6301 if (!D) continue;
6302 }
6303
6304 // Functions and function templates.
6305 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6306 CheckAbstractClassUsage(Info, FD);
6307 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6308 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6309
6310 // Fields and static variables.
6311 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6312 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6313 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6314 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6315 CheckAbstractClassUsage(Info, VD);
6316 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6317 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6318
6319 // Nested classes and class templates.
6320 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6321 CheckAbstractClassUsage(Info, RD);
6322 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6323 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6324 }
6325 }
6326}
6327
6328static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6329 Attr *ClassAttr = getDLLAttr(D: Class);
6330 if (!ClassAttr)
6331 return;
6332
6333 assert(ClassAttr->getKind() == attr::DLLExport);
6334
6335 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6336
6337 if (TSK == TSK_ExplicitInstantiationDeclaration)
6338 // Don't go any further if this is just an explicit instantiation
6339 // declaration.
6340 return;
6341
6342 // Add a context note to explain how we got to any diagnostics produced below.
6343 struct MarkingClassDllexported {
6344 Sema &S;
6345 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6346 SourceLocation AttrLoc)
6347 : S(S) {
6348 Sema::CodeSynthesisContext Ctx;
6349 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6350 Ctx.PointOfInstantiation = AttrLoc;
6351 Ctx.Entity = Class;
6352 S.pushCodeSynthesisContext(Ctx);
6353 }
6354 ~MarkingClassDllexported() {
6355 S.popCodeSynthesisContext();
6356 }
6357 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6358
6359 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6360 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6361
6362 for (Decl *Member : Class->decls()) {
6363 // Skip members that were not marked exported.
6364 if (!Member->hasAttr<DLLExportAttr>())
6365 continue;
6366
6367 // Defined static variables that are members of an exported base
6368 // class must be marked export too.
6369 auto *VD = dyn_cast<VarDecl>(Val: Member);
6370 if (VD && VD->getStorageClass() == SC_Static &&
6371 TSK == TSK_ImplicitInstantiation)
6372 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6373
6374 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6375 if (!MD)
6376 continue;
6377
6378 if (MD->isUserProvided()) {
6379 // Instantiate non-default class member functions ...
6380
6381 // .. except for certain kinds of template specializations.
6382 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6383 continue;
6384
6385 // If this is an MS ABI dllexport default constructor, instantiate any
6386 // default arguments.
6387 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6388 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6389 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6390 S.BuildCtorClosureDefaultArgs(
6391 Loc: CD->getAttr<DLLExportAttr>()->getLocation(), Ctor: CD);
6392 }
6393 }
6394
6395 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6396
6397 // The function will be passed to the consumer when its definition is
6398 // encountered.
6399 } else if (MD->isExplicitlyDefaulted()) {
6400 // Synthesize and instantiate explicitly defaulted methods.
6401 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6402
6403 if (TSK != TSK_ExplicitInstantiationDefinition) {
6404 // Except for explicit instantiation defs, we will not see the
6405 // definition again later, so pass it to the consumer now.
6406 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6407 }
6408 } else if (!MD->isTrivial() ||
6409 MD->isCopyAssignmentOperator() ||
6410 MD->isMoveAssignmentOperator()) {
6411 // Synthesize and instantiate non-trivial implicit methods, and the copy
6412 // and move assignment operators. The latter are exported even if they
6413 // are trivial, because the address of an operator can be taken and
6414 // should compare equal across libraries.
6415 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6416
6417 // There is no later point when we will see the definition of this
6418 // function, so pass it to the consumer now.
6419 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6420 }
6421 }
6422}
6423
6424static void checkForMultipleExportedDefaultConstructors(Sema &S,
6425 CXXRecordDecl *Class) {
6426 // Only the MS ABI has default constructor closures, so we don't need to do
6427 // this semantic checking anywhere else.
6428 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6429 return;
6430
6431 if (Class->isInvalidDecl())
6432 return;
6433
6434 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6435 for (Decl *Member : Class->decls()) {
6436 // Nested classes finish delayed default argument parsing with the outermost
6437 // class, so check each nested definition here.
6438 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
6439 if (NestedClass->isThisDeclarationADefinition())
6440 checkForMultipleExportedDefaultConstructors(S, Class: NestedClass);
6441 continue;
6442 }
6443
6444 // Look for exported default constructors.
6445 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6446 if (!CD || !CD->isDefaultConstructor())
6447 continue;
6448 auto *Attr = CD->getAttr<DLLExportAttr>();
6449 if (!Attr)
6450 continue;
6451
6452 // If the class is non-dependent, mark the default arguments as ODR-used so
6453 // that we can properly codegen the constructor closure.
6454 if (!Class->isDependentContext()) {
6455 S.BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor: CD);
6456 S.DiscardCleanupsInEvaluationContext();
6457 }
6458
6459 if (LastExportedDefaultCtor) {
6460 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6461 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6462 << Class;
6463 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6464 << CD->getDeclName();
6465 return;
6466 }
6467 LastExportedDefaultCtor = CD;
6468 }
6469}
6470
6471static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6472 CXXRecordDecl *Class) {
6473 bool ErrorReported = false;
6474 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6475 ClassTemplateDecl *TD) {
6476 if (ErrorReported)
6477 return;
6478 S.Diag(Loc: TD->getLocation(),
6479 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6480 << /*surface*/ 0 << TD;
6481 ErrorReported = true;
6482 };
6483
6484 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6485 if (!TD) {
6486 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6487 if (!SD) {
6488 S.Diag(Loc: Class->getLocation(),
6489 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6490 << /*surface*/ 0 << Class;
6491 S.Diag(Loc: Class->getLocation(),
6492 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6493 << Class;
6494 return;
6495 }
6496 TD = SD->getSpecializedTemplate();
6497 }
6498
6499 TemplateParameterList *Params = TD->getTemplateParameters();
6500 unsigned N = Params->size();
6501
6502 if (N != 2) {
6503 reportIllegalClassTemplate(S, TD);
6504 S.Diag(Loc: TD->getLocation(),
6505 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6506 << TD << 2;
6507 }
6508 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6509 reportIllegalClassTemplate(S, TD);
6510 S.Diag(Loc: TD->getLocation(),
6511 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6512 << TD << /*1st*/ 0 << /*type*/ 0;
6513 }
6514 if (N > 1) {
6515 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6516 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6517 reportIllegalClassTemplate(S, TD);
6518 S.Diag(Loc: TD->getLocation(),
6519 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6520 << TD << /*2nd*/ 1 << /*integer*/ 1;
6521 }
6522 }
6523}
6524
6525static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6526 CXXRecordDecl *Class) {
6527 bool ErrorReported = false;
6528 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6529 ClassTemplateDecl *TD) {
6530 if (ErrorReported)
6531 return;
6532 S.Diag(Loc: TD->getLocation(),
6533 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6534 << /*texture*/ 1 << TD;
6535 ErrorReported = true;
6536 };
6537
6538 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6539 if (!TD) {
6540 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6541 if (!SD) {
6542 S.Diag(Loc: Class->getLocation(),
6543 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6544 << /*texture*/ 1 << Class;
6545 S.Diag(Loc: Class->getLocation(),
6546 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6547 << Class;
6548 return;
6549 }
6550 TD = SD->getSpecializedTemplate();
6551 }
6552
6553 TemplateParameterList *Params = TD->getTemplateParameters();
6554 unsigned N = Params->size();
6555
6556 if (N != 3) {
6557 reportIllegalClassTemplate(S, TD);
6558 S.Diag(Loc: TD->getLocation(),
6559 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6560 << TD << 3;
6561 }
6562 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6563 reportIllegalClassTemplate(S, TD);
6564 S.Diag(Loc: TD->getLocation(),
6565 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6566 << TD << /*1st*/ 0 << /*type*/ 0;
6567 }
6568 if (N > 1) {
6569 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6570 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6571 reportIllegalClassTemplate(S, TD);
6572 S.Diag(Loc: TD->getLocation(),
6573 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6574 << TD << /*2nd*/ 1 << /*integer*/ 1;
6575 }
6576 }
6577 if (N > 2) {
6578 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6579 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6580 reportIllegalClassTemplate(S, TD);
6581 S.Diag(Loc: TD->getLocation(),
6582 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6583 << TD << /*3rd*/ 2 << /*integer*/ 1;
6584 }
6585 }
6586}
6587
6588void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6589 // Mark any compiler-generated routines with the implicit code_seg attribute.
6590 for (auto *Method : Class->methods()) {
6591 if (Method->isUserProvided())
6592 continue;
6593 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6594 Method->addAttr(A);
6595 }
6596}
6597
6598void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6599 Attr *ClassAttr = getDLLAttr(D: Class);
6600
6601 // MSVC inherits DLL attributes to partial class template specializations.
6602 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6603 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6604 if (Attr *TemplateAttr =
6605 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6606 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6607 A->setInherited(true);
6608 ClassAttr = A;
6609 }
6610 }
6611 }
6612
6613 if (!ClassAttr)
6614 return;
6615
6616 // MSVC allows imported or exported template classes that have UniqueExternal
6617 // linkage. This occurs when the template class has been instantiated with
6618 // a template parameter which itself has internal linkage.
6619 // We drop the attribute to avoid exporting or importing any members.
6620 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6621 Context.getTargetInfo().getTriple().isPS()) &&
6622 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6623 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6624 return;
6625 }
6626
6627 if (!Class->isExternallyVisible()) {
6628 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6629 << Class << ClassAttr;
6630 return;
6631 }
6632
6633 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6634 !ClassAttr->isInherited()) {
6635 // Diagnose dll attributes on members of class with dll attribute.
6636 for (Decl *Member : Class->decls()) {
6637 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6638 continue;
6639 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6640 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6641 continue;
6642
6643 Diag(Loc: MemberAttr->getLocation(),
6644 DiagID: diag::err_attribute_dll_member_of_dll_class)
6645 << MemberAttr << ClassAttr;
6646 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6647 Member->setInvalidDecl();
6648 }
6649 }
6650
6651 if (Class->getDescribedClassTemplate())
6652 // Don't inherit dll attribute until the template is instantiated.
6653 return;
6654
6655 // The class is either imported or exported.
6656 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6657
6658 // Check if this was a dllimport attribute propagated from a derived class to
6659 // a base class template specialization. We don't apply these attributes to
6660 // static data members.
6661 const bool PropagatedImport =
6662 !ClassExported &&
6663 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6664
6665 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6666
6667 // Ignore explicit dllexport on explicit class template instantiation
6668 // declarations, except in MinGW mode.
6669 if (ClassExported && !ClassAttr->isInherited() &&
6670 TSK == TSK_ExplicitInstantiationDeclaration &&
6671 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6672 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6673 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6674 Class->dropAttr<DLLExportAttr>();
6675 }
6676 return;
6677 }
6678
6679 // Force declaration of implicit members so they can inherit the attribute.
6680 ForceDeclarationOfImplicitMembers(Class);
6681
6682 // Inherited constructors are created lazily; force their creation now so the
6683 // loop below can propagate the DLL attribute to them.
6684 if (ClassExported && getLangOpts().DllExportInlines) {
6685 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6686 for (Decl *D : Class->decls())
6687 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6688 Shadows.push_back(Elt: S);
6689 for (ConstructorUsingShadowDecl *S : Shadows) {
6690 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6691 if (!BC || BC->isDeleted())
6692 continue;
6693 // Skip constructors whose requires clause is not satisfied.
6694 // Normally overload resolution filters these, but we are bypassing
6695 // it to eagerly create inherited constructors for dllexport.
6696 if (BC->getTrailingRequiresClause()) {
6697 ConstraintSatisfaction Satisfaction;
6698 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6699 !Satisfaction.IsSatisfied)
6700 continue;
6701 }
6702 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6703 }
6704 }
6705
6706 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6707 // seem to be true in practice?
6708
6709 for (Decl *Member : Class->decls()) {
6710 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6711 continue;
6712
6713 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6714 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6715
6716 // Only methods and static fields inherit the attributes.
6717 if (!VD && !MD)
6718 continue;
6719
6720 if (MD) {
6721 // Don't process deleted methods.
6722 if (MD->isDeleted())
6723 continue;
6724
6725 if (ClassExported && getLangOpts().DllExportInlines) {
6726 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6727 if (CD && CD->getInheritedConstructor()) {
6728 // Inherited constructors already had their base constructor's
6729 // constraints checked before creation via
6730 // findInheritingConstructor, so only ABI-compatibility checks
6731 // are needed here.
6732 //
6733 // Don't export inherited constructors whose parameters prevent
6734 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6735 // CodeGen) returns false, Clang inlines the constructor body
6736 // instead of emitting a forwarding thunk, producing code that
6737 // is not ABI-compatible with MSVC. Suppress the export and warn
6738 // so the user gets a linker error rather than a silent runtime
6739 // mismatch.
6740 if (CD->isVariadic()) {
6741 Diag(Loc: CD->getLocation(),
6742 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6743 << /*variadic=*/0;
6744 continue;
6745 }
6746 if (Context.getTargetInfo()
6747 .getCXXABI()
6748 .areArgsDestroyedLeftToRightInCallee()) {
6749 bool HasCalleeCleanupParam = false;
6750 for (const ParmVarDecl *P : CD->parameters())
6751 if (P->needsDestruction(Ctx: Context)) {
6752 HasCalleeCleanupParam = true;
6753 break;
6754 }
6755 if (HasCalleeCleanupParam) {
6756 Diag(Loc: CD->getLocation(),
6757 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6758 << /*callee-cleanup=*/1;
6759 continue;
6760 }
6761 }
6762 } else if (MD->getTrailingRequiresClause()) {
6763 // Don't export methods whose requires clause is not satisfied.
6764 // For class template specializations, member constraints may
6765 // depend on template arguments and an unsatisfied constraint
6766 // means the member should not be available in this
6767 // specialization.
6768 ConstraintSatisfaction Satisfaction;
6769 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6770 !Satisfaction.IsSatisfied)
6771 continue;
6772 }
6773 }
6774
6775 if (MD->isInlined()) {
6776 // MinGW does not import or export inline methods. But do it for
6777 // template instantiations and inherited constructors (which are
6778 // marked inline but must be exported to match MSVC behavior).
6779 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6780 TSK != TSK_ExplicitInstantiationDeclaration &&
6781 TSK != TSK_ExplicitInstantiationDefinition) {
6782 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6783 !CD || !CD->getInheritedConstructor())
6784 continue;
6785 }
6786
6787 // MSVC versions before 2015 don't export the move assignment operators
6788 // and move constructor, so don't attempt to import/export them if
6789 // we have a definition.
6790 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6791 if ((MD->isMoveAssignmentOperator() ||
6792 (Ctor && Ctor->isMoveConstructor())) &&
6793 getLangOpts().isCompatibleWithMSVC() &&
6794 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6795 continue;
6796
6797 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6798 // operator is exported anyway.
6799 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6800 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6801 continue;
6802 }
6803 }
6804
6805 // Don't apply dllimport attributes to static data members of class template
6806 // instantiations when the attribute is propagated from a derived class.
6807 if (VD && PropagatedImport)
6808 continue;
6809
6810 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6811 continue;
6812
6813 if (!getDLLAttr(D: Member)) {
6814 InheritableAttr *NewAttr = nullptr;
6815
6816 // Do not export/import inline function when -fno-dllexport-inlines is
6817 // passed. But add attribute for later local static var check.
6818 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6819 TSK != TSK_ExplicitInstantiationDeclaration &&
6820 TSK != TSK_ExplicitInstantiationDefinition) {
6821 if (ClassExported) {
6822 NewAttr = ::new (getASTContext())
6823 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6824 } else {
6825 NewAttr = ::new (getASTContext())
6826 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6827 }
6828 } else {
6829 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6830 }
6831
6832 NewAttr->setInherited(true);
6833 Member->addAttr(A: NewAttr);
6834
6835 if (MD) {
6836 // Propagate DLLAttr to friend re-declarations of MD that have already
6837 // been constructed.
6838 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6839 FD = FD->getPreviousDecl()) {
6840 if (FD->getFriendObjectKind() == Decl::FOK_None)
6841 continue;
6842 assert(!getDLLAttr(FD) &&
6843 "friend re-decl should not already have a DLLAttr");
6844 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6845 NewAttr->setInherited(true);
6846 FD->addAttr(A: NewAttr);
6847 }
6848 }
6849 }
6850 }
6851
6852 if (ClassExported)
6853 DelayedDllExportClasses.push_back(Elt: Class);
6854}
6855
6856void Sema::propagateDLLAttrToBaseClassTemplate(
6857 CXXRecordDecl *Class, Attr *ClassAttr,
6858 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6859 if (getDLLAttr(
6860 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6861 // If the base class template has a DLL attribute, don't try to change it.
6862 return;
6863 }
6864
6865 auto TSK = BaseTemplateSpec->getSpecializationKind();
6866 if (!getDLLAttr(D: BaseTemplateSpec) &&
6867 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6868 TSK == TSK_ImplicitInstantiation)) {
6869 // The template hasn't been instantiated yet (or it has, but only as an
6870 // explicit instantiation declaration or implicit instantiation, which means
6871 // we haven't codegenned any members yet), so propagate the attribute.
6872 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6873 NewAttr->setInherited(true);
6874 BaseTemplateSpec->addAttr(A: NewAttr);
6875
6876 // If this was an import, mark that we propagated it from a derived class to
6877 // a base class template specialization.
6878 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6879 ImportAttr->setPropagatedToBaseTemplate();
6880
6881 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6882 // needs to be run again to work see the new attribute. Otherwise this will
6883 // get run whenever the template is instantiated.
6884 if (TSK != TSK_Undeclared)
6885 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6886
6887 return;
6888 }
6889
6890 if (getDLLAttr(D: BaseTemplateSpec)) {
6891 // The template has already been specialized or instantiated with an
6892 // attribute, explicitly or through propagation. We should not try to change
6893 // it.
6894 return;
6895 }
6896
6897 // The template was previously instantiated or explicitly specialized without
6898 // a dll attribute, It's too late for us to add an attribute, so warn that
6899 // this is unsupported.
6900 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6901 << BaseTemplateSpec->isExplicitSpecialization();
6902 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6903 if (BaseTemplateSpec->isExplicitSpecialization()) {
6904 Diag(Loc: BaseTemplateSpec->getLocation(),
6905 DiagID: diag::note_template_class_explicit_specialization_was_here)
6906 << BaseTemplateSpec;
6907 } else {
6908 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6909 DiagID: diag::note_template_class_instantiation_was_here)
6910 << BaseTemplateSpec;
6911 }
6912}
6913
6914namespace {
6915/// RAII object to restore the floating-point (FP) features active at the time
6916/// a defaulted function was declared. This ensures that the synthesized body
6917/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6918/// that were in effect when the function was explicitly defaulted.
6919struct DefaultedFunctionFPFeaturesRAII {
6920 Sema::FPFeaturesStateRAII SavedFPFeatures;
6921 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6922 : SavedFPFeatures(S) {
6923 auto *Info = FD->getDefaultedOrDeletedInfo();
6924 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6925 S.CurFPFeatures = FPO.applyOverrides(LO: S.LangOpts);
6926 S.FpPragmaStack.CurrentValue = FPO;
6927 }
6928
6929 ~DefaultedFunctionFPFeaturesRAII() = default;
6930};
6931} // namespace
6932
6933static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6934 SourceLocation DefaultLoc) {
6935 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
6936 if (DFK.isComparison())
6937 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6938 if (DFK.isPostfixOperator())
6939 return S.DefineDefaultedPostfixOperator(Loc: DefaultLoc, FD,
6940 Kind: DFK.asPostfixOperator());
6941
6942 switch (DFK.asSpecialMember()) {
6943 case CXXSpecialMemberKind::DefaultConstructor:
6944 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6945 Constructor: cast<CXXConstructorDecl>(Val: FD));
6946 break;
6947 case CXXSpecialMemberKind::CopyConstructor:
6948 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6949 break;
6950 case CXXSpecialMemberKind::CopyAssignment:
6951 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6952 break;
6953 case CXXSpecialMemberKind::Destructor:
6954 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6955 break;
6956 case CXXSpecialMemberKind::MoveConstructor:
6957 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6958 break;
6959 case CXXSpecialMemberKind::MoveAssignment:
6960 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6961 break;
6962 case CXXSpecialMemberKind::Invalid:
6963 llvm_unreachable("Invalid special member.");
6964 }
6965}
6966
6967/// Determine whether a type is permitted to be passed or returned in
6968/// registers, per C++ [class.temporary]p3.
6969static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6970 TargetInfo::CallingConvKind CCK) {
6971 if (D->isDependentType() || D->isInvalidDecl())
6972 return false;
6973
6974 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6975 // The PS4 platform ABI follows the behavior of Clang 3.2.
6976 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6977 return !D->hasNonTrivialDestructorForCall() &&
6978 !D->hasNonTrivialCopyConstructorForCall();
6979
6980 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6981 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6982 bool DtorIsTrivialForCall = false;
6983
6984 // If a class has at least one eligible, trivial copy constructor, it
6985 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6986 //
6987 // Note: This permits classes with non-trivial copy or move ctors to be
6988 // passed in registers, so long as they *also* have a trivial copy ctor,
6989 // which is non-conforming.
6990 if (D->needsImplicitCopyConstructor()) {
6991 if (!D->defaultedCopyConstructorIsDeleted()) {
6992 if (D->hasTrivialCopyConstructor())
6993 CopyCtorIsTrivial = true;
6994 if (D->hasTrivialCopyConstructorForCall())
6995 CopyCtorIsTrivialForCall = true;
6996 }
6997 } else {
6998 for (const CXXConstructorDecl *CD : D->ctors()) {
6999 if (CD->isCopyConstructor() && !CD->isDeleted() &&
7000 !CD->isIneligibleOrNotSelected()) {
7001 if (CD->isTrivial())
7002 CopyCtorIsTrivial = true;
7003 if (CD->isTrivialForCall())
7004 CopyCtorIsTrivialForCall = true;
7005 }
7006 }
7007 }
7008
7009 if (D->needsImplicitDestructor()) {
7010 if (!D->defaultedDestructorIsDeleted() &&
7011 D->hasTrivialDestructorForCall())
7012 DtorIsTrivialForCall = true;
7013 } else if (const auto *DD = D->getDestructor()) {
7014 if (!DD->isDeleted() && DD->isTrivialForCall())
7015 DtorIsTrivialForCall = true;
7016 }
7017
7018 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7019 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7020 return true;
7021
7022 // If a class has a destructor, we'd really like to pass it indirectly
7023 // because it allows us to elide copies. Unfortunately, MSVC makes that
7024 // impossible for small types, which it will pass in a single register or
7025 // stack slot. Most objects with dtors are large-ish, so handle that early.
7026 // We can't call out all large objects as being indirect because there are
7027 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7028 // how we pass large POD types.
7029
7030 // Note: This permits small classes with nontrivial destructors to be
7031 // passed in registers, which is non-conforming.
7032 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7033 uint64_t TypeSize = isAArch64 ? 128 : 64;
7034
7035 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7036 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
7037 return true;
7038 return false;
7039 }
7040
7041 // Per C++ [class.temporary]p3, the relevant condition is:
7042 // each copy constructor, move constructor, and destructor of X is
7043 // either trivial or deleted, and X has at least one non-deleted copy
7044 // or move constructor
7045 bool HasNonDeletedCopyOrMove = false;
7046
7047 if (D->needsImplicitCopyConstructor() &&
7048 !D->defaultedCopyConstructorIsDeleted()) {
7049 if (!D->hasTrivialCopyConstructorForCall())
7050 return false;
7051 HasNonDeletedCopyOrMove = true;
7052 }
7053
7054 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7055 !D->defaultedMoveConstructorIsDeleted()) {
7056 if (!D->hasTrivialMoveConstructorForCall())
7057 return false;
7058 HasNonDeletedCopyOrMove = true;
7059 }
7060
7061 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7062 !D->hasTrivialDestructorForCall())
7063 return false;
7064
7065 for (const CXXMethodDecl *MD : D->methods()) {
7066 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7067 continue;
7068
7069 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7070 if (CD && CD->isCopyOrMoveConstructor())
7071 HasNonDeletedCopyOrMove = true;
7072 else if (!isa<CXXDestructorDecl>(Val: MD))
7073 continue;
7074
7075 if (!MD->isTrivialForCall())
7076 return false;
7077 }
7078
7079 return HasNonDeletedCopyOrMove;
7080}
7081
7082/// Report an error regarding overriding, along with any relevant
7083/// overridden methods.
7084///
7085/// \param DiagID the primary error to report.
7086/// \param MD the overriding method.
7087static bool
7088ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7089 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7090 bool IssuedDiagnostic = false;
7091 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7092 if (Report(O)) {
7093 if (!IssuedDiagnostic) {
7094 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7095 IssuedDiagnostic = true;
7096 }
7097 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7098 }
7099 }
7100 return IssuedDiagnostic;
7101}
7102
7103void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7104 if (!Record)
7105 return;
7106
7107 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7108 AbstractUsageInfo Info(*this, Record);
7109 CheckAbstractClassUsage(Info, RD: Record);
7110 }
7111
7112 // If this is not an aggregate type and has no user-declared constructor,
7113 // complain about any non-static data members of reference or const scalar
7114 // type, since they will never get initializers.
7115 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7116 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7117 !Record->isLambda()) {
7118 bool Complained = false;
7119 for (const auto *F : Record->fields()) {
7120 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7121 continue;
7122
7123 if (F->getType()->isReferenceType() ||
7124 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7125 if (!Complained) {
7126 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7127 << Record->getTagKind() << Record;
7128 Complained = true;
7129 }
7130
7131 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7132 << F->getType()->isReferenceType()
7133 << F->getDeclName();
7134 }
7135 }
7136 }
7137
7138 if (Record->getIdentifier()) {
7139 // C++ [class.mem]p13:
7140 // If T is the name of a class, then each of the following shall have a
7141 // name different from T:
7142 // - every member of every anonymous union that is a member of class T.
7143 //
7144 // C++ [class.mem]p14:
7145 // In addition, if class T has a user-declared constructor (12.1), every
7146 // non-static data member of class T shall have a name different from T.
7147 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7148 const NamedDecl *D = Element->getUnderlyingDecl();
7149 // Invalid IndirectFieldDecls have already been diagnosed with
7150 // err_anonymous_record_member_redecl in
7151 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7152 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7153 Record->hasUserDeclaredConstructor()) ||
7154 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7155 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7156 << D->getDeclName();
7157 break;
7158 }
7159 }
7160 }
7161
7162 // Warn if the class has virtual methods but non-virtual public destructor.
7163 if (Record->isPolymorphic() && !Record->isDependentType()) {
7164 CXXDestructorDecl *dtor = Record->getDestructor();
7165 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7166 !Record->hasAttr<FinalAttr>())
7167 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7168 DiagID: diag::warn_non_virtual_dtor)
7169 << Context.getCanonicalTagType(TD: Record);
7170 }
7171
7172 if (Record->isAbstract()) {
7173 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7174 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7175 << FA->isSpelledAsSealed();
7176 DiagnoseAbstractType(RD: Record);
7177 }
7178 }
7179
7180 // Warn if the class has a final destructor but is not itself marked final.
7181 if (!Record->hasAttr<FinalAttr>()) {
7182 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7183 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7184 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7185 << FA->isSpelledAsSealed()
7186 << FixItHint::CreateInsertion(
7187 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7188 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7189 Diag(Loc: Record->getLocation(),
7190 DiagID: diag::note_final_dtor_non_final_class_silence)
7191 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7192 }
7193 }
7194 }
7195
7196 // See if trivial_abi has to be dropped.
7197 if (Record->hasAttr<TrivialABIAttr>())
7198 checkIllFormedTrivialABIStruct(RD&: *Record);
7199
7200 // Set HasTrivialSpecialMemberForCall if the record has attribute
7201 // "trivial_abi".
7202 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7203
7204 if (HasTrivialABI)
7205 Record->setHasTrivialSpecialMemberForCall();
7206
7207 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7208 // We check these last because they can depend on the properties of the
7209 // primary comparison functions (==, <=>).
7210 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7211
7212 // Perform checks that can't be done until we know all the properties of a
7213 // member function (whether it's defaulted, deleted, virtual, overriding,
7214 // ...).
7215 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7216 // A static function cannot override anything.
7217 if (MD->getStorageClass() == SC_Static) {
7218 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7219 Report: [](const CXXMethodDecl *) { return true; }))
7220 return;
7221 }
7222
7223 // A deleted function cannot override a non-deleted function and vice
7224 // versa.
7225 if (ReportOverrides(S&: *this,
7226 DiagID: MD->isDeleted() ? diag::err_deleted_override
7227 : diag::err_non_deleted_override,
7228 MD, Report: [&](const CXXMethodDecl *V) {
7229 return MD->isDeleted() != V->isDeleted();
7230 })) {
7231 if (MD->isDefaulted() && MD->isDeleted())
7232 // Explain why this defaulted function was deleted.
7233 DiagnoseDeletedDefaultedFunction(FD: MD);
7234 return;
7235 }
7236
7237 // A consteval function cannot override a non-consteval function and vice
7238 // versa.
7239 if (ReportOverrides(S&: *this,
7240 DiagID: MD->isConsteval() ? diag::err_consteval_override
7241 : diag::err_non_consteval_override,
7242 MD, Report: [&](const CXXMethodDecl *V) {
7243 return MD->isConsteval() != V->isConsteval();
7244 })) {
7245 if (MD->isDefaulted() && MD->isDeleted())
7246 // Explain why this defaulted function was deleted.
7247 DiagnoseDeletedDefaultedFunction(FD: MD);
7248 return;
7249 }
7250 };
7251
7252 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7253 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7254 return false;
7255
7256 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
7257 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7258 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7259 DefaultedSecondaryComparisons.push_back(Elt: FD);
7260 return true;
7261 }
7262
7263 CheckExplicitlyDefaultedFunction(S, MD: FD);
7264 return false;
7265 };
7266
7267 if (!Record->isInvalidDecl() &&
7268 Record->hasAttr<VTablePointerAuthenticationAttr>())
7269 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7270
7271 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7272 // Check whether the explicitly-defaulted members are valid.
7273 bool Incomplete = CheckForDefaultedFunction(M);
7274
7275 // Skip the rest of the checks for a member of a dependent class.
7276 if (Record->isDependentType())
7277 return;
7278
7279 // For an explicitly defaulted or deleted special member, we defer
7280 // determining triviality until the class is complete. That time is now!
7281 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7282 if (!M->isImplicit() && !M->isUserProvided()) {
7283 if (CSM != CXXSpecialMemberKind::Invalid) {
7284 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7285 // Inform the class that we've finished declaring this member.
7286 Record->finishedDefaultedOrDeletedMember(MD: M);
7287 M->setTrivialForCall(
7288 HasTrivialABI ||
7289 SpecialMemberIsTrivial(MD: M, CSM,
7290 TAH: TrivialABIHandling::ConsiderTrivialABI));
7291 Record->setTrivialForCallFlags(M);
7292 }
7293 }
7294
7295 // Set triviality for the purpose of calls if this is a user-provided
7296 // copy/move constructor or destructor.
7297 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7298 CSM == CXXSpecialMemberKind::MoveConstructor ||
7299 CSM == CXXSpecialMemberKind::Destructor) &&
7300 M->isUserProvided()) {
7301 M->setTrivialForCall(HasTrivialABI);
7302 Record->setTrivialForCallFlags(M);
7303 }
7304
7305 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7306 M->hasAttr<DLLExportAttr>()) {
7307 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7308 M->isTrivial() &&
7309 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7310 CSM == CXXSpecialMemberKind::CopyConstructor ||
7311 CSM == CXXSpecialMemberKind::Destructor))
7312 M->dropAttr<DLLExportAttr>();
7313
7314 if (M->hasAttr<DLLExportAttr>()) {
7315 // Define after any fields with in-class initializers have been parsed.
7316 DelayedDllExportMemberFunctions.push_back(Elt: M);
7317 }
7318 }
7319
7320 bool EffectivelyConstexprDestructor = true;
7321 // Avoid triggering vtable instantiation due to a dtor that is not
7322 // "effectively constexpr" for better compatibility.
7323 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7324 if (isa<CXXDestructorDecl>(Val: M)) {
7325 llvm::SmallDenseSet<QualType> Visited;
7326 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7327 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7328 return false;
7329 const CXXRecordDecl *RD =
7330 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7331 if (!RD || !RD->isCompleteDefinition())
7332 return true;
7333
7334 if (!RD->hasConstexprDestructor())
7335 return false;
7336
7337 for (const CXXBaseSpecifier &B : RD->bases())
7338 if (!Check(B.getType(), Check))
7339 return false;
7340 for (const FieldDecl *FD : RD->fields())
7341 if (!Check(FD->getType(), Check))
7342 return false;
7343 return true;
7344 };
7345 EffectivelyConstexprDestructor =
7346 Check(Context.getCanonicalTagType(TD: Record), Check);
7347 }
7348
7349 // Define defaulted constexpr virtual functions that override a base class
7350 // function right away.
7351 // FIXME: We can defer doing this until the vtable is marked as used.
7352 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7353 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7354 EffectivelyConstexprDestructor)
7355 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7356
7357 if (!Incomplete)
7358 CheckCompletedMemberFunction(M);
7359 };
7360
7361 // Check the destructor before any other member function. We need to
7362 // determine whether it's trivial in order to determine whether the claas
7363 // type is a literal type, which is a prerequisite for determining whether
7364 // other special member functions are valid and whether they're implicitly
7365 // 'constexpr'.
7366 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7367 CompleteMemberFunction(Dtor);
7368
7369 bool HasMethodWithOverrideControl = false,
7370 HasOverridingMethodWithoutOverrideControl = false;
7371 for (auto *D : Record->decls()) {
7372 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7373 // FIXME: We could do this check for dependent types with non-dependent
7374 // bases.
7375 if (!Record->isDependentType()) {
7376 // See if a method overloads virtual methods in a base
7377 // class without overriding any.
7378 if (!M->isStatic())
7379 DiagnoseHiddenVirtualMethods(MD: M);
7380
7381 if (M->hasAttr<OverrideAttr>()) {
7382 HasMethodWithOverrideControl = true;
7383 } else if (M->size_overridden_methods() > 0) {
7384 HasOverridingMethodWithoutOverrideControl = true;
7385 } else {
7386 // Warn on newly-declared virtual methods in `final` classes
7387 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7388 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7389 << M;
7390 }
7391 }
7392 }
7393
7394 if (!isa<CXXDestructorDecl>(Val: M))
7395 CompleteMemberFunction(M);
7396 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7397 CheckForDefaultedFunction(
7398 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7399 }
7400 }
7401
7402 if (HasOverridingMethodWithoutOverrideControl) {
7403 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7404 for (auto *M : Record->methods())
7405 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7406 }
7407
7408 // Check the defaulted secondary comparisons after any other member functions.
7409 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7410 CheckExplicitlyDefaultedFunction(S, MD: FD);
7411
7412 // If this is a member function, we deferred checking it until now.
7413 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7414 CheckCompletedMemberFunction(MD);
7415 }
7416
7417 // {ms,gcc}_struct is a request to change ABI rules to either follow
7418 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7419 // present, we do not layout classes following foreign ABI rules, but
7420 // instead enter a special "compatibility mode", which only changes
7421 // alignments of fundamental types and layout of bit fields.
7422 // Check whether this class uses any C++ features that are implemented
7423 // completely differently in the requested ABI, and if so, emit a
7424 // diagnostic. That diagnostic defaults to an error, but we allow
7425 // projects to map it down to a warning (or ignore it). It's a fairly
7426 // common practice among users of the ms_struct pragma to
7427 // mass-annotate headers, sweeping up a bunch of types that the
7428 // project doesn't really rely on MSVC-compatible layout for. We must
7429 // therefore support "ms_struct except for C++ stuff" as a secondary
7430 // ABI.
7431 // Don't emit this diagnostic if the feature was enabled as a
7432 // language option (as opposed to via a pragma or attribute), as
7433 // the option -mms-bitfields otherwise essentially makes it impossible
7434 // to build C++ code, unless this diagnostic is turned off.
7435 if (Context.getLangOpts().getLayoutCompatibility() ==
7436 LangOptions::LayoutCompatibilityKind::Default &&
7437 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7438 (Record->isPolymorphic() || Record->getNumBases())) {
7439 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7440 }
7441
7442 checkClassLevelDLLAttribute(Class: Record);
7443 checkClassLevelCodeSegAttribute(Class: Record);
7444
7445 bool ClangABICompat4 =
7446 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver4);
7447 TargetInfo::CallingConvKind CCK =
7448 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7449 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7450
7451 // Do not change ArgPassingRestrictions if it has already been set to
7452 // RecordArgPassingKind::CanNeverPassInRegs.
7453 if (Record->getArgPassingRestrictions() !=
7454 RecordArgPassingKind::CanNeverPassInRegs)
7455 Record->setArgPassingRestrictions(
7456 CanPass ? RecordArgPassingKind::CanPassInRegs
7457 : RecordArgPassingKind::CannotPassInRegs);
7458
7459 // If canPassInRegisters returns true despite the record having a non-trivial
7460 // destructor, the record is destructed in the callee. This happens only when
7461 // the record or one of its subobjects has a field annotated with trivial_abi
7462 // or a field qualified with ObjC __strong/__weak.
7463 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7464 Record->setParamDestroyedInCallee(true);
7465 else if (Record->hasNonTrivialDestructor())
7466 Record->setParamDestroyedInCallee(CanPass);
7467
7468 if (getLangOpts().ForceEmitVTables) {
7469 // If we want to emit all the vtables, we need to mark it as used. This
7470 // is especially required for cases like vtable assumption loads.
7471 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7472 }
7473
7474 if (getLangOpts().CUDA) {
7475 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7476 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7477 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7478 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7479 }
7480
7481 llvm::SmallDenseMap<OverloadedOperatorKind,
7482 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7483 TypeAwareDecls{{OO_New, {}},
7484 {OO_Array_New, {}},
7485 {OO_Delete, {}},
7486 {OO_Array_New, {}}};
7487 for (auto *D : Record->decls()) {
7488 const FunctionDecl *FnDecl = D->getAsFunction();
7489 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7490 continue;
7491 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7492 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7493 }
7494 auto CheckMismatchedTypeAwareAllocators =
7495 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7496 OverloadedOperatorKind DeleteKind) {
7497 auto &NewDecls = TypeAwareDecls[NewKind];
7498 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7499 if (NewDecls.empty() == DeleteDecls.empty())
7500 return;
7501 DeclarationName FoundOperator =
7502 Context.DeclarationNames.getCXXOperatorName(
7503 Op: NewDecls.empty() ? DeleteKind : NewKind);
7504 DeclarationName MissingOperator =
7505 Context.DeclarationNames.getCXXOperatorName(
7506 Op: NewDecls.empty() ? NewKind : DeleteKind);
7507 Diag(Loc: Record->getLocation(),
7508 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7509 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7510 << MissingOperator;
7511 for (auto MD : NewDecls)
7512 Diag(Loc: MD->getLocation(),
7513 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7514 << MD;
7515 for (auto MD : DeleteDecls)
7516 Diag(Loc: MD->getLocation(),
7517 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7518 << MD;
7519 };
7520 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7521 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7522}
7523
7524/// Look up the special member function that would be called by a special
7525/// member function for a subobject of class type.
7526///
7527/// \param Class The class type of the subobject.
7528/// \param CSM The kind of special member function.
7529/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7530/// \param ConstRHS True if this is a copy operation with a const object
7531/// on its RHS, that is, if the argument to the outer special member
7532/// function is 'const' and this is not a field marked 'mutable'.
7533static Sema::SpecialMemberOverloadResult
7534lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7535 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7536 bool ConstRHS) {
7537 unsigned LHSQuals = 0;
7538 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7539 CSM == CXXSpecialMemberKind::MoveAssignment)
7540 LHSQuals = FieldQuals;
7541
7542 unsigned RHSQuals = FieldQuals;
7543 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7544 CSM == CXXSpecialMemberKind::Destructor)
7545 RHSQuals = 0;
7546 else if (ConstRHS)
7547 RHSQuals |= Qualifiers::Const;
7548
7549 return S.LookupSpecialMember(D: Class, SM: CSM,
7550 ConstArg: RHSQuals & Qualifiers::Const,
7551 VolatileArg: RHSQuals & Qualifiers::Volatile,
7552 RValueThis: false,
7553 ConstThis: LHSQuals & Qualifiers::Const,
7554 VolatileThis: LHSQuals & Qualifiers::Volatile);
7555}
7556
7557class Sema::InheritedConstructorInfo {
7558 Sema &S;
7559 SourceLocation UseLoc;
7560
7561 /// A mapping from the base classes through which the constructor was
7562 /// inherited to the using shadow declaration in that base class (or a null
7563 /// pointer if the constructor was declared in that base class).
7564 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7565 InheritedFromBases;
7566
7567public:
7568 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7569 ConstructorUsingShadowDecl *Shadow)
7570 : S(S), UseLoc(UseLoc) {
7571 bool DiagnosedMultipleConstructedBases = false;
7572 CXXRecordDecl *ConstructedBase = nullptr;
7573 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7574
7575 // Find the set of such base class subobjects and check that there's a
7576 // unique constructed subobject.
7577 for (auto *D : Shadow->redecls()) {
7578 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7579 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7580 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7581
7582 InheritedFromBases.insert(
7583 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7584 y: DShadow->getNominatedBaseClassShadowDecl()));
7585 if (DShadow->constructsVirtualBase())
7586 InheritedFromBases.insert(
7587 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7588 y: DShadow->getConstructedBaseClassShadowDecl()));
7589 else
7590 assert(DNominatedBase == DConstructedBase);
7591
7592 // [class.inhctor.init]p2:
7593 // If the constructor was inherited from multiple base class subobjects
7594 // of type B, the program is ill-formed.
7595 if (!ConstructedBase) {
7596 ConstructedBase = DConstructedBase;
7597 ConstructedBaseIntroducer = D->getIntroducer();
7598 } else if (ConstructedBase != DConstructedBase &&
7599 !Shadow->isInvalidDecl()) {
7600 if (!DiagnosedMultipleConstructedBases) {
7601 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7602 << Shadow->getTargetDecl();
7603 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7604 DiagID: diag::note_ambiguous_inherited_constructor_using)
7605 << ConstructedBase;
7606 DiagnosedMultipleConstructedBases = true;
7607 }
7608 S.Diag(Loc: D->getIntroducer()->getLocation(),
7609 DiagID: diag::note_ambiguous_inherited_constructor_using)
7610 << DConstructedBase;
7611 }
7612 }
7613
7614 if (DiagnosedMultipleConstructedBases)
7615 Shadow->setInvalidDecl();
7616 }
7617
7618 /// Find the constructor to use for inherited construction of a base class,
7619 /// and whether that base class constructor inherits the constructor from a
7620 /// virtual base class (in which case it won't actually invoke it).
7621 std::pair<CXXConstructorDecl *, bool>
7622 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7623 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7624 if (It == InheritedFromBases.end())
7625 return std::make_pair(x: nullptr, y: false);
7626
7627 // This is an intermediary class.
7628 if (It->second)
7629 return std::make_pair(
7630 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7631 y: It->second->constructsVirtualBase());
7632
7633 // This is the base class from which the constructor was inherited.
7634 return std::make_pair(x&: Ctor, y: false);
7635 }
7636};
7637
7638/// Is the special member function which would be selected to perform the
7639/// specified operation on the specified class type a constexpr constructor?
7640static bool specialMemberIsConstexpr(
7641 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7642 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7643 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7644 // Suppress duplicate constraint checking here, in case a constraint check
7645 // caused us to decide to do this. Any truely recursive checks will get
7646 // caught during these checks anyway.
7647 Sema::SatisfactionStackResetRAII SSRAII{S};
7648
7649 // If we're inheriting a constructor, see if we need to call it for this base
7650 // class.
7651 if (InheritedCtor) {
7652 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7653 auto BaseCtor =
7654 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7655 if (BaseCtor)
7656 return BaseCtor->isConstexpr();
7657 }
7658
7659 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7660 return ClassDecl->hasConstexprDefaultConstructor();
7661 if (CSM == CXXSpecialMemberKind::Destructor)
7662 return ClassDecl->hasConstexprDestructor();
7663
7664 Sema::SpecialMemberOverloadResult SMOR =
7665 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7666 if (!SMOR.getMethod())
7667 // A constructor we wouldn't select can't be "involved in initializing"
7668 // anything.
7669 return true;
7670 return SMOR.getMethod()->isConstexpr();
7671}
7672
7673/// Determine whether the specified special member function would be constexpr
7674/// if it were implicitly defined.
7675static bool defaultedSpecialMemberIsConstexpr(
7676 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7677 CXXConstructorDecl *InheritedCtor = nullptr,
7678 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7679 if (!S.getLangOpts().CPlusPlus11)
7680 return false;
7681
7682 // C++11 [dcl.constexpr]p4:
7683 // In the definition of a constexpr constructor [...]
7684 bool Ctor = true;
7685 switch (CSM) {
7686 case CXXSpecialMemberKind::DefaultConstructor:
7687 if (Inherited)
7688 break;
7689 // Since default constructor lookup is essentially trivial (and cannot
7690 // involve, for instance, template instantiation), we compute whether a
7691 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7692 //
7693 // This is important for performance; we need to know whether the default
7694 // constructor is constexpr to determine whether the type is a literal type.
7695 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7696
7697 case CXXSpecialMemberKind::CopyConstructor:
7698 case CXXSpecialMemberKind::MoveConstructor:
7699 // For copy or move constructors, we need to perform overload resolution.
7700 break;
7701
7702 case CXXSpecialMemberKind::CopyAssignment:
7703 case CXXSpecialMemberKind::MoveAssignment:
7704 if (!S.getLangOpts().CPlusPlus14)
7705 return false;
7706 // In C++1y, we need to perform overload resolution.
7707 Ctor = false;
7708 break;
7709
7710 case CXXSpecialMemberKind::Destructor:
7711 return ClassDecl->defaultedDestructorIsConstexpr();
7712
7713 case CXXSpecialMemberKind::Invalid:
7714 return false;
7715 }
7716
7717 // -- if the class is a non-empty union, or for each non-empty anonymous
7718 // union member of a non-union class, exactly one non-static data member
7719 // shall be initialized; [DR1359]
7720 //
7721 // If we squint, this is guaranteed, since exactly one non-static data member
7722 // will be initialized (if the constructor isn't deleted), we just don't know
7723 // which one.
7724 if (Ctor && ClassDecl->isUnion())
7725 return CSM == CXXSpecialMemberKind::DefaultConstructor
7726 ? ClassDecl->hasInClassInitializer() ||
7727 !ClassDecl->hasVariantMembers()
7728 : true;
7729
7730 // -- the class shall not have any virtual base classes;
7731 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7732 return false;
7733
7734 // C++1y [class.copy]p26:
7735 // -- [the class] is a literal type, and
7736 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7737 return false;
7738
7739 // -- every constructor involved in initializing [...] base class
7740 // sub-objects shall be a constexpr constructor;
7741 // -- the assignment operator selected to copy/move each direct base
7742 // class is a constexpr function, and
7743 if (!S.getLangOpts().CPlusPlus23) {
7744 for (const auto &B : ClassDecl->bases()) {
7745 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7746 if (!BaseClassDecl)
7747 continue;
7748 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7749 InheritedCtor, Inherited))
7750 return false;
7751 }
7752 }
7753
7754 // -- every constructor involved in initializing non-static data members
7755 // [...] shall be a constexpr constructor;
7756 // -- every non-static data member and base class sub-object shall be
7757 // initialized
7758 // -- for each non-static data member of X that is of class type (or array
7759 // thereof), the assignment operator selected to copy/move that member is
7760 // a constexpr function
7761 if (!S.getLangOpts().CPlusPlus23) {
7762 for (const auto *F : ClassDecl->fields()) {
7763 if (F->isInvalidDecl())
7764 continue;
7765 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7766 F->hasInClassInitializer())
7767 continue;
7768 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7769 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7770 auto *FieldRecDecl =
7771 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7772 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7773 Quals: BaseType.getCVRQualifiers(),
7774 ConstRHS: ConstArg && !F->isMutable()))
7775 return false;
7776 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7777 return false;
7778 }
7779 }
7780 }
7781
7782 // All OK, it's constexpr!
7783 return true;
7784}
7785
7786namespace {
7787/// RAII object to register a defaulted function as having its exception
7788/// specification computed.
7789struct ComputingExceptionSpec {
7790 Sema &S;
7791
7792 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7793 : S(S) {
7794 Sema::CodeSynthesisContext Ctx;
7795 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7796 Ctx.PointOfInstantiation = Loc;
7797 Ctx.Entity = FD;
7798 S.pushCodeSynthesisContext(Ctx);
7799 }
7800 ~ComputingExceptionSpec() {
7801 S.popCodeSynthesisContext();
7802 }
7803};
7804}
7805
7806static Sema::ImplicitExceptionSpecification
7807ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7808 CXXMethodDecl *MD,
7809 CXXSpecialMemberKind CSM,
7810 Sema::InheritedConstructorInfo *ICI);
7811
7812static Sema::ImplicitExceptionSpecification
7813ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7814 FunctionDecl *FD,
7815 DefaultedComparisonKind DCK);
7816
7817static Sema::ImplicitExceptionSpecification
7818ComputeDefaultedPostfixOperatorExceptionSpec(Sema &S, SourceLocation Loc,
7819 FunctionDecl *FD,
7820 PostfixOperatorKind Kind);
7821
7822static Sema::ImplicitExceptionSpecification
7823computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7824 auto DFK = FD->getDefaultedFunctionKind();
7825 if (DFK.isSpecialMember())
7826 return ComputeDefaultedSpecialMemberExceptionSpec(
7827 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7828 if (DFK.isComparison())
7829 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7830 DCK: DFK.asComparison());
7831 if (DFK.isPostfixOperator())
7832 return ComputeDefaultedPostfixOperatorExceptionSpec(
7833 S, Loc, FD, Kind: DFK.asPostfixOperator());
7834
7835 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7836 assert(CD->getInheritedConstructor() &&
7837 "only defaulted functions and inherited constructors have implicit "
7838 "exception specs");
7839 Sema::InheritedConstructorInfo ICI(
7840 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7841 return ComputeDefaultedSpecialMemberExceptionSpec(
7842 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7843}
7844
7845static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7846 CXXMethodDecl *MD) {
7847 FunctionProtoType::ExtProtoInfo EPI;
7848
7849 // Build an exception specification pointing back at this member.
7850 EPI.ExceptionSpec.Type = EST_Unevaluated;
7851 EPI.ExceptionSpec.SourceDecl = MD;
7852
7853 // Set the calling convention to the default for C++ instance methods.
7854 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7855 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7856 /*IsCXXMethod=*/true));
7857 return EPI;
7858}
7859
7860void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7861 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7862 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7863 return;
7864
7865 // Evaluate the exception specification.
7866 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7867 auto ESI = IES.getExceptionSpec();
7868
7869 // Update the type of the special member to use it.
7870 UpdateExceptionSpec(FD, ESI);
7871}
7872
7873void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7874 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7875
7876 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
7877 if (!DefKind) {
7878 assert(FD->getDeclContext()->isDependentContext());
7879 return;
7880 }
7881
7882 if (DefKind.isComparison()) {
7883 auto PT = FD->getParamDecl(i: 0)->getType();
7884 if (const CXXRecordDecl *RD =
7885 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7886 for (FieldDecl *Field : RD->fields()) {
7887 UnusedPrivateFields.remove(X: Field);
7888 }
7889 }
7890 }
7891
7892 if (DefKind.isPostfixOperator()) {
7893 if (CheckExplicitlyDefaultedPostfixOperator(S, FD,
7894 Kind: DefKind.asPostfixOperator()))
7895 FD->setInvalidDecl();
7896 return;
7897 }
7898
7899 if (DefKind.isSpecialMember()
7900 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7901 CSM: DefKind.asSpecialMember(),
7902 DefaultLoc: FD->getDefaultLoc())
7903 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7904 FD->setInvalidDecl();
7905}
7906
7907bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7908 CXXSpecialMemberKind CSM,
7909 SourceLocation DefaultLoc) {
7910 CXXRecordDecl *RD = MD->getParent();
7911
7912 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7913 "not an explicitly-defaulted special member");
7914
7915 // Defer all checking for special members of a dependent type.
7916 if (RD->isDependentType())
7917 return false;
7918
7919 // Whether this was the first-declared instance of the constructor.
7920 // This affects whether we implicitly add an exception spec and constexpr.
7921 bool First = MD == MD->getCanonicalDecl();
7922
7923 bool HadError = false;
7924
7925 // C++11 [dcl.fct.def.default]p1:
7926 // A function that is explicitly defaulted shall
7927 // -- be a special member function [...] (checked elsewhere),
7928 // -- have the same type (except for ref-qualifiers, and except that a
7929 // copy operation can take a non-const reference) as an implicit
7930 // declaration, and
7931 // -- not have default arguments.
7932 // C++2a changes the second bullet to instead delete the function if it's
7933 // defaulted on its first declaration, unless it's "an assignment operator,
7934 // and its return type differs or its parameter type is not a reference".
7935 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7936 bool ShouldDeleteForTypeMismatch = false;
7937 unsigned ExpectedParams = 1;
7938 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7939 CSM == CXXSpecialMemberKind::Destructor)
7940 ExpectedParams = 0;
7941 if (MD->getNumExplicitParams() != ExpectedParams) {
7942 // This checks for default arguments: a copy or move constructor with a
7943 // default argument is classified as a default constructor, and assignment
7944 // operations and destructors can't have default arguments.
7945 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7946 << CSM << MD->getSourceRange();
7947 HadError = true;
7948 } else if (MD->isVariadic()) {
7949 if (DeleteOnTypeMismatch)
7950 ShouldDeleteForTypeMismatch = true;
7951 else {
7952 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7953 << CSM << MD->getSourceRange();
7954 HadError = true;
7955 }
7956 }
7957
7958 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7959
7960 bool CanHaveConstParam = false;
7961 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7962 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7963 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7964 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7965
7966 QualType ReturnType = Context.VoidTy;
7967 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7968 CSM == CXXSpecialMemberKind::MoveAssignment) {
7969 // Check for return type matching.
7970 ReturnType = Type->getReturnType();
7971 QualType ThisType = MD->getFunctionObjectParameterType();
7972
7973 QualType DeclType =
7974 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7975 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7976 DeclType = Context.getAddrSpaceQualType(
7977 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7978 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7979
7980 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7981 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7982 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7983 << ExpectedReturnType;
7984 HadError = true;
7985 }
7986
7987 // A defaulted special member cannot have cv-qualifiers.
7988 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7989 if (DeleteOnTypeMismatch)
7990 ShouldDeleteForTypeMismatch = true;
7991 else {
7992 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7993 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7994 << getLangOpts().CPlusPlus14;
7995 HadError = true;
7996 }
7997 }
7998 // [C++23][dcl.fct.def.default]/p2.2
7999 // if F2 has an implicit object parameter of type “reference to C”,
8000 // F1 may be an explicit object member function whose explicit object
8001 // parameter is of (possibly different) type “reference to C”,
8002 // in which case the type of F1 would differ from the type of F2
8003 // in that the type of F1 has an additional parameter;
8004 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
8005 ? MD->getParamDecl(i: 0)->getType()
8006 : QualType();
8007 if (!ExplicitObjectParameter.isNull() &&
8008 (!ExplicitObjectParameter->isReferenceType() ||
8009 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
8010 T2: Context.getCanonicalTagType(TD: RD)))) {
8011 if (DeleteOnTypeMismatch)
8012 ShouldDeleteForTypeMismatch = true;
8013 else {
8014 Diag(Loc: MD->getLocation(),
8015 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
8016 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
8017 << MD->getSourceRange();
8018 HadError = true;
8019 }
8020 }
8021 }
8022
8023 // Check for parameter type matching.
8024 QualType ArgType =
8025 ExpectedParams
8026 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
8027 : QualType();
8028 bool HasConstParam = false;
8029 if (ExpectedParams && ArgType->isReferenceType()) {
8030 // Argument must be reference to possibly-const T.
8031 QualType ReferentType = ArgType->getPointeeType();
8032 HasConstParam = ReferentType.isConstQualified();
8033
8034 if (ReferentType.isVolatileQualified()) {
8035 if (DeleteOnTypeMismatch)
8036 ShouldDeleteForTypeMismatch = true;
8037 else {
8038 Diag(Loc: MD->getLocation(),
8039 DiagID: diag::err_defaulted_special_member_volatile_param)
8040 << CSM;
8041 HadError = true;
8042 }
8043 }
8044
8045 if (HasConstParam && !CanHaveConstParam) {
8046 if (DeleteOnTypeMismatch)
8047 ShouldDeleteForTypeMismatch = true;
8048 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8049 CSM == CXXSpecialMemberKind::CopyAssignment) {
8050 Diag(Loc: MD->getLocation(),
8051 DiagID: diag::err_defaulted_special_member_copy_const_param)
8052 << (CSM == CXXSpecialMemberKind::CopyAssignment);
8053 // FIXME: Explain why this special member can't be const.
8054 HadError = true;
8055 } else {
8056 Diag(Loc: MD->getLocation(),
8057 DiagID: diag::err_defaulted_special_member_move_const_param)
8058 << (CSM == CXXSpecialMemberKind::MoveAssignment);
8059 HadError = true;
8060 }
8061 }
8062 } else if (ExpectedParams) {
8063 // A copy assignment operator can take its argument by value, but a
8064 // defaulted one cannot.
8065 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
8066 "unexpected non-ref argument");
8067 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
8068 HadError = true;
8069 }
8070
8071 // C++11 [dcl.fct.def.default]p2:
8072 // An explicitly-defaulted function may be declared constexpr only if it
8073 // would have been implicitly declared as constexpr,
8074 // Do not apply this rule to members of class templates, since core issue 1358
8075 // makes such functions always instantiate to constexpr functions. For
8076 // functions which cannot be constexpr (for non-constructors in C++11 and for
8077 // destructors in C++14 and C++17), this is checked elsewhere.
8078 //
8079 // FIXME: This should not apply if the member is deleted.
8080 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8081 ConstArg: HasConstParam);
8082
8083 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8084 // If the instantiated template specialization of a constexpr function
8085 // template or member function of a class template would fail to satisfy
8086 // the requirements for a constexpr function or constexpr constructor, that
8087 // specialization is still a constexpr function or constexpr constructor,
8088 // even though a call to such a function cannot appear in a constant
8089 // expression.
8090 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8091 Constexpr = true;
8092
8093 if ((getLangOpts().CPlusPlus20 ||
8094 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8095 : isa<CXXConstructorDecl>(Val: MD))) &&
8096 MD->isConstexpr() && !Constexpr &&
8097 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8098 if (!MD->isConsteval() && RD->getNumVBases()) {
8099 Diag(Loc: MD->getBeginLoc(),
8100 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8101 << CSM;
8102 for (const auto &I : RD->vbases())
8103 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8104 } else {
8105 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8106 << CSM << MD->isConsteval();
8107 }
8108 HadError = true;
8109 // FIXME: Explain why the special member can't be constexpr.
8110 }
8111 if (First) {
8112 // C++2a [dcl.fct.def.default]p3:
8113 // If a function is explicitly defaulted on its first declaration, it is
8114 // implicitly considered to be constexpr if the implicit declaration
8115 // would be.
8116 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8117 ? ConstexprSpecKind::Consteval
8118 : ConstexprSpecKind::Constexpr)
8119 : ConstexprSpecKind::Unspecified);
8120
8121 if (!Type->hasExceptionSpec()) {
8122 // C++2a [except.spec]p3:
8123 // If a declaration of a function does not have a noexcept-specifier
8124 // [and] is defaulted on its first declaration, [...] the exception
8125 // specification is as specified below
8126 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8127 EPI.ExceptionSpec.Type = EST_Unevaluated;
8128 EPI.ExceptionSpec.SourceDecl = MD;
8129 MD->setType(
8130 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8131 }
8132 }
8133
8134 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8135 if (First) {
8136 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8137 if (!inTemplateInstantiation() && !HadError) {
8138 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8139 if (ShouldDeleteForTypeMismatch) {
8140 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8141 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8142 /*Diagnose*/ true) &&
8143 DefaultLoc.isValid()) {
8144 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8145 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8146 }
8147 }
8148 if (ShouldDeleteForTypeMismatch && !HadError) {
8149 Diag(Loc: MD->getLocation(),
8150 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8151 << CSM;
8152 }
8153 } else {
8154 // C++11 [dcl.fct.def.default]p4:
8155 // [For a] user-provided explicitly-defaulted function [...] if such a
8156 // function is implicitly defined as deleted, the program is ill-formed.
8157 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8158 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8159 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8160 HadError = true;
8161 }
8162 }
8163
8164 return HadError;
8165}
8166
8167namespace {
8168/// Helper class for building and checking a defaulted comparison.
8169///
8170/// Defaulted functions are built in two phases:
8171///
8172/// * First, the set of operations that the function will perform are
8173/// identified, and some of them are checked. If any of the checked
8174/// operations is invalid in certain ways, the comparison function is
8175/// defined as deleted and no body is built.
8176/// * Then, if the function is not defined as deleted, the body is built.
8177///
8178/// This is accomplished by performing two visitation steps over the eventual
8179/// body of the function.
8180template<typename Derived, typename ResultList, typename Result,
8181 typename Subobject>
8182class DefaultedComparisonVisitor {
8183public:
8184 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8185 DefaultedComparisonKind DCK)
8186 : S(S), RD(RD), FD(FD), DCK(DCK) {
8187 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8188 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8189 // UnresolvedSet to avoid this copy.
8190 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8191 E: Info->getUnqualifiedLookups().end());
8192 }
8193 }
8194
8195 ResultList visit() {
8196 // The type of an lvalue naming a parameter of this function.
8197 QualType ParamLvalType =
8198 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8199
8200 ResultList Results;
8201
8202 switch (DCK) {
8203 case DefaultedComparisonKind::None:
8204 llvm_unreachable("not a defaulted comparison");
8205
8206 case DefaultedComparisonKind::Equal:
8207 case DefaultedComparisonKind::ThreeWay:
8208 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8209 return Results;
8210
8211 case DefaultedComparisonKind::NotEqual:
8212 case DefaultedComparisonKind::Relational:
8213 Results.add(getDerived().visitExpandedSubobject(
8214 ParamLvalType, getDerived().getCompleteObject()));
8215 return Results;
8216 }
8217 llvm_unreachable("");
8218 }
8219
8220protected:
8221 Derived &getDerived() { return static_cast<Derived&>(*this); }
8222
8223 /// Visit the expanded list of subobjects of the given type, as specified in
8224 /// C++2a [class.compare.default].
8225 ///
8226 /// \return \c true if the ResultList object said we're done, \c false if not.
8227 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8228 Qualifiers Quals) {
8229 // C++2a [class.compare.default]p4:
8230 // The direct base class subobjects of C
8231 for (CXXBaseSpecifier &Base : Record->bases())
8232 if (Results.add(getDerived().visitSubobject(
8233 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8234 getDerived().getBase(&Base))))
8235 return true;
8236
8237 // followed by the non-static data members of C
8238 for (FieldDecl *Field : Record->fields()) {
8239 // C++23 [class.bit]p2:
8240 // Unnamed bit-fields are not members ...
8241 if (Field->isUnnamedBitField())
8242 continue;
8243 if (Field->isInvalidDecl())
8244 continue;
8245 // Recursively expand anonymous structs.
8246 if (Field->isAnonymousStructOrUnion()) {
8247 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8248 Quals))
8249 return true;
8250 continue;
8251 }
8252
8253 // Figure out the type of an lvalue denoting this field.
8254 Qualifiers FieldQuals = Quals;
8255 if (Field->isMutable())
8256 FieldQuals.removeConst();
8257 QualType FieldType =
8258 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8259
8260 if (Results.add(getDerived().visitSubobject(
8261 FieldType, getDerived().getField(Field))))
8262 return true;
8263 }
8264
8265 // form a list of subobjects.
8266 return false;
8267 }
8268
8269 Result visitSubobject(QualType Type, Subobject Subobj) {
8270 // In that list, any subobject of array type is recursively expanded
8271 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8272 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8273 return getDerived().visitSubobjectArray(CAT->getElementType(),
8274 CAT->getSize(), Subobj);
8275 return getDerived().visitExpandedSubobject(Type, Subobj);
8276 }
8277
8278 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8279 Subobject Subobj) {
8280 return getDerived().visitSubobject(Type, Subobj);
8281 }
8282
8283protected:
8284 Sema &S;
8285 CXXRecordDecl *RD;
8286 FunctionDecl *FD;
8287 DefaultedComparisonKind DCK;
8288 UnresolvedSet<16> Fns;
8289};
8290
8291/// Information about a defaulted comparison, as determined by
8292/// DefaultedComparisonAnalyzer.
8293struct DefaultedComparisonInfo {
8294 bool Deleted = false;
8295 bool Constexpr = true;
8296 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8297
8298 static DefaultedComparisonInfo deleted() {
8299 DefaultedComparisonInfo Deleted;
8300 Deleted.Deleted = true;
8301 return Deleted;
8302 }
8303
8304 bool add(const DefaultedComparisonInfo &R) {
8305 Deleted |= R.Deleted;
8306 Constexpr &= R.Constexpr;
8307 Category = commonComparisonType(A: Category, B: R.Category);
8308 return Deleted;
8309 }
8310};
8311
8312/// An element in the expanded list of subobjects of a defaulted comparison, as
8313/// specified in C++2a [class.compare.default]p4.
8314struct DefaultedComparisonSubobject {
8315 enum { CompleteObject, Member, Base } Kind;
8316 NamedDecl *Decl;
8317 SourceLocation Loc;
8318};
8319
8320/// A visitor over the notional body of a defaulted comparison that determines
8321/// whether that body would be deleted or constexpr.
8322class DefaultedComparisonAnalyzer
8323 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8324 DefaultedComparisonInfo,
8325 DefaultedComparisonInfo,
8326 DefaultedComparisonSubobject> {
8327public:
8328 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8329
8330private:
8331 DiagnosticKind Diagnose;
8332
8333public:
8334 using Base = DefaultedComparisonVisitor;
8335 using Result = DefaultedComparisonInfo;
8336 using Subobject = DefaultedComparisonSubobject;
8337
8338 friend Base;
8339
8340 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8341 DefaultedComparisonKind DCK,
8342 DiagnosticKind Diagnose = NoDiagnostics)
8343 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8344
8345 Result visit() {
8346 if ((DCK == DefaultedComparisonKind::Equal ||
8347 DCK == DefaultedComparisonKind::ThreeWay) &&
8348 RD->hasVariantMembers()) {
8349 // C++2a [class.compare.default]p2 [P2002R0]:
8350 // A defaulted comparison operator function for class C is defined as
8351 // deleted if [...] C has variant members.
8352 if (Diagnose == ExplainDeleted) {
8353 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8354 << FD << RD->isUnion() << RD;
8355 }
8356 return Result::deleted();
8357 }
8358
8359 return Base::visit();
8360 }
8361
8362private:
8363 Subobject getCompleteObject() {
8364 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8365 }
8366
8367 Subobject getBase(CXXBaseSpecifier *Base) {
8368 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8369 .Loc: Base->getBaseTypeLoc()};
8370 }
8371
8372 Subobject getField(FieldDecl *Field) {
8373 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8374 }
8375
8376 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8377 // C++2a [class.compare.default]p2 [P2002R0]:
8378 // A defaulted <=> or == operator function for class C is defined as
8379 // deleted if any non-static data member of C is of reference type
8380 if (Type->isReferenceType()) {
8381 if (Diagnose == ExplainDeleted) {
8382 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8383 << FD << RD;
8384 }
8385 return Result::deleted();
8386 }
8387
8388 // [...] Let xi be an lvalue denoting the ith element [...]
8389 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8390 Expr *Args[] = {&Xi, &Xi};
8391
8392 // All operators start by trying to apply that same operator recursively.
8393 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8394 assert(OO != OO_None && "not an overloaded operator!");
8395 return visitBinaryOperator(OO, Args, Subobj);
8396 }
8397
8398 Result
8399 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8400 Subobject Subobj,
8401 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8402 // Note that there is no need to consider rewritten candidates here if
8403 // we've already found there is no viable 'operator<=>' candidate (and are
8404 // considering synthesizing a '<=>' from '==' and '<').
8405 OverloadCandidateSet CandidateSet(
8406 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8407 OverloadCandidateSet::OperatorRewriteInfo(
8408 OO, FD->getLocation(),
8409 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8410
8411 /// C++2a [class.compare.default]p1 [P2002R0]:
8412 /// [...] the defaulted function itself is never a candidate for overload
8413 /// resolution [...]
8414 CandidateSet.exclude(F: FD);
8415
8416 if (Args[0]->getType()->isOverloadableType())
8417 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8418 else
8419 // FIXME: We determine whether this is a valid expression by checking to
8420 // see if there's a viable builtin operator candidate for it. That isn't
8421 // really what the rules ask us to do, but should give the right results.
8422 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8423
8424 Result R;
8425
8426 OverloadCandidateSet::iterator Best;
8427 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8428 case OR_Success: {
8429 // C++2a [class.compare.secondary]p2 [P2002R0]:
8430 // The operator function [...] is defined as deleted if [...] the
8431 // candidate selected by overload resolution is not a rewritten
8432 // candidate.
8433 if ((DCK == DefaultedComparisonKind::NotEqual ||
8434 DCK == DefaultedComparisonKind::Relational) &&
8435 !Best->RewriteKind) {
8436 if (Diagnose == ExplainDeleted) {
8437 if (Best->Function) {
8438 S.Diag(Loc: Best->Function->getLocation(),
8439 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8440 << FD;
8441 } else {
8442 assert(Best->Conversions.size() == 2 &&
8443 Best->Conversions[0].isUserDefined() &&
8444 "non-user-defined conversion from class to built-in "
8445 "comparison");
8446 S.Diag(Loc: Best->Conversions[0]
8447 .UserDefined.FoundConversionFunction.getDecl()
8448 ->getLocation(),
8449 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8450 << FD;
8451 }
8452 }
8453 return Result::deleted();
8454 }
8455
8456 // Throughout C++2a [class.compare]: if overload resolution does not
8457 // result in a usable function, the candidate function is defined as
8458 // deleted. This requires that we selected an accessible function.
8459 //
8460 // Note that this only considers the access of the function when named
8461 // within the type of the subobject, and not the access path for any
8462 // derived-to-base conversion.
8463 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8464 if (ArgClass && Best->FoundDecl.getDecl() &&
8465 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8466 QualType ObjectType = Subobj.Kind == Subobject::Member
8467 ? Args[0]->getType()
8468 : S.Context.getCanonicalTagType(TD: RD);
8469 if (!S.isMemberAccessibleForDeletion(
8470 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8471 Diag: Diagnose == ExplainDeleted
8472 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8473 << FD << Subobj.Kind << Subobj.Decl
8474 : S.PDiag()))
8475 return Result::deleted();
8476 }
8477
8478 bool NeedsDeducing =
8479 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8480
8481 if (FunctionDecl *BestFD = Best->Function) {
8482 // C++2a [class.compare.default]p3 [P2002R0]:
8483 // A defaulted comparison function is constexpr-compatible if
8484 // [...] no overlod resolution performed [...] results in a
8485 // non-constexpr function.
8486 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8487 // If it's not constexpr, explain why not.
8488 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8489 if (Subobj.Kind != Subobject::CompleteObject)
8490 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8491 << Subobj.Kind << Subobj.Decl;
8492 S.Diag(Loc: BestFD->getLocation(),
8493 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8494 // Bail out after explaining; we don't want any more notes.
8495 return Result::deleted();
8496 }
8497 R.Constexpr &= BestFD->isConstexpr();
8498
8499 if (NeedsDeducing) {
8500 // If any callee has an undeduced return type, deduce it now.
8501 // FIXME: It's not clear how a failure here should be handled. For
8502 // now, we produce an eager diagnostic, because that is forward
8503 // compatible with most (all?) other reasonable options.
8504 if (BestFD->getReturnType()->isUndeducedType() &&
8505 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8506 /*Diagnose=*/false)) {
8507 // Don't produce a duplicate error when asked to explain why the
8508 // comparison is deleted: we diagnosed that when initially checking
8509 // the defaulted operator.
8510 if (Diagnose == NoDiagnostics) {
8511 S.Diag(
8512 Loc: FD->getLocation(),
8513 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8514 << Subobj.Kind << Subobj.Decl;
8515 S.Diag(
8516 Loc: Subobj.Loc,
8517 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8518 << Subobj.Kind << Subobj.Decl;
8519 S.Diag(Loc: BestFD->getLocation(),
8520 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8521 << Subobj.Kind << Subobj.Decl;
8522 }
8523 return Result::deleted();
8524 }
8525 auto *Info = S.Context.CompCategories.lookupInfoForType(
8526 Ty: BestFD->getCallResultType());
8527 if (!Info) {
8528 if (Diagnose == ExplainDeleted) {
8529 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8530 << Subobj.Kind << Subobj.Decl
8531 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8532 S.Diag(Loc: BestFD->getLocation(),
8533 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8534 << Subobj.Kind << Subobj.Decl;
8535 }
8536 return Result::deleted();
8537 }
8538 R.Category = Info->Kind;
8539 }
8540 } else {
8541 QualType T = Best->BuiltinParamTypes[0];
8542 assert(T == Best->BuiltinParamTypes[1] &&
8543 "builtin comparison for different types?");
8544 assert(Best->BuiltinParamTypes[2].isNull() &&
8545 "invalid builtin comparison");
8546
8547 // FIXME: If the type we deduced is a vector type, we mark the
8548 // comparison as deleted because we don't yet support this.
8549 if (isa<VectorType>(Val: T)) {
8550 if (Diagnose == ExplainDeleted) {
8551 S.Diag(Loc: FD->getLocation(),
8552 DiagID: diag::note_defaulted_comparison_vector_types)
8553 << FD;
8554 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8555 }
8556 return Result::deleted();
8557 }
8558
8559 if (NeedsDeducing) {
8560 std::optional<ComparisonCategoryType> Cat =
8561 getComparisonCategoryForBuiltinCmp(T);
8562 assert(Cat && "no category for builtin comparison?");
8563 R.Category = *Cat;
8564 }
8565 }
8566
8567 // Note that we might be rewriting to a different operator. That call is
8568 // not considered until we come to actually build the comparison function.
8569 break;
8570 }
8571
8572 case OR_Ambiguous:
8573 if (Diagnose == ExplainDeleted) {
8574 unsigned Kind = 0;
8575 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8576 Kind = OO == OO_EqualEqual ? 1 : 2;
8577 CandidateSet.NoteCandidates(
8578 PA: PartialDiagnosticAt(
8579 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8580 << FD << Kind << Subobj.Kind << Subobj.Decl),
8581 S, OCD: OCD_AmbiguousCandidates, Args);
8582 }
8583 R = Result::deleted();
8584 break;
8585
8586 case OR_Deleted:
8587 if (Diagnose == ExplainDeleted) {
8588 if ((DCK == DefaultedComparisonKind::NotEqual ||
8589 DCK == DefaultedComparisonKind::Relational) &&
8590 !Best->RewriteKind) {
8591 S.Diag(Loc: Best->Function->getLocation(),
8592 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8593 << FD;
8594 } else {
8595 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_function_calls_deleted)
8596 << FD << /*comparison function*/ 4 << Subobj.Kind << Subobj.Decl;
8597 S.NoteDeletedFunction(FD: Best->Function);
8598 }
8599 }
8600 R = Result::deleted();
8601 break;
8602
8603 case OR_No_Viable_Function:
8604 // If there's no usable candidate, we're done unless we can rewrite a
8605 // '<=>' in terms of '==' and '<'.
8606 if (OO == OO_Spaceship &&
8607 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8608 // For any kind of comparison category return type, we need a usable
8609 // '==' and a usable '<'.
8610 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8611 SpaceshipCandidates: &CandidateSet)))
8612 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8613 break;
8614 }
8615
8616 if (Diagnose == ExplainDeleted) {
8617 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8618 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8619 << Subobj.Kind << Subobj.Decl;
8620
8621 // For a three-way comparison, list both the candidates for the
8622 // original operator and the candidates for the synthesized operator.
8623 if (SpaceshipCandidates) {
8624 SpaceshipCandidates->NoteCandidates(
8625 S, Args,
8626 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8627 Args, OpLoc: FD->getLocation()));
8628 S.Diag(Loc: Subobj.Loc,
8629 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8630 << (OO == OO_EqualEqual ? 0 : 1);
8631 }
8632
8633 CandidateSet.NoteCandidates(
8634 S, Args,
8635 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8636 OpLoc: FD->getLocation()));
8637 }
8638 R = Result::deleted();
8639 break;
8640 }
8641
8642 return R;
8643 }
8644};
8645
8646/// A list of statements.
8647struct StmtListResult {
8648 bool IsInvalid = false;
8649 llvm::SmallVector<Stmt*, 16> Stmts;
8650
8651 bool add(const StmtResult &S) {
8652 IsInvalid |= S.isInvalid();
8653 if (IsInvalid)
8654 return true;
8655 Stmts.push_back(Elt: S.get());
8656 return false;
8657 }
8658};
8659
8660/// A visitor over the notional body of a defaulted comparison that synthesizes
8661/// the actual body.
8662class DefaultedComparisonSynthesizer
8663 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8664 StmtListResult, StmtResult,
8665 std::pair<ExprResult, ExprResult>> {
8666 SourceLocation Loc;
8667 unsigned ArrayDepth = 0;
8668
8669public:
8670 using Base = DefaultedComparisonVisitor;
8671 using ExprPair = std::pair<ExprResult, ExprResult>;
8672
8673 friend Base;
8674
8675 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8676 DefaultedComparisonKind DCK,
8677 SourceLocation BodyLoc)
8678 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8679
8680 /// Build a suitable function body for this defaulted comparison operator.
8681 StmtResult build() {
8682 Sema::CompoundScopeRAII CompoundScope(S);
8683
8684 StmtListResult Stmts = visit();
8685 if (Stmts.IsInvalid)
8686 return StmtError();
8687
8688 ExprResult RetVal;
8689 switch (DCK) {
8690 case DefaultedComparisonKind::None:
8691 llvm_unreachable("not a defaulted comparison");
8692
8693 case DefaultedComparisonKind::Equal: {
8694 // C++2a [class.eq]p3:
8695 // [...] compar[e] the corresponding elements [...] until the first
8696 // index i where xi == yi yields [...] false. If no such index exists,
8697 // V is true. Otherwise, V is false.
8698 //
8699 // Join the comparisons with '&&'s and return the result. Use a right
8700 // fold (traversing the conditions right-to-left), because that
8701 // short-circuits more naturally.
8702 auto OldStmts = std::move(Stmts.Stmts);
8703 Stmts.Stmts.clear();
8704 ExprResult CmpSoFar;
8705 // Finish a particular comparison chain.
8706 auto FinishCmp = [&] {
8707 if (Expr *Prior = CmpSoFar.get()) {
8708 // Convert the last expression to 'return ...;'
8709 if (RetVal.isUnset() && Stmts.Stmts.empty())
8710 RetVal = CmpSoFar;
8711 // Convert any prior comparison to 'if (!(...)) return false;'
8712 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8713 return true;
8714 CmpSoFar = ExprResult();
8715 }
8716 return false;
8717 };
8718 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8719 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8720 if (!E) {
8721 // Found an array comparison.
8722 if (FinishCmp() || Stmts.add(S: EAsStmt))
8723 return StmtError();
8724 continue;
8725 }
8726
8727 if (CmpSoFar.isUnset()) {
8728 CmpSoFar = E;
8729 continue;
8730 }
8731 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8732 if (CmpSoFar.isInvalid())
8733 return StmtError();
8734 }
8735 if (FinishCmp())
8736 return StmtError();
8737 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8738 // If no such index exists, V is true.
8739 if (RetVal.isUnset())
8740 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8741 break;
8742 }
8743
8744 case DefaultedComparisonKind::ThreeWay: {
8745 // Per C++2a [class.spaceship]p3, as a fallback add:
8746 // return static_cast<R>(std::strong_ordering::equal);
8747 QualType StrongOrdering = S.CheckComparisonCategoryType(
8748 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8749 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8750 if (StrongOrdering.isNull())
8751 return StmtError();
8752 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8753 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8754 ->VD;
8755 RetVal = getDecl(VD: EqualVD);
8756 if (RetVal.isInvalid())
8757 return StmtError();
8758 RetVal = buildStaticCastToR(E: RetVal.get());
8759 break;
8760 }
8761
8762 case DefaultedComparisonKind::NotEqual:
8763 case DefaultedComparisonKind::Relational:
8764 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8765 break;
8766 }
8767
8768 // Build the final return statement.
8769 if (RetVal.isInvalid())
8770 return StmtError();
8771 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8772 if (ReturnStmt.isInvalid())
8773 return StmtError();
8774 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8775
8776 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8777 }
8778
8779private:
8780 ExprResult getDecl(ValueDecl *VD) {
8781 return S.BuildDeclarationNameExpr(
8782 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8783 }
8784
8785 ExprResult getParam(unsigned I) {
8786 ParmVarDecl *PD = FD->getParamDecl(i: I);
8787 return getDecl(VD: PD);
8788 }
8789
8790 ExprPair getCompleteObject() {
8791 unsigned Param = 0;
8792 ExprResult LHS;
8793 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8794 MD && MD->isImplicitObjectMemberFunction()) {
8795 // LHS is '*this'.
8796 LHS = S.ActOnCXXThis(Loc);
8797 if (!LHS.isInvalid())
8798 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8799 } else {
8800 LHS = getParam(I: Param++);
8801 }
8802 ExprResult RHS = getParam(I: Param++);
8803 assert(Param == FD->getNumParams());
8804 return {LHS, RHS};
8805 }
8806
8807 ExprPair getBase(CXXBaseSpecifier *Base) {
8808 ExprPair Obj = getCompleteObject();
8809 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8810 return {ExprError(), ExprError()};
8811 CXXCastPath Path = {Base};
8812 const auto CastToBase = [&](Expr *E) {
8813 QualType ToType = S.Context.getQualifiedType(
8814 T: Base->getType(), Qs: E->getType().getQualifiers());
8815 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8816 };
8817 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8818 }
8819
8820 ExprPair getField(FieldDecl *Field) {
8821 ExprPair Obj = getCompleteObject();
8822 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8823 return {ExprError(), ExprError()};
8824
8825 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8826 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8827 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8828 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8829 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8830 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8831 }
8832
8833 // FIXME: When expanding a subobject, register a note in the code synthesis
8834 // stack to say which subobject we're comparing.
8835
8836 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8837 if (Cond.isInvalid())
8838 return StmtError();
8839
8840 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8841 if (NotCond.isInvalid())
8842 return StmtError();
8843
8844 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8845 assert(!False.isInvalid() && "should never fail");
8846 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8847 if (ReturnFalse.isInvalid())
8848 return StmtError();
8849
8850 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8851 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8852 CK: Sema::ConditionKind::Boolean),
8853 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8854 }
8855
8856 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8857 ExprPair Subobj) {
8858 QualType SizeType = S.Context.getSizeType();
8859 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8860
8861 // Build 'size_t i$n = 0'.
8862 IdentifierInfo *IterationVarName = nullptr;
8863 {
8864 SmallString<8> Str;
8865 llvm::raw_svector_ostream OS(Str);
8866 OS << "i" << ArrayDepth;
8867 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8868 }
8869 VarDecl *IterationVar = VarDecl::Create(
8870 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8871 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8872 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8873 IterationVar->setInit(
8874 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8875 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8876
8877 auto IterRef = [&] {
8878 ExprResult Ref = S.BuildDeclarationNameExpr(
8879 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8880 D: IterationVar);
8881 assert(!Ref.isInvalid() && "can't reference our own variable?");
8882 return Ref.get();
8883 };
8884
8885 // Build 'i$n != Size'.
8886 ExprResult Cond = S.CreateBuiltinBinOp(
8887 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8888 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8889 assert(!Cond.isInvalid() && "should never fail");
8890
8891 // Build '++i$n'.
8892 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8893 assert(!Inc.isInvalid() && "should never fail");
8894
8895 // Build 'a[i$n]' and 'b[i$n]'.
8896 auto Index = [&](ExprResult E) {
8897 if (E.isInvalid())
8898 return ExprError();
8899 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8900 };
8901 Subobj.first = Index(Subobj.first);
8902 Subobj.second = Index(Subobj.second);
8903
8904 // Compare the array elements.
8905 ++ArrayDepth;
8906 StmtResult Substmt = visitSubobject(Type, Subobj);
8907 --ArrayDepth;
8908
8909 if (Substmt.isInvalid())
8910 return StmtError();
8911
8912 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8913 // For outer levels or for an 'operator<=>' we already have a suitable
8914 // statement that returns as necessary.
8915 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8916 assert(DCK == DefaultedComparisonKind::Equal &&
8917 "should have non-expression statement");
8918 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8919 if (Substmt.isInvalid())
8920 return StmtError();
8921 }
8922
8923 // Build 'for (...) ...'
8924 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8925 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8926 CK: Sema::ConditionKind::Boolean),
8927 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8928 Body: Substmt.get());
8929 }
8930
8931 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8932 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8933 return StmtError();
8934
8935 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8936 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8937 ExprResult Op;
8938 if (Type->isOverloadableType())
8939 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8940 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8941 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8942 else
8943 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8944 if (Op.isInvalid())
8945 return StmtError();
8946
8947 switch (DCK) {
8948 case DefaultedComparisonKind::None:
8949 llvm_unreachable("not a defaulted comparison");
8950
8951 case DefaultedComparisonKind::Equal:
8952 // Per C++2a [class.eq]p2, each comparison is individually contextually
8953 // converted to bool.
8954 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8955 if (Op.isInvalid())
8956 return StmtError();
8957 return Op.get();
8958
8959 case DefaultedComparisonKind::ThreeWay: {
8960 // Per C++2a [class.spaceship]p3, form:
8961 // if (R cmp = static_cast<R>(op); cmp != 0)
8962 // return cmp;
8963 QualType R = FD->getReturnType();
8964 Op = buildStaticCastToR(E: Op.get());
8965 if (Op.isInvalid())
8966 return StmtError();
8967
8968 // R cmp = ...;
8969 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8970 VarDecl *VD =
8971 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8972 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8973 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8974 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8975
8976 // cmp != 0
8977 ExprResult VDRef = getDecl(VD);
8978 if (VDRef.isInvalid())
8979 return StmtError();
8980 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8981 Expr *Zero =
8982 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8983 ExprResult Comp;
8984 if (VDRef.get()->getType()->isOverloadableType())
8985 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8986 AllowRewrittenCandidates: true, DefaultedFn: FD);
8987 else
8988 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8989 if (Comp.isInvalid())
8990 return StmtError();
8991 Sema::ConditionResult Cond = S.ActOnCondition(
8992 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8993 if (Cond.isInvalid())
8994 return StmtError();
8995
8996 // return cmp;
8997 VDRef = getDecl(VD);
8998 if (VDRef.isInvalid())
8999 return StmtError();
9000 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
9001 if (ReturnStmt.isInvalid())
9002 return StmtError();
9003
9004 // if (...)
9005 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
9006 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
9007 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
9008 }
9009
9010 case DefaultedComparisonKind::NotEqual:
9011 case DefaultedComparisonKind::Relational:
9012 // C++2a [class.compare.secondary]p2:
9013 // Otherwise, the operator function yields x @ y.
9014 return Op.get();
9015 }
9016 llvm_unreachable("");
9017 }
9018
9019 /// Build "static_cast<R>(E)".
9020 ExprResult buildStaticCastToR(Expr *E) {
9021 QualType R = FD->getReturnType();
9022 assert(!R->isUndeducedType() && "type should have been deduced already");
9023
9024 // Don't bother forming a no-op cast in the common case.
9025 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
9026 return E;
9027 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
9028 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
9029 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
9030 }
9031};
9032}
9033
9034/// Perform the unqualified lookups that might be needed to form a defaulted
9035/// comparison function for the given operator.
9036static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
9037 UnresolvedSetImpl &Operators,
9038 OverloadedOperatorKind Op) {
9039 auto Lookup = [&](OverloadedOperatorKind OO) {
9040 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
9041 };
9042
9043 // Every defaulted operator looks up itself.
9044 Lookup(Op);
9045 // ... and the rewritten form of itself, if any.
9046 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
9047 Lookup(ExtraOp);
9048
9049 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9050 // synthesize a three-way comparison from '<' and '=='. In a dependent
9051 // context, we also need to look up '==' in case we implicitly declare a
9052 // defaulted 'operator=='.
9053 if (Op == OO_Spaceship) {
9054 Lookup(OO_ExclaimEqual);
9055 Lookup(OO_Less);
9056 Lookup(OO_EqualEqual);
9057 }
9058}
9059
9060bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
9061 DefaultedComparisonKind DCK) {
9062 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9063
9064 // Perform any unqualified lookups we're going to need to default this
9065 // function.
9066 if (S) {
9067 UnresolvedSet<32> Operators;
9068 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9069 Op: FD->getOverloadedOperator());
9070 FD->setDefaultedOrDeletedInfo(
9071 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9072 Context, Lookups: Operators.pairs(), FPFeatures: CurFPFeatureOverrides()));
9073 }
9074
9075 // C++2a [class.compare.default]p1:
9076 // A defaulted comparison operator function for some class C shall be a
9077 // non-template function declared in the member-specification of C that is
9078 // -- a non-static const non-volatile member of C having one parameter of
9079 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9080 // -- a friend of C having two parameters of type const C& or two
9081 // parameters of type C.
9082
9083 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9084 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9085 if (IsMethod) {
9086 auto *MD = cast<CXXMethodDecl>(Val: FD);
9087 assert(!MD->isStatic() && "comparison function cannot be a static member");
9088
9089 if (MD->getRefQualifier() == RQ_RValue) {
9090 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9091
9092 // Remove the ref qualifier to recover.
9093 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9094 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9095 EPI.RefQualifier = RQ_None;
9096 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9097 Args: FPT->getParamTypes(), EPI));
9098 }
9099
9100 // If we're out-of-class, this is the class we're comparing.
9101 if (!RD)
9102 RD = MD->getParent();
9103 QualType T = MD->getFunctionObjectParameterReferenceType();
9104 if (!T.getNonReferenceType().isConstQualified() &&
9105 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9106 SourceLocation Loc, InsertLoc;
9107 if (MD->isExplicitObjectMemberFunction()) {
9108 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9109 InsertLoc = getLocForEndOfToken(
9110 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9111 } else {
9112 Loc = MD->getLocation();
9113 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9114 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9115 }
9116 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9117 // corresponding defaulted 'operator<=>' already.
9118 if (!MD->isImplicit()) {
9119 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9120 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9121 }
9122
9123 // Add the 'const' to the type to recover.
9124 if (MD->isExplicitObjectMemberFunction()) {
9125 assert(T->isLValueReferenceType());
9126 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9127 T: T.getNonReferenceType().withConst()));
9128 } else {
9129 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9130 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9131 EPI.TypeQuals.addConst();
9132 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9133 Args: FPT->getParamTypes(), EPI));
9134 }
9135 }
9136
9137 if (MD->isVolatile()) {
9138 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9139
9140 // Remove the 'volatile' from the type to recover.
9141 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9142 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9143 EPI.TypeQuals.removeVolatile();
9144 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9145 Args: FPT->getParamTypes(), EPI));
9146 }
9147 }
9148
9149 if ((FD->getNumParams() -
9150 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9151 (IsMethod ? 1 : 2)) {
9152 // Let's not worry about using a variadic template pack here -- who would do
9153 // such a thing?
9154 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9155 << int(IsMethod) << int(DCK);
9156 return true;
9157 }
9158
9159 const ParmVarDecl *KnownParm = nullptr;
9160 for (const ParmVarDecl *Param : FD->parameters()) {
9161 QualType ParmTy = Param->getType();
9162 if (!KnownParm) {
9163 auto CTy = ParmTy;
9164 // Is it `T const &`?
9165 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9166 QualType ExpectedTy;
9167 if (RD)
9168 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9169 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9170 CTy = Ref->getPointeeType();
9171 if (RD)
9172 ExpectedTy.addConst();
9173 Ok = true;
9174 }
9175
9176 // Is T a class?
9177 if (RD) {
9178 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9179 } else {
9180 RD = CTy->getAsCXXRecordDecl();
9181 Ok &= RD != nullptr;
9182 }
9183
9184 if (Ok) {
9185 KnownParm = Param;
9186 } else {
9187 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9188 // corresponding defaulted 'operator<=>' already.
9189 if (!FD->isImplicit()) {
9190 if (RD) {
9191 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9192 QualType RefTy =
9193 Context.getLValueReferenceType(T: PlainTy.withConst());
9194 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9195 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9196 << Param->getSourceRange();
9197 } else {
9198 assert(!IsMethod && "should know expected type for method");
9199 Diag(Loc: FD->getLocation(),
9200 DiagID: diag::err_defaulted_comparison_param_unknown)
9201 << int(DCK) << ParmTy << Param->getSourceRange();
9202 }
9203 }
9204 return true;
9205 }
9206 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9207 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9208 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9209 << ParmTy << Param->getSourceRange();
9210 return true;
9211 }
9212 }
9213
9214 assert(RD && "must have determined class");
9215 if (IsMethod) {
9216 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9217 // In-class, must be a friend decl.
9218 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9219 } else {
9220 // Out of class, require the defaulted comparison to be a friend (of a
9221 // complete type, per CWG2547).
9222 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9223 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9224 Args: int(1)))
9225 return true;
9226
9227 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9228 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9229 })) {
9230 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9231 << int(DCK) << int(0) << RD;
9232 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9233 return true;
9234 }
9235 }
9236
9237 // C++2a [class.eq]p1, [class.rel]p1:
9238 // A [defaulted comparison other than <=>] shall have a declared return
9239 // type bool.
9240 if (DCK != DefaultedComparisonKind::ThreeWay &&
9241 !FD->getDeclaredReturnType()->isDependentType() &&
9242 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9243 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9244 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9245 << FD->getReturnTypeSourceRange();
9246 return true;
9247 }
9248 // C++2a [class.spaceship]p2 [P2002R0]:
9249 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9250 // R shall not contain a placeholder type.
9251 if (QualType RT = FD->getDeclaredReturnType();
9252 DCK == DefaultedComparisonKind::ThreeWay &&
9253 RT->getContainedDeducedType() &&
9254 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9255 RT->getContainedAutoType()->isConstrained())) {
9256 Diag(Loc: FD->getLocation(),
9257 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9258 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9259 << FD->getReturnTypeSourceRange();
9260 return true;
9261 }
9262
9263 // For a defaulted function in a dependent class, defer all remaining checks
9264 // until instantiation.
9265 if (RD->isDependentType())
9266 return false;
9267
9268 // Determine whether the function should be defined as deleted.
9269 DefaultedComparisonInfo Info =
9270 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9271
9272 bool First = FD == FD->getCanonicalDecl();
9273
9274 if (!First) {
9275 if (Info.Deleted) {
9276 // C++11 [dcl.fct.def.default]p4:
9277 // [For a] user-provided explicitly-defaulted function [...] if such a
9278 // function is implicitly defined as deleted, the program is ill-formed.
9279 //
9280 // This is really just a consequence of the general rule that you can
9281 // only delete a function on its first declaration.
9282 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9283 << FD->isImplicit() << (int)DCK;
9284 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9285 DefaultedComparisonAnalyzer::ExplainDeleted)
9286 .visit();
9287 return true;
9288 }
9289 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9290 // C++20 [class.compare.default]p1:
9291 // [...] A definition of a comparison operator as defaulted that appears
9292 // in a class shall be the first declaration of that function.
9293 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9294 << (int)DCK;
9295 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9296 DiagID: diag::note_previous_declaration);
9297 return true;
9298 }
9299 }
9300
9301 // If we want to delete the function, then do so; there's nothing else to
9302 // check in that case.
9303 if (Info.Deleted) {
9304 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9305 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9306 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9307 << (int)DCK;
9308 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9309 DefaultedComparisonAnalyzer::ExplainDeleted)
9310 .visit();
9311 if (FD->getDefaultLoc().isValid())
9312 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9313 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9314 }
9315 return false;
9316 }
9317
9318 // C++2a [class.spaceship]p2:
9319 // The return type is deduced as the common comparison type of R0, R1, ...
9320 if (DCK == DefaultedComparisonKind::ThreeWay &&
9321 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9322 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9323 if (RetLoc.isInvalid())
9324 RetLoc = FD->getBeginLoc();
9325 // FIXME: Should we really care whether we have the complete type and the
9326 // 'enumerator' constants here? A forward declaration seems sufficient.
9327 QualType Cat = CheckComparisonCategoryType(
9328 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9329 if (Cat.isNull())
9330 return true;
9331 Context.adjustDeducedFunctionResultType(
9332 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9333 }
9334
9335 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9336 // An explicitly-defaulted function that is not defined as deleted may be
9337 // declared constexpr or consteval only if it is constexpr-compatible.
9338 // C++2a [class.compare.default]p3 [P2002R0]:
9339 // A defaulted comparison function is constexpr-compatible if it satisfies
9340 // the requirements for a constexpr function [...]
9341 // The only relevant requirements are that the parameter and return types are
9342 // literal types. The remaining conditions are checked by the analyzer.
9343 //
9344 // We support P2448R2 in language modes earlier than C++23 as an extension.
9345 // The concept of constexpr-compatible was removed.
9346 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9347 // A function explicitly defaulted on its first declaration is implicitly
9348 // inline, and is implicitly constexpr if it is constexpr-suitable.
9349 // C++23 [dcl.constexpr]p3
9350 // A function is constexpr-suitable if
9351 // - it is not a coroutine, and
9352 // - if the function is a constructor or destructor, its class does not
9353 // have any virtual base classes.
9354 if (FD->isConstexpr()) {
9355 if (!getLangOpts().CPlusPlus23 &&
9356 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9357 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9358 !Info.Constexpr) {
9359 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9360 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9361 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9362 DefaultedComparisonAnalyzer::ExplainConstexpr)
9363 .visit();
9364 }
9365 }
9366
9367 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9368 // If a constexpr-compatible function is explicitly defaulted on its first
9369 // declaration, it is implicitly considered to be constexpr.
9370 // FIXME: Only applying this to the first declaration seems problematic, as
9371 // simple reorderings can affect the meaning of the program.
9372 if (First && !FD->isConstexpr() && Info.Constexpr)
9373 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9374
9375 // C++2a [except.spec]p3:
9376 // If a declaration of a function does not have a noexcept-specifier
9377 // [and] is defaulted on its first declaration, [...] the exception
9378 // specification is as specified below
9379 if (FD->getExceptionSpecType() == EST_None) {
9380 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9381 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9382 EPI.ExceptionSpec.Type = EST_Unevaluated;
9383 EPI.ExceptionSpec.SourceDecl = FD;
9384 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9385 Args: FPT->getParamTypes(), EPI));
9386 }
9387
9388 return false;
9389}
9390
9391void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9392 FunctionDecl *Spaceship) {
9393 Sema::CodeSynthesisContext Ctx;
9394 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9395 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9396 Ctx.Entity = Spaceship;
9397 pushCodeSynthesisContext(Ctx);
9398
9399 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9400 EqualEqual->setImplicit();
9401
9402 popCodeSynthesisContext();
9403}
9404
9405/// Define a defaulted function whose body is synthesized by \p BuildBody: a
9406/// defaulted comparison operator function or a defaulted postfix increment or
9407/// decrement operator function.
9408static void defineDefaultedFunctionWithSynthesizedBody(
9409 Sema &S, SourceLocation UseLoc, FunctionDecl *FD,
9410 llvm::function_ref<StmtResult(SourceLocation BodyLoc)> BuildBody) {
9411 assert(FD->isDefaulted() && !FD->isDeleted() &&
9412 !FD->doesThisDeclarationHaveABody());
9413 if (FD->willHaveBody() || FD->isInvalidDecl())
9414 return;
9415
9416 Sema::SynthesizedFunctionScope Scope(S, FD);
9417
9418 // Add a context note for diagnostics produced after this point.
9419 Scope.addContextNote(UseLoc);
9420
9421 DefaultedFunctionFPFeaturesRAII RestoreFP(S, FD);
9422
9423 {
9424 // Build and set up the function body.
9425 SourceLocation BodyLoc =
9426 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9427 StmtResult Body = BuildBody(BodyLoc);
9428 if (Body.isInvalid()) {
9429 FD->setInvalidDecl();
9430 return;
9431 }
9432 FD->setBody(Body.get());
9433 FD->markUsed(C&: S.Context);
9434 }
9435
9436 // The exception specification is needed because we are defining the
9437 // function. Note that this will reuse the body we just built.
9438 S.ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9439
9440 if (ASTMutationListener *L = S.getASTMutationListener())
9441 L->CompletedImplicitDefinition(D: FD);
9442}
9443
9444void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9445 DefaultedComparisonKind DCK) {
9446 auto BuildBody = [&](SourceLocation BodyLoc) {
9447 // The first parameter has type maybe-ref-to maybe-const T, use that to
9448 // get the type of the class being compared.
9449 auto PT = FD->getParamDecl(i: 0)->getType();
9450 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9451 return DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9452 };
9453 defineDefaultedFunctionWithSynthesizedBody(S&: *this, UseLoc, FD, BuildBody);
9454}
9455
9456/// Compute the exception specification of a defaulted function whose body is
9457/// synthesized by \p BuildBody: a defaulted comparison operator function or a
9458/// defaulted postfix increment or decrement operator function.
9459static Sema::ImplicitExceptionSpecification
9460computeExceptionSpecFromSynthesizedBody(
9461 Sema &S, SourceLocation Loc, FunctionDecl *FD,
9462 llvm::function_ref<StmtResult(SourceLocation BodyLoc)> BuildBody) {
9463 ComputingExceptionSpec CES(S, FD, Loc);
9464 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9465
9466 if (FD->isInvalidDecl())
9467 return ExceptSpec;
9468
9469 // The common case is that we just defined the function. In that case, just
9470 // look at whether the body can throw.
9471 if (Stmt *FunctionBody = FD->getBody()) {
9472 ExceptSpec.CalledStmt(S: FunctionBody);
9473 } else {
9474 // Otherwise, build a body so we can check it. This should ideally only
9475 // happen when we're not actually marking the function referenced. (This is
9476 // only really important for efficiency: we don't want to build and throw
9477 // away bodies for defaulted functions more than we strictly need to.)
9478
9479 // Pretend to synthesize the function body in an unevaluated context.
9480 // Note that we can't actually just go ahead and define the function here:
9481 // we are not permitted to mark its callees as referenced.
9482 Sema::SynthesizedFunctionScope Scope(S, FD);
9483 EnterExpressionEvaluationContext Context(
9484 S, Sema::ExpressionEvaluationContext::Unevaluated);
9485
9486 SourceLocation BodyLoc =
9487 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9488 StmtResult Body = BuildBody(BodyLoc);
9489 if (!Body.isInvalid())
9490 ExceptSpec.CalledStmt(S: Body.get());
9491
9492 // FIXME: Can we hold onto this body and just transform it to potentially
9493 // evaluated when we're asked to define the function rather than rebuilding
9494 // it? Either that, or we should only build the bits of the body that we
9495 // need (the expressions, not the statements).
9496 }
9497
9498 return ExceptSpec;
9499}
9500
9501static Sema::ImplicitExceptionSpecification
9502ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9503 FunctionDecl *FD,
9504 DefaultedComparisonKind DCK) {
9505 auto BuildBody = [&](SourceLocation BodyLoc) {
9506 CXXRecordDecl *RD =
9507 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9508 ? FD->getDeclContext()
9509 : FD->getLexicalDeclContext());
9510 return DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9511 };
9512 return computeExceptionSpecFromSynthesizedBody(S, Loc, FD, BuildBody);
9513}
9514
9515// C++2d [over.inc.default]: defaulted postfix increment and decrement operator
9516// functions (P3668R4).
9517
9518namespace {
9519/// Information about a defaulted postfix increment or decrement operator
9520/// function, as determined by analyzeDefaultedPostfixOperator.
9521struct DefaultedPostfixOperatorInfo {
9522 /// Whether the function should be defined as deleted.
9523 bool Deleted = false;
9524 /// Whether every function invoked by the implicit definition is constexpr.
9525 bool Constexpr = true;
9526};
9527} // namespace
9528
9529/// Get the type of the first parameter of a postfix increment or decrement
9530/// operator function, where the implicit object parameter (if any) is
9531/// considered to be the first parameter.
9532static QualType getPostfixOperatorFirstParamType(const FunctionDecl *FD) {
9533 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
9534 return MD->getFunctionObjectParameterReferenceType();
9535 return FD->getParamDecl(i: 0)->getType();
9536}
9537
9538/// Determine whether the implicit definition of the defaulted postfix
9539/// increment or decrement operator function \p FD can direct-initialize a
9540/// variable of class type \p C from the lvalue \p Obj of type \p C, and then
9541/// destroy it, using functions that are usable from the current context.
9542///
9543/// \p CheckConstexpr is called on each constructor the initialization invokes.
9544/// If \p Diagnose is true, explain why the copy or destruction is not possible.
9545static bool canCopyAndDestroyForDefaultedPostfixOperator(
9546 Sema &S, FunctionDecl *FD, CXXRecordDecl *RD, QualType C, Expr *Obj,
9547 bool Diagnose,
9548 llvm::function_ref<void(const FunctionDecl *)> CheckConstexpr) {
9549 SourceLocation Loc = FD->getLocation();
9550 auto InaccessibleDiag = [&](unsigned Step) {
9551 return Diagnose
9552 ? S.PDiag(DiagID: diag::note_defaulted_postfix_operator_inaccessible)
9553 << FD << Step
9554 : S.PDiag();
9555 };
9556
9557 InitializedEntity Entity = InitializedEntity::InitializeTemporary(Type: C);
9558 InitializationKind InitKind = InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: Loc, RParenLoc: Loc);
9559 InitializationSequence Seq(S, Entity, InitKind, Obj);
9560 if (Seq.Failed()) {
9561 // FIXME: This emits errors rather than notes explaining why the function
9562 // is deleted.
9563 if (Diagnose)
9564 Seq.Diagnose(S, Entity, Kind: InitKind, Args: Obj);
9565 return false;
9566 }
9567 for (const InitializationSequence::Step &Step : Seq.steps()) {
9568 if (Step.Kind != InitializationSequence::SK_ConstructorInitialization)
9569 continue;
9570 if (!S.isMemberAccessibleForDeletion(
9571 NamingClass: RD, Found: Step.Function.FoundDecl, ObjectType: C, Loc,
9572 Diag: InaccessibleDiag(diag::DefaultedPostfixOperatorStep::Constructor)))
9573 return false;
9574 CheckConstexpr(Step.Function.Function);
9575 }
9576
9577 CXXDestructorDecl *Dtor = S.LookupDestructor(Class: RD);
9578 if (!Dtor)
9579 return true;
9580 if (Dtor->isDeleted()) {
9581 if (Diagnose) {
9582 S.Diag(Loc, DiagID: diag::note_defaulted_function_calls_deleted)
9583 << FD << diag::DefaultedPostfixOperatorStep::Destructor
9584 << /*complete object*/ 0;
9585 S.NoteDeletedFunction(FD: Dtor);
9586 }
9587 return false;
9588 }
9589 return S.isMemberAccessibleForDeletion(
9590 NamingClass: RD, Found: DeclAccessPair::make(D: Dtor, AS: Dtor->getAccess()), ObjectType: C, Loc,
9591 Diag: InaccessibleDiag(diag::DefaultedPostfixOperatorStep::Destructor));
9592}
9593
9594/// Determine whether a defaulted postfix increment or decrement operator
9595/// function for type \p C should be defined as deleted, as specified in C++2d
9596/// [over.inc.default]p2, and whether every function it would invoke is
9597/// constexpr.
9598///
9599/// If \p Diagnose is true, explain why the function is defined as deleted.
9600static DefaultedPostfixOperatorInfo
9601analyzeDefaultedPostfixOperator(Sema &S, FunctionDecl *FD,
9602 PostfixOperatorKind Kind, QualType C,
9603 bool Diagnose) {
9604 DefaultedPostfixOperatorInfo Info;
9605 SourceLocation Loc = FD->getLocation();
9606
9607 // C++2d [over.inc.default]p1:
9608 // Name lookups and access checks in the implicit definition of a defaulted
9609 // postfix increment or decrement operator function are performed from a
9610 // context equivalent to its function-body.
9611 Sema::ContextRAII SavedContext(S, FD);
9612
9613 // Let c be an lvalue of type C. c stands for the first parameter (or the
9614 // implicit object), which is always an lvalue when named in the function
9615 // body, even if it is declared as an rvalue reference.
9616 OpaqueValueExpr Obj(Loc, C, VK_LValue);
9617 Expr *Args[] = {&Obj};
9618
9619 auto Deleted = [&] {
9620 Info.Deleted = true;
9621 return Info;
9622 };
9623 auto InaccessibleDiag = [&](unsigned Step) {
9624 return Diagnose
9625 ? S.PDiag(DiagID: diag::note_defaulted_postfix_operator_inaccessible)
9626 << FD << Step
9627 : S.PDiag();
9628 };
9629 auto NoteCallsDeleted = [&](unsigned Step, FunctionDecl *Callee) {
9630 if (!Diagnose)
9631 return;
9632 S.Diag(Loc, DiagID: diag::note_defaulted_function_calls_deleted)
9633 << FD << Step << /*complete object*/ 0;
9634 if (Callee)
9635 S.NoteDeletedFunction(FD: Callee);
9636 };
9637 auto CheckConstexpr = [&](const FunctionDecl *Callee) {
9638 if (!Callee->isConstexpr())
9639 Info.Constexpr = false;
9640 };
9641
9642 // C++2d [over.inc.default]p2:
9643 // A defaulted postfix increment or decrement operator function for a type
9644 // C is defined as deleted if
9645 // -- C is a class type for which overload resolution, as applied to
9646 // direct-initialization of a variable of type C from an lvalue of
9647 // type C, does not result in a usable candidate,
9648 // -- C has a destructor that is deleted or inaccessible from the context
9649 // of the function-body, or
9650 CXXRecordDecl *RD = C->getAsCXXRecordDecl();
9651 if (RD && !canCopyAndDestroyForDefaultedPostfixOperator(
9652 S, FD, RD, C, Obj: &Obj, Diagnose, CheckConstexpr))
9653 return Deleted();
9654
9655 // -- for an lvalue c of type C, overload resolution as applied to ++c for a
9656 // postfix increment operator function or --c for a postfix decrement
9657 // operator function does not result in a usable candidate.
9658 bool IsIncrement = Kind == PostfixOperatorKind::Increment;
9659 unsigned PrefixStep =
9660 IsIncrement ? diag::DefaultedPostfixOperatorStep::PrefixIncrement
9661 : diag::DefaultedPostfixOperatorStep::PrefixDecrement;
9662 UnresolvedSet<2> Fns;
9663 if (auto *DFI = FD->getDefaultedOrDeletedInfo())
9664 Fns.assign(I: DFI->getUnqualifiedLookups().begin(),
9665 E: DFI->getUnqualifiedLookups().end());
9666 OverloadCandidateSet CandidateSet(Loc, OverloadCandidateSet::CSK_Operator);
9667 S.LookupOverloadedUnaryOp(
9668 CandidateSet, Op: IsIncrement ? OO_PlusPlus : OO_MinusMinus, Fns, Args);
9669
9670 OverloadCandidateSet::iterator Best;
9671 switch (CandidateSet.BestViableFunction(S, Loc, Best)) {
9672 case OR_Success:
9673 if (FunctionDecl *Prefix = Best->Function) {
9674 // Only a member of C can be inaccessible here; the non-member
9675 // candidates were found by unqualified lookup and ADL.
9676 if (RD && Best->FoundDecl.getDecl() &&
9677 Best->FoundDecl.getDecl()->isCXXClassMember() &&
9678 !S.isMemberAccessibleForDeletion(NamingClass: RD, Found: Best->FoundDecl, ObjectType: C, Loc,
9679 Diag: InaccessibleDiag(PrefixStep)))
9680 return Deleted();
9681 CheckConstexpr(Prefix);
9682 } else if (!Best->Conversions.empty() &&
9683 Best->Conversions[0].isUserDefined()) {
9684 // A built-in candidate, reached through a conversion function.
9685 CheckConstexpr(Best->Conversions[0].UserDefined.ConversionFunction);
9686 }
9687 break;
9688
9689 case OR_Ambiguous:
9690 if (Diagnose)
9691 CandidateSet.NoteCandidates(
9692 PA: PartialDiagnosticAt(
9693 Loc, S.PDiag(DiagID: diag::note_defaulted_postfix_operator_ambiguous)
9694 << FD << !IsIncrement << C),
9695 S, OCD: OCD_AmbiguousCandidates, Args, Opc: IsIncrement ? "++" : "--", Loc);
9696 return Deleted();
9697
9698 case OR_Deleted:
9699 NoteCallsDeleted(PrefixStep, Best->Function);
9700 return Deleted();
9701
9702 case OR_No_Viable_Function:
9703 // Don't list the non-viable candidates: like for any other unary operator,
9704 // the candidate notes can't sensibly describe an arity mismatch for a
9705 // member postfix operator (whose object argument is not a parameter).
9706 if (Diagnose)
9707 S.Diag(Loc, DiagID: diag::note_defaulted_postfix_operator_no_viable)
9708 << FD << !IsIncrement << C;
9709 return Deleted();
9710 }
9711
9712 return Info;
9713}
9714
9715bool Sema::CheckExplicitlyDefaultedPostfixOperator(Scope *S, FunctionDecl *FD,
9716 PostfixOperatorKind Kind) {
9717 assert(Kind != PostfixOperatorKind::None &&
9718 "not a defaulted postfix operator");
9719 bool IsIncrement = Kind == PostfixOperatorKind::Increment;
9720
9721 // Perform the unqualified lookup of the prefix operator that the implicit
9722 // definition needs. C++2d [over.inc.default]p1:
9723 // Name lookups and access checks in the implicit definition of a defaulted
9724 // postfix increment or decrement operator function are performed from a
9725 // context equivalent to its function-body.
9726 // The lookup is performed from S, not from CurContext. S is either the body
9727 // scope of an out-of-line definition, or the scope of the class in which the
9728 // function is defaulted on its first declaration; for a lookup that ignores
9729 // member functions, both are equivalent to the function-body.
9730 if (S) {
9731 assert((S->getEntity() == FD ||
9732 S->getEntity() == FD->getLexicalDeclContext()) &&
9733 "lookup scope is not equivalent to the function-body");
9734 UnresolvedSet<2> Operators;
9735 LookupOverloadedOperatorName(Op: IsIncrement ? OO_PlusPlus : OO_MinusMinus, S,
9736 Functions&: Operators);
9737 FD->setDefaultedOrDeletedInfo(
9738 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9739 Context, Lookups: Operators.pairs(), FPFeatures: CurFPFeatureOverrides()));
9740 }
9741
9742 // C++2d [over.inc.default]p1:
9743 // A defaulted postfix increment or decrement operator function for a type
9744 // C shall be a non-template function that
9745 // -- has a first parameter of type "reference to C" or a first parameter
9746 // of type "reference to volatile C", where the implicit object
9747 // parameter (if any) is considered to be the first parameter,
9748 // -- is defined as defaulted in C or in a context where C is complete,
9749 // and
9750 // -- has a declared return type of C.
9751 auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9752 ParmVarDecl *FirstParam = FD->getParamDecl(i: 0);
9753 QualType FirstParamType = getPostfixOperatorFirstParamType(FD);
9754 QualType ReturnType = FD->getDeclaredReturnType();
9755
9756 // If the first parameter type is dependent, or the function is in a dependent
9757 // context, defer all checks until instantiation.
9758 if (FirstParamType->isDependentType() || FD->isDependentContext())
9759 return false;
9760
9761 // Check the type of the first parameter and determine the type C from it.
9762 // For a member function, C is the enclosing class. For a non-member function,
9763 // C is the class or enumeration type of its first parameter;
9764 // CheckOverloadedOperatorDeclaration has already required it to have one.
9765 QualType Referent = FirstParamType.getNonReferenceType();
9766 QualType C = MD ? Context.getCanonicalTagType(TD: MD->getParent())
9767 : Referent.getUnqualifiedType();
9768 assert((C->isRecordType() || C->isEnumeralType()) &&
9769 "postfix operator for a non-class, non-enumeration type");
9770
9771 // The first parameter must be a reference to C, which may be
9772 // volatile-qualified but not const-qualified.
9773 if (!FirstParamType->isReferenceType() ||
9774 !Context.hasSameUnqualifiedType(T1: Referent, T2: C) ||
9775 Referent.isConstQualified()) {
9776 if (MD && MD->isImplicitObjectMemberFunction()) {
9777 // The implicit object parameter is always a reference to the enclosing
9778 // class, so the only possible problem is a const qualifier.
9779 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_postfix_operator_const)
9780 << (int)Kind;
9781 } else {
9782 Diag(Loc: FirstParam->getBeginLoc(),
9783 DiagID: diag::err_defaulted_postfix_operator_param)
9784 << (int)Kind << !MD << FirstParamType
9785 << Context.getLValueReferenceType(T: C) << FirstParam->getSourceRange();
9786 }
9787 return true;
9788 }
9789
9790 // A deduced return type is never permitted. Allowing it would need P2952R2
9791 // (auto& operator=(X&&) = default), which is not part of the standard.
9792 if (ReturnType->getContainedDeducedType()) {
9793 Diag(Loc: FD->getLocation(),
9794 DiagID: diag::err_defaulted_postfix_operator_deduced_return_type)
9795 << (int)Kind << FD->getReturnTypeSourceRange();
9796 return true;
9797 }
9798
9799 // -- has a declared return type of C.
9800 if (!Context.hasSameType(T1: ReturnType, T2: C)) {
9801 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_postfix_operator_return_type)
9802 << (int)Kind << C << ReturnType << FD->getReturnTypeSourceRange();
9803 return true;
9804 }
9805
9806 // -- is defined as defaulted in C or in a context where C is complete
9807 if (RequireCompleteType(Loc: FD->getLocation(), T: C,
9808 DiagID: diag::err_defaulted_postfix_operator_incomplete,
9809 Args: (int)Kind))
9810 return true;
9811
9812 // Determine whether the function should be defined as deleted.
9813 DefaultedPostfixOperatorInfo Info =
9814 analyzeDefaultedPostfixOperator(S&: *this, FD, Kind, C, /*Diagnose=*/false);
9815
9816 // An instantiated member function has a single declaration; whether it is
9817 // defaulted on its first declaration, and where, is decided by the
9818 // defaulted definition that it is instantiated from.
9819 const FunctionDecl *Defaulted = FD;
9820 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
9821 if (const FunctionDecl *PatternDef = Pattern->getDefinition())
9822 Defaulted = PatternDef;
9823 bool First = Defaulted == Defaulted->getFirstDecl();
9824
9825 if (!First) {
9826 if (Info.Deleted) {
9827 // C++11 [dcl.fct.def.default]p4:
9828 // [For a] user-provided explicitly-defaulted function [...] if such a
9829 // function is implicitly defined as deleted, the program is ill-formed.
9830 //
9831 // This is really just a consequence of the general rule that you can
9832 // only delete a function on its first declaration.
9833 Diag(Loc: FD->getLocation(),
9834 DiagID: diag::err_non_first_default_postfix_operator_deletes)
9835 << (int)Kind;
9836 analyzeDefaultedPostfixOperator(S&: *this, FD, Kind, C, /*Diagnose=*/true);
9837 return true;
9838 }
9839 if (isa<CXXRecordDecl>(Val: Defaulted->getLexicalDeclContext())) {
9840 // C++2d [over.inc.default]p1:
9841 // A definition of a postfix increment or decrement operator as
9842 // defaulted that appears in a class shall be the first declaration of
9843 // that function.
9844 Diag(Loc: FD->getLocation(),
9845 DiagID: diag::err_non_first_default_postfix_operator_in_class)
9846 << (int)Kind;
9847 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9848 DiagID: diag::note_previous_declaration);
9849 return true;
9850 }
9851 }
9852
9853 // If we want to delete the function, then do so; there's nothing else to
9854 // check in that case.
9855 if (Info.Deleted) {
9856 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9857 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9858 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_postfix_operator_deleted)
9859 << (int)Kind;
9860 analyzeDefaultedPostfixOperator(S&: *this, FD, Kind, C, /*Diagnose=*/true);
9861 if (FD->getDefaultLoc().isValid())
9862 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9863 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9864 }
9865 return false;
9866 }
9867
9868 // C++23 [dcl.fct.def.default]p3 [P2448R2] allows any defaulted function to
9869 // be declared constexpr or consteval. Before C++23, it could only be declared
9870 // so if it was constexpr-compatible; we don't apply that restriction to
9871 // defaulted postfix operators, which are an extension before C++2d.
9872
9873 if (First) {
9874 // C++11 [dcl.fct.def.default]p5:
9875 // A function explicitly defaulted on its first declaration is implicitly
9876 // inline.
9877 FD->setImplicitlyInline();
9878
9879 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9880 // If a constexpr-compatible function is explicitly defaulted on its
9881 // first declaration, it is implicitly considered to be constexpr.
9882 // C++23 [dcl.fct.def.default]p3 [P2448R2]:
9883 // A function explicitly defaulted on its first declaration is [...]
9884 // implicitly constexpr if it is constexpr-suitable.
9885 // A postfix operator function is always constexpr-suitable. The implicit
9886 // definition declares a variable, so it can only be constexpr in C++14
9887 // and later, and a virtual function can only be constexpr in C++20 and
9888 // later.
9889 if (!FD->isConstexpr() && getLangOpts().CPlusPlus14 &&
9890 (getLangOpts().CPlusPlus20 || !MD || !MD->isVirtual()) &&
9891 (getLangOpts().CPlusPlus23 ||
9892 (Info.Constexpr &&
9893 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::CheckValid) &&
9894 CheckConstexprParameterTypes(SemaRef&: *this, FD,
9895 Kind: CheckConstexprKind::CheckValid))))
9896 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9897
9898 // C++2d [except.spec]p10:
9899 // The exception specification for [...] a postfix increment or decrement
9900 // operator function without a noexcept-specifier that is defaulted on
9901 // its first declaration is potentially-throwing if and only if any
9902 // expression in the implicit definition is potentially-throwing.
9903 if (FD->getExceptionSpecType() == EST_None) {
9904 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9905 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9906 EPI.ExceptionSpec.Type = EST_Unevaluated;
9907 EPI.ExceptionSpec.SourceDecl = FD;
9908 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9909 Args: FPT->getParamTypes(), EPI));
9910 }
9911 }
9912
9913 return false;
9914}
9915
9916/// Build the body of a defaulted postfix increment or decrement operator
9917/// function. C++2d [over.inc.default]p3:
9918/// The implicit definition of a defaulted postfix increment or decrement
9919/// operator function F that is not defined as deleted for a type C is
9920/// equivalent to:
9921/// C tmp(c);
9922/// ++c; // or --c
9923/// return tmp;
9924/// where tmp is a variable defined for exposition only, and c is an lvalue
9925/// that denotes *this if F is an implicit object member function, or the
9926/// first parameter of F otherwise.
9927static StmtResult buildDefaultedPostfixOperatorBody(Sema &S, FunctionDecl *FD,
9928 PostfixOperatorKind Kind,
9929 SourceLocation Loc) {
9930 Sema::CompoundScopeRAII CompoundScope(S);
9931
9932 // Build an expression denoting 'c'.
9933 auto BuildObject = [&]() -> Expr * {
9934 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
9935 MD && MD->isImplicitObjectMemberFunction()) {
9936 ExprResult This = S.ActOnCXXThis(Loc);
9937 assert(This.isUsable() && "no 'this' in an implicit object member");
9938 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: This.get()).get();
9939 }
9940 // Diagnose the use of an unavailable or deprecated parameter. Nothing else
9941 // can make the use of a parameter in its function's body invalid.
9942 ParmVarDecl *Param = FD->getParamDecl(i: 0);
9943 [[maybe_unused]] bool Invalid = S.DiagnoseUseOfDecl(D: Param, Locs: Loc);
9944 assert(!Invalid && "invalid use of a parameter in its function's body");
9945 return S.BuildDeclRefExpr(D: Param, Ty: Param->getType().getNonReferenceType(),
9946 VK: VK_LValue, Loc);
9947 };
9948
9949 // C tmp(c);
9950 QualType C = FD->getReturnType();
9951 VarDecl *Tmp =
9952 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, /*Id=*/nullptr, T: C,
9953 TInfo: S.Context.getTrivialTypeSourceInfo(T: C, Loc), S: SC_None);
9954 Expr *InitArgs[] = {BuildObject()};
9955 S.AddInitializerToDecl(dcl: Tmp,
9956 init: ParenListExpr::Create(Ctx: S.Context, LParenLoc: Loc, Exprs: InitArgs, RParenLoc: Loc),
9957 /*DirectInit=*/true);
9958 // A failed initialization doesn't invalidate the variable, but an abstract
9959 // type C does.
9960 if (Tmp->isInvalidDecl())
9961 return StmtError();
9962 StmtResult TmpStmt = S.ActOnDeclStmt(Decl: S.ConvertDeclToDeclGroup(Ptr: Tmp), StartLoc: Loc, EndLoc: Loc);
9963 assert(TmpStmt.isUsable() && "failed to build a declaration statement");
9964
9965 // ++c; or --c;
9966 Expr *Obj = BuildObject();
9967 UnaryOperatorKind Opc =
9968 Kind == PostfixOperatorKind::Increment ? UO_PreInc : UO_PreDec;
9969 UnresolvedSet<2> Fns;
9970 if (auto *DFI = FD->getDefaultedOrDeletedInfo())
9971 Fns.assign(I: DFI->getUnqualifiedLookups().begin(),
9972 E: DFI->getUnqualifiedLookups().end());
9973 ExprResult Prefix =
9974 S.CreateOverloadedUnaryOp(OpLoc: Loc, Opc, Fns, input: Obj, /*RequiresADL=*/true);
9975 if (Prefix.isInvalid())
9976 return StmtError();
9977 StmtResult PrefixStmt = S.ActOnExprStmt(Arg: Prefix, /*DiscardedValue=*/true);
9978 if (PrefixStmt.isInvalid())
9979 return StmtError();
9980
9981 // return tmp;
9982 Expr *TmpRef = S.BuildDeclRefExpr(D: Tmp, Ty: C, VK: VK_LValue, Loc);
9983 StmtResult Return = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: TmpRef);
9984 if (Return.isInvalid())
9985 return StmtError();
9986 // 'tmp' is the only variable returned by this function, so it qualifies for
9987 // the named return value optimization.
9988 if (cast<ReturnStmt>(Val: Return.get())->getNRVOCandidate() == Tmp)
9989 Tmp->setNRVOVariable(true);
9990
9991 Stmt *Stmts[] = {TmpStmt.get(), PrefixStmt.get(), Return.get()};
9992 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts, /*IsStmtExpr=*/isStmtExpr: false);
9993}
9994
9995void Sema::DefineDefaultedPostfixOperator(SourceLocation UseLoc,
9996 FunctionDecl *FD,
9997 PostfixOperatorKind Kind) {
9998 defineDefaultedFunctionWithSynthesizedBody(
9999 S&: *this, UseLoc, FD, BuildBody: [&](SourceLocation BodyLoc) {
10000 return buildDefaultedPostfixOperatorBody(S&: *this, FD, Kind, Loc: BodyLoc);
10001 });
10002}
10003
10004static Sema::ImplicitExceptionSpecification
10005ComputeDefaultedPostfixOperatorExceptionSpec(Sema &S, SourceLocation Loc,
10006 FunctionDecl *FD,
10007 PostfixOperatorKind Kind) {
10008 return computeExceptionSpecFromSynthesizedBody(
10009 S, Loc, FD, BuildBody: [&](SourceLocation BodyLoc) {
10010 return buildDefaultedPostfixOperatorBody(S, FD, Kind, Loc: BodyLoc);
10011 });
10012}
10013
10014void Sema::CheckDelayedMemberExceptionSpecs() {
10015 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
10016 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
10017
10018 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
10019 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
10020
10021 // Perform any deferred checking of exception specifications for virtual
10022 // destructors.
10023 for (auto &Check : Overriding)
10024 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
10025
10026 // Perform any deferred checking of exception specifications for befriended
10027 // special members.
10028 for (auto &Check : Equivalent)
10029 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
10030}
10031
10032namespace {
10033/// CRTP base class for visiting operations performed by a special member
10034/// function (or inherited constructor).
10035template<typename Derived>
10036struct SpecialMemberVisitor {
10037 Sema &S;
10038 CXXMethodDecl *MD;
10039 CXXSpecialMemberKind CSM;
10040 Sema::InheritedConstructorInfo *ICI;
10041
10042 // Properties of the special member, computed for convenience.
10043 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
10044
10045 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10046 Sema::InheritedConstructorInfo *ICI)
10047 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
10048 switch (CSM) {
10049 case CXXSpecialMemberKind::DefaultConstructor:
10050 case CXXSpecialMemberKind::CopyConstructor:
10051 case CXXSpecialMemberKind::MoveConstructor:
10052 IsConstructor = true;
10053 break;
10054 case CXXSpecialMemberKind::CopyAssignment:
10055 case CXXSpecialMemberKind::MoveAssignment:
10056 IsAssignment = true;
10057 break;
10058 case CXXSpecialMemberKind::Destructor:
10059 break;
10060 case CXXSpecialMemberKind::Invalid:
10061 llvm_unreachable("invalid special member kind");
10062 }
10063
10064 if (MD->getNumExplicitParams()) {
10065 if (const ReferenceType *RT =
10066 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
10067 ConstArg = RT->getPointeeType().isConstQualified();
10068 }
10069 }
10070
10071 Derived &getDerived() { return static_cast<Derived&>(*this); }
10072
10073 /// Is this a "move" special member?
10074 bool isMove() const {
10075 return CSM == CXXSpecialMemberKind::MoveConstructor ||
10076 CSM == CXXSpecialMemberKind::MoveAssignment;
10077 }
10078
10079 /// Look up the corresponding special member in the given class.
10080 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
10081 unsigned Quals, bool IsMutable) {
10082 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
10083 ConstRHS: ConstArg && !IsMutable);
10084 }
10085
10086 /// Look up the constructor for the specified base class to see if it's
10087 /// overridden due to this being an inherited constructor.
10088 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
10089 if (!ICI)
10090 return {};
10091 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
10092 auto *BaseCtor =
10093 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
10094 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
10095 return MD;
10096 return {};
10097 }
10098
10099 /// A base or member subobject.
10100 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
10101
10102 /// Get the location to use for a subobject in diagnostics.
10103 static SourceLocation getSubobjectLoc(Subobject Subobj) {
10104 // FIXME: For an indirect virtual base, the direct base leading to
10105 // the indirect virtual base would be a more useful choice.
10106 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
10107 return B->getBaseTypeLoc();
10108 else
10109 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
10110 }
10111
10112 enum BasesToVisit {
10113 /// Visit all non-virtual (direct) bases.
10114 VisitNonVirtualBases,
10115 /// Visit all direct bases, virtual or not.
10116 VisitDirectBases,
10117 /// Visit all non-virtual bases, and all virtual bases if the class
10118 /// is not abstract.
10119 VisitPotentiallyConstructedBases,
10120 /// Visit all direct or virtual bases.
10121 VisitAllBases
10122 };
10123
10124 // Visit the bases and members of the class.
10125 bool visit(BasesToVisit Bases) {
10126 CXXRecordDecl *RD = MD->getParent();
10127
10128 if (Bases == VisitPotentiallyConstructedBases)
10129 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
10130
10131 for (auto &B : RD->bases())
10132 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
10133 getDerived().visitBase(&B))
10134 return true;
10135
10136 if (Bases == VisitAllBases)
10137 for (auto &B : RD->vbases())
10138 if (getDerived().visitBase(&B))
10139 return true;
10140
10141 for (auto *F : RD->fields())
10142 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
10143 getDerived().visitField(F))
10144 return true;
10145
10146 return false;
10147 }
10148};
10149}
10150
10151namespace {
10152struct SpecialMemberDeletionInfo
10153 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
10154 bool Diagnose;
10155
10156 SourceLocation Loc;
10157
10158 bool AllFieldsAreConst;
10159
10160 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
10161 CXXSpecialMemberKind CSM,
10162 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
10163 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
10164 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
10165
10166 bool inUnion() const { return MD->getParent()->isUnion(); }
10167
10168 CXXSpecialMemberKind getEffectiveCSM() {
10169 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
10170 }
10171
10172 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
10173
10174 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
10175
10176 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
10177 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
10178
10179 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
10180 bool shouldDeleteForField(FieldDecl *FD);
10181 bool shouldDeleteForAllConstMembers();
10182
10183 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
10184 unsigned Quals);
10185 bool shouldDeleteForSubobjectCall(Subobject Subobj,
10186 Sema::SpecialMemberOverloadResult SMOR,
10187 bool IsDtorCallInCtor);
10188
10189 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
10190};
10191}
10192
10193/// Is the given special member inaccessible when used on the given
10194/// sub-object.
10195bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
10196 CXXMethodDecl *target) {
10197 /// If we're operating on a base class, the object type is the
10198 /// type of this special member.
10199 CanQualType objectTy;
10200 AccessSpecifier access = target->getAccess();
10201 if (CXXBaseSpecifier *base = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj)) {
10202 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
10203 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
10204
10205 // If we're operating on a field, the object type is the type of the field.
10206 } else {
10207 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
10208 }
10209
10210 return S.isMemberAccessibleForDeletion(
10211 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
10212}
10213
10214/// Check whether we should delete a special member due to the implicit
10215/// definition containing a call to a special member of a subobject.
10216bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
10217 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
10218 bool IsDtorCallInCtor) {
10219 CXXMethodDecl *Decl = SMOR.getMethod();
10220 FieldDecl *Field = dyn_cast<FieldDecl *>(Val&: Subobj);
10221
10222 enum {
10223 NotSet = -1,
10224 NoDecl,
10225 DeletedDecl,
10226 MultipleDecl,
10227 InaccessibleDecl,
10228 NonTrivialDecl
10229 } DiagKind = NotSet;
10230
10231 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
10232 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
10233 Field->getParent()->isUnion()) {
10234 // [class.default.ctor]p2:
10235 // A defaulted default constructor for class X is defined as deleted if
10236 // - X is a union that has a variant member with a non-trivial default
10237 // constructor and no variant member of X has a default member
10238 // initializer
10239 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
10240 if (RD->hasInClassInitializer())
10241 return false;
10242 }
10243 DiagKind = !Decl ? NoDecl : DeletedDecl;
10244 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10245 DiagKind = MultipleDecl;
10246 else if (!isAccessible(Subobj, target: Decl))
10247 DiagKind = InaccessibleDecl;
10248 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
10249 !Decl->isTrivial()) {
10250 // A member of a union must have a trivial corresponding special member.
10251 // As a weird special case, a destructor call from a union's constructor
10252 // must be accessible and non-deleted, but need not be trivial. Such a
10253 // destructor is never actually called, but is semantically checked as
10254 // if it were.
10255 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
10256 // [class.default.ctor]p2:
10257 // A defaulted default constructor for class X is defined as deleted if
10258 // - X is a union that has a variant member with a non-trivial default
10259 // constructor and no variant member of X has a default member
10260 // initializer
10261 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
10262 if (!RD->hasInClassInitializer())
10263 DiagKind = NonTrivialDecl;
10264 } else {
10265 DiagKind = NonTrivialDecl;
10266 }
10267 }
10268
10269 if (DiagKind == NotSet)
10270 return false;
10271
10272 if (Diagnose) {
10273 if (Field) {
10274 S.Diag(Loc: Field->getLocation(),
10275 DiagID: diag::note_deleted_special_member_class_subobject)
10276 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
10277 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
10278 } else {
10279 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
10280 S.Diag(Loc: Base->getBeginLoc(),
10281 DiagID: diag::note_deleted_special_member_class_subobject)
10282 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
10283 << Base->getType() << DiagKind << IsDtorCallInCtor
10284 << /*IsObjCPtr*/ false;
10285 }
10286
10287 if (DiagKind == DeletedDecl)
10288 S.NoteDeletedFunction(FD: Decl);
10289 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
10290 }
10291
10292 return true;
10293}
10294
10295/// Check whether we should delete a special member function due to having a
10296/// direct or virtual base class or non-static data member of class type M.
10297bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
10298 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
10299 FieldDecl *Field = dyn_cast<FieldDecl *>(Val&: Subobj);
10300 bool IsMutable = Field && Field->isMutable();
10301
10302 // C++11 [class.ctor]p5:
10303 // -- any direct or virtual base class, or non-static data member with no
10304 // brace-or-equal-initializer, has class type M (or array thereof) and
10305 // either M has no default constructor or overload resolution as applied
10306 // to M's default constructor results in an ambiguity or in a function
10307 // that is deleted or inaccessible
10308 // C++11 [class.copy]p11, C++11 [class.copy]p23:
10309 // -- a direct or virtual base class B that cannot be copied/moved because
10310 // overload resolution, as applied to B's corresponding special member,
10311 // results in an ambiguity or a function that is deleted or inaccessible
10312 // from the defaulted special member
10313 // C++11 [class.dtor]p5:
10314 // -- any direct or virtual base class [...] has a type with a destructor
10315 // that is deleted or inaccessible
10316 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
10317 Field->hasInClassInitializer()) &&
10318 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
10319 IsDtorCallInCtor: false))
10320 return true;
10321
10322 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
10323 // -- any direct or virtual base class or non-static data member has a
10324 // type with a destructor that is deleted or inaccessible
10325 if (IsConstructor) {
10326 Sema::SpecialMemberOverloadResult SMOR =
10327 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
10328 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
10329 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
10330 return true;
10331 }
10332
10333 return false;
10334}
10335
10336bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
10337 FieldDecl *FD, QualType FieldType) {
10338 // The defaulted special functions are defined as deleted if this is a variant
10339 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
10340 // type under ARC.
10341 if (!FieldType.hasNonTrivialObjCLifetime())
10342 return false;
10343
10344 // Don't make the defaulted default constructor defined as deleted if the
10345 // member has an in-class initializer.
10346 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10347 FD->hasInClassInitializer())
10348 return false;
10349
10350 if (Diagnose) {
10351 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
10352 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
10353 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
10354 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
10355 }
10356
10357 return true;
10358}
10359
10360bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
10361 const FieldDecl *FD) {
10362 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
10363 // Copy/move constructors/assignment operators are deleted if the field has an
10364 // address-discriminated ptrauth qualifier.
10365 PointerAuthQualifier Q = FieldType.getPointerAuth();
10366
10367 if (!Q || !Q.isAddressDiscriminated())
10368 return false;
10369
10370 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10371 CSM == CXXSpecialMemberKind::Destructor)
10372 return false;
10373
10374 if (Diagnose) {
10375 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
10376 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
10377 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
10378 << /*IsDtorCallInCtor*/ false << 2;
10379 }
10380
10381 return true;
10382}
10383
10384/// Check whether we should delete a special member function due to the class
10385/// having a particular direct or virtual base class.
10386bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
10387 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
10388 // If program is correct, BaseClass cannot be null, but if it is, the error
10389 // must be reported elsewhere.
10390 if (!BaseClass)
10391 return false;
10392 // If we have an inheriting constructor, check whether we're calling an
10393 // inherited constructor instead of a default constructor.
10394 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
10395 if (auto *BaseCtor = SMOR.getMethod()) {
10396 // Note that we do not check access along this path; other than that,
10397 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
10398 // FIXME: Check that the base has a usable destructor! Sink this into
10399 // shouldDeleteForClassSubobject.
10400 if (BaseCtor->isDeleted() && Diagnose) {
10401 S.Diag(Loc: Base->getBeginLoc(),
10402 DiagID: diag::note_deleted_special_member_class_subobject)
10403 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
10404 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
10405 << /*IsObjCPtr*/ false;
10406 S.NoteDeletedFunction(FD: BaseCtor);
10407 }
10408 return BaseCtor->isDeleted();
10409 }
10410 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
10411}
10412
10413/// Check whether we should delete a special member function due to the class
10414/// having a particular non-static data member.
10415bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
10416 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
10417 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
10418
10419 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
10420 return true;
10421
10422 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
10423 return true;
10424
10425 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
10426 // For a default constructor, all references must be initialized in-class
10427 // and, if a union, it must have a non-const member.
10428 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
10429 if (Diagnose)
10430 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
10431 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
10432 return true;
10433 }
10434 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
10435 // data member of const-qualified type (or array thereof) with no
10436 // brace-or-equal-initializer is not const-default-constructible.
10437 if (!inUnion() && FieldType.isConstQualified() &&
10438 !FD->hasInClassInitializer() &&
10439 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
10440 if (Diagnose)
10441 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
10442 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
10443 return true;
10444 }
10445
10446 if (inUnion() && !FieldType.isConstQualified())
10447 AllFieldsAreConst = false;
10448 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
10449 // For a copy constructor, data members must not be of rvalue reference
10450 // type.
10451 if (FieldType->isRValueReferenceType()) {
10452 if (Diagnose)
10453 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
10454 << MD->getParent() << FD << FieldType;
10455 return true;
10456 }
10457 } else if (IsAssignment) {
10458 // For an assignment operator, data members must not be of reference type.
10459 if (FieldType->isReferenceType()) {
10460 if (Diagnose)
10461 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
10462 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
10463 return true;
10464 }
10465 if (!FieldRecord && FieldType.isConstQualified()) {
10466 // C++11 [class.copy]p23:
10467 // -- a non-static data member of const non-class type (or array thereof)
10468 if (Diagnose)
10469 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
10470 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
10471 return true;
10472 }
10473 }
10474
10475 if (FieldRecord) {
10476 // Some additional restrictions exist on the variant members.
10477 if (!inUnion() && FieldRecord->isUnion() &&
10478 FieldRecord->isAnonymousStructOrUnion()) {
10479 bool AllVariantFieldsAreConst = true;
10480
10481 // FIXME: Handle anonymous unions declared within anonymous unions.
10482 for (auto *UI : FieldRecord->fields()) {
10483 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
10484
10485 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
10486 return true;
10487
10488 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
10489 return true;
10490
10491 if (!UnionFieldType.isConstQualified())
10492 AllVariantFieldsAreConst = false;
10493
10494 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
10495 if (UnionFieldRecord &&
10496 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
10497 Quals: UnionFieldType.getCVRQualifiers()))
10498 return true;
10499 }
10500
10501 // At least one member in each anonymous union must be non-const
10502 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10503 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
10504 if (Diagnose)
10505 S.Diag(Loc: FieldRecord->getLocation(),
10506 DiagID: diag::note_deleted_default_ctor_all_const)
10507 << !!ICI << MD->getParent() << /*anonymous union*/1;
10508 return true;
10509 }
10510
10511 // Don't check the implicit member of the anonymous union type.
10512 // This is technically non-conformant but supported, and we have a
10513 // diagnostic for this elsewhere.
10514 return false;
10515 }
10516
10517 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
10518 Quals: FieldType.getCVRQualifiers()))
10519 return true;
10520 }
10521
10522 return false;
10523}
10524
10525/// C++11 [class.ctor] p5:
10526/// A defaulted default constructor for a class X is defined as deleted if
10527/// X is a union and all of its variant members are of const-qualified type.
10528bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
10529 // This is a silly definition, because it gives an empty union a deleted
10530 // default constructor. Don't do that.
10531 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
10532 AllFieldsAreConst) {
10533 bool AnyFields = false;
10534 for (auto *F : MD->getParent()->fields())
10535 if ((AnyFields = !F->isUnnamedBitField()))
10536 break;
10537 if (!AnyFields)
10538 return false;
10539 if (Diagnose)
10540 S.Diag(Loc: MD->getParent()->getLocation(),
10541 DiagID: diag::note_deleted_default_ctor_all_const)
10542 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10543 return true;
10544 }
10545 return false;
10546}
10547
10548/// Determine whether a defaulted special member function should be defined as
10549/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10550/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10551bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
10552 CXXSpecialMemberKind CSM,
10553 InheritedConstructorInfo *ICI,
10554 bool Diagnose) {
10555 if (MD->isInvalidDecl())
10556 return false;
10557 CXXRecordDecl *RD = MD->getParent();
10558 assert(!RD->isDependentType() && "do deletion after instantiation");
10559 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10560 RD->isInvalidDecl())
10561 return false;
10562
10563 // C++11 [expr.lambda.prim]p19:
10564 // The closure type associated with a lambda-expression has a
10565 // deleted (8.4.3) default constructor and a deleted copy
10566 // assignment operator.
10567 // C++2a adds back these operators if the lambda has no lambda-capture.
10568 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
10569 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10570 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10571 if (Diagnose)
10572 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
10573 return true;
10574 }
10575
10576 // C++11 [class.copy]p7, p18:
10577 // If the class definition declares a move constructor or move assignment
10578 // operator, an implicitly declared copy constructor or copy assignment
10579 // operator is defined as deleted.
10580 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
10581 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10582 CXXMethodDecl *UserDeclaredMove = nullptr;
10583
10584 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10585 // deletion of the corresponding copy operation, not both copy operations.
10586 // MSVC 2015 has adopted the standards conforming behavior.
10587 bool DeletesOnlyMatchingCopy =
10588 getLangOpts().MSVCCompat &&
10589 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
10590
10591 if (RD->hasUserDeclaredMoveConstructor() &&
10592 (!DeletesOnlyMatchingCopy ||
10593 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10594 if (!Diagnose) return true;
10595
10596 // Find any user-declared move constructor.
10597 for (auto *I : RD->ctors()) {
10598 if (I->isMoveConstructor()) {
10599 UserDeclaredMove = I;
10600 break;
10601 }
10602 }
10603 assert(UserDeclaredMove);
10604 } else if (RD->hasUserDeclaredMoveAssignment() &&
10605 (!DeletesOnlyMatchingCopy ||
10606 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10607 if (!Diagnose) return true;
10608
10609 // Find any user-declared move assignment operator.
10610 for (auto *I : RD->methods()) {
10611 if (I->isMoveAssignmentOperator()) {
10612 UserDeclaredMove = I;
10613 break;
10614 }
10615 }
10616 assert(UserDeclaredMove);
10617 }
10618
10619 if (UserDeclaredMove) {
10620 Diag(Loc: UserDeclaredMove->getLocation(),
10621 DiagID: diag::note_deleted_copy_user_declared_move)
10622 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10623 << UserDeclaredMove->isMoveAssignmentOperator();
10624 return true;
10625 }
10626 }
10627
10628 // Do access control from the special member function
10629 ContextRAII MethodContext(*this, MD);
10630
10631 // C++11 [class.dtor]p5:
10632 // -- for a virtual destructor, lookup of the non-array deallocation function
10633 // results in an ambiguity or in a function that is deleted or inaccessible
10634 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10635 FunctionDecl *OperatorDelete = nullptr;
10636 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10637 DeclarationName Name =
10638 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10639 ImplicitDeallocationParameters IDP = {
10640 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10641 AlignedAllocationMode::No, SizedDeallocationMode::No};
10642 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10643 Operator&: OperatorDelete, IDP,
10644 /*Diagnose=*/false)) {
10645 if (Diagnose)
10646 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10647 return true;
10648 }
10649 }
10650
10651 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10652
10653 // Per DR1611, do not consider virtual bases of constructors of abstract
10654 // classes, since we are not going to construct them.
10655 // Per DR1658, do not consider virtual bases of destructors of abstract
10656 // classes either.
10657 // Per DR2180, for assignment operators we only assign (and thus only
10658 // consider) direct bases.
10659 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10660 : SMI.VisitPotentiallyConstructedBases))
10661 return true;
10662
10663 if (SMI.shouldDeleteForAllConstMembers())
10664 return true;
10665
10666 if (getLangOpts().CUDA) {
10667 // We should delete the special member in CUDA mode if target inference
10668 // failed.
10669 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10670 // is treated as certain special member, which may not reflect what special
10671 // member MD really is. However inferTargetForImplicitSpecialMember
10672 // expects CSM to match MD, therefore recalculate CSM.
10673 assert(ICI || CSM == MD->getSpecialMemberKind());
10674 auto RealCSM = CSM;
10675 if (ICI)
10676 RealCSM = MD->getSpecialMemberKind();
10677
10678 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10679 ConstRHS: SMI.ConstArg, Diagnose);
10680 }
10681
10682 return false;
10683}
10684
10685void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10686 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
10687 assert(DFK && "not a defaultable function");
10688 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10689
10690 if (DFK.isSpecialMember()) {
10691 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10692 ICI: nullptr, /*Diagnose=*/true);
10693 } else if (DFK.isPostfixOperator()) {
10694 QualType C = getPostfixOperatorFirstParamType(FD)
10695 .getNonReferenceType()
10696 .getUnqualifiedType();
10697 analyzeDefaultedPostfixOperator(S&: *this, FD, Kind: DFK.asPostfixOperator(), C,
10698 /*Diagnose=*/true);
10699 } else {
10700 DefaultedComparisonAnalyzer(
10701 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10702 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10703 .visit();
10704 }
10705}
10706
10707/// Perform lookup for a special member of the specified kind, and determine
10708/// whether it is trivial. If the triviality can be determined without the
10709/// lookup, skip it. This is intended for use when determining whether a
10710/// special member of a containing object is trivial, and thus does not ever
10711/// perform overload resolution for default constructors.
10712///
10713/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10714/// member that was most likely to be intended to be trivial, if any.
10715///
10716/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10717/// determine whether the special member is trivial.
10718static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10719 CXXSpecialMemberKind CSM, unsigned Quals,
10720 bool ConstRHS, TrivialABIHandling TAH,
10721 CXXMethodDecl **Selected) {
10722 if (Selected)
10723 *Selected = nullptr;
10724
10725 switch (CSM) {
10726 case CXXSpecialMemberKind::Invalid:
10727 llvm_unreachable("not a special member");
10728
10729 case CXXSpecialMemberKind::DefaultConstructor:
10730 // C++11 [class.ctor]p5:
10731 // A default constructor is trivial if:
10732 // - all the [direct subobjects] have trivial default constructors
10733 //
10734 // Note, no overload resolution is performed in this case.
10735 if (RD->hasTrivialDefaultConstructor())
10736 return true;
10737
10738 if (Selected) {
10739 // If there's a default constructor which could have been trivial, dig it
10740 // out. Otherwise, if there's any user-provided default constructor, point
10741 // to that as an example of why there's not a trivial one.
10742 CXXConstructorDecl *DefCtor = nullptr;
10743 if (RD->needsImplicitDefaultConstructor())
10744 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10745 for (auto *CI : RD->ctors()) {
10746 if (!CI->isDefaultConstructor())
10747 continue;
10748 DefCtor = CI;
10749 if (!DefCtor->isUserProvided())
10750 break;
10751 }
10752
10753 *Selected = DefCtor;
10754 }
10755
10756 return false;
10757
10758 case CXXSpecialMemberKind::Destructor:
10759 // C++11 [class.dtor]p5:
10760 // A destructor is trivial if:
10761 // - all the direct [subobjects] have trivial destructors
10762 if (RD->hasTrivialDestructor() ||
10763 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10764 RD->hasTrivialDestructorForCall()))
10765 return true;
10766
10767 if (Selected) {
10768 if (RD->needsImplicitDestructor())
10769 S.DeclareImplicitDestructor(ClassDecl: RD);
10770 *Selected = RD->getDestructor();
10771 }
10772
10773 return false;
10774
10775 case CXXSpecialMemberKind::CopyConstructor:
10776 // C++11 [class.copy]p12:
10777 // A copy constructor is trivial if:
10778 // - the constructor selected to copy each direct [subobject] is trivial
10779 if (RD->hasTrivialCopyConstructor() ||
10780 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10781 RD->hasTrivialCopyConstructorForCall())) {
10782 if (Quals == Qualifiers::Const)
10783 // We must either select the trivial copy constructor or reach an
10784 // ambiguity; no need to actually perform overload resolution.
10785 return true;
10786 } else if (!Selected) {
10787 return false;
10788 }
10789 // In C++98, we are not supposed to perform overload resolution here, but we
10790 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10791 // cases like B as having a non-trivial copy constructor:
10792 // struct A { template<typename T> A(T&); };
10793 // struct B { mutable A a; };
10794 goto NeedOverloadResolution;
10795
10796 case CXXSpecialMemberKind::CopyAssignment:
10797 // C++11 [class.copy]p25:
10798 // A copy assignment operator is trivial if:
10799 // - the assignment operator selected to copy each direct [subobject] is
10800 // trivial
10801 if (RD->hasTrivialCopyAssignment()) {
10802 if (Quals == Qualifiers::Const)
10803 return true;
10804 } else if (!Selected) {
10805 return false;
10806 }
10807 // In C++98, we are not supposed to perform overload resolution here, but we
10808 // treat that as a language defect.
10809 goto NeedOverloadResolution;
10810
10811 case CXXSpecialMemberKind::MoveConstructor:
10812 case CXXSpecialMemberKind::MoveAssignment:
10813 NeedOverloadResolution:
10814 Sema::SpecialMemberOverloadResult SMOR =
10815 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10816
10817 // The standard doesn't describe how to behave if the lookup is ambiguous.
10818 // We treat it as not making the member non-trivial, just like the standard
10819 // mandates for the default constructor. This should rarely matter, because
10820 // the member will also be deleted.
10821 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10822 return true;
10823
10824 if (!SMOR.getMethod()) {
10825 assert(SMOR.getKind() ==
10826 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10827 return false;
10828 }
10829
10830 // We deliberately don't check if we found a deleted special member. We're
10831 // not supposed to!
10832 if (Selected)
10833 *Selected = SMOR.getMethod();
10834
10835 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10836 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10837 CSM == CXXSpecialMemberKind::MoveConstructor))
10838 return SMOR.getMethod()->isTrivialForCall();
10839 return SMOR.getMethod()->isTrivial();
10840 }
10841
10842 llvm_unreachable("unknown special method kind");
10843}
10844
10845static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10846 for (auto *CI : RD->ctors())
10847 if (!CI->isImplicit())
10848 return CI;
10849
10850 // Look for constructor templates.
10851 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10852 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10853 if (CXXConstructorDecl *CD =
10854 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10855 return CD;
10856 }
10857
10858 return nullptr;
10859}
10860
10861/// The kind of subobject we are checking for triviality. The values of this
10862/// enumeration are used in diagnostics.
10863enum TrivialSubobjectKind {
10864 /// The subobject is a base class.
10865 TSK_BaseClass,
10866 /// The subobject is a non-static data member.
10867 TSK_Field,
10868 /// The object is actually the complete object.
10869 TSK_CompleteObject
10870};
10871
10872/// Check whether the special member selected for a given type would be trivial.
10873static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10874 QualType SubType, bool ConstRHS,
10875 CXXSpecialMemberKind CSM,
10876 TrivialSubobjectKind Kind,
10877 TrivialABIHandling TAH, bool Diagnose) {
10878 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10879 if (!SubRD)
10880 return true;
10881
10882 CXXMethodDecl *Selected;
10883 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10884 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10885 return true;
10886
10887 if (Diagnose) {
10888 if (ConstRHS)
10889 SubType.addConst();
10890
10891 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10892 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10893 << Kind << SubType.getUnqualifiedType();
10894 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10895 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10896 } else if (!Selected)
10897 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10898 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10899 else if (Selected->isUserProvided()) {
10900 if (Kind == TSK_CompleteObject)
10901 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10902 << Kind << SubType.getUnqualifiedType() << CSM;
10903 else {
10904 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10905 << Kind << SubType.getUnqualifiedType() << CSM;
10906 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10907 }
10908 } else {
10909 if (Kind != TSK_CompleteObject)
10910 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10911 << Kind << SubType.getUnqualifiedType() << CSM;
10912
10913 // Explain why the defaulted or deleted special member isn't trivial.
10914 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10915 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10916 }
10917 }
10918
10919 return false;
10920}
10921
10922/// Check whether the members of a class type allow a special member to be
10923/// trivial.
10924static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10925 CXXSpecialMemberKind CSM, bool ConstArg,
10926 TrivialABIHandling TAH, bool Diagnose) {
10927 for (const auto *FI : RD->fields()) {
10928 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10929 continue;
10930
10931 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10932
10933 // Pretend anonymous struct or union members are members of this class.
10934 if (FI->isAnonymousStructOrUnion()) {
10935 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10936 CSM, ConstArg, TAH, Diagnose))
10937 return false;
10938 continue;
10939 }
10940
10941 // C++11 [class.ctor]p5:
10942 // A default constructor is trivial if [...]
10943 // -- no non-static data member of its class has a
10944 // brace-or-equal-initializer
10945 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10946 FI->hasInClassInitializer()) {
10947 if (Diagnose)
10948 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10949 << FI;
10950 return false;
10951 }
10952
10953 // Objective C ARC 4.3.5:
10954 // [...] nontrivally ownership-qualified types are [...] not trivially
10955 // default constructible, copy constructible, move constructible, copy
10956 // assignable, move assignable, or destructible [...]
10957 if (FieldType.hasNonTrivialObjCLifetime()) {
10958 if (Diagnose)
10959 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10960 << RD << FieldType.getObjCLifetime();
10961 return false;
10962 }
10963
10964 bool ConstRHS = ConstArg && !FI->isMutable();
10965 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10966 CSM, Kind: TSK_Field, TAH, Diagnose))
10967 return false;
10968 }
10969
10970 return true;
10971}
10972
10973void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10974 CXXSpecialMemberKind CSM) {
10975 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10976
10977 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10978 CSM == CXXSpecialMemberKind::CopyAssignment);
10979 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10980 Kind: TSK_CompleteObject,
10981 TAH: TrivialABIHandling::IgnoreTrivialABI,
10982 /*Diagnose*/ true);
10983}
10984
10985bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10986 TrivialABIHandling TAH, bool Diagnose) {
10987 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10988 "not special enough");
10989
10990 CXXRecordDecl *RD = MD->getParent();
10991
10992 bool ConstArg = false;
10993
10994 // C++11 [class.copy]p12, p25: [DR1593]
10995 // A [special member] is trivial if [...] its parameter-type-list is
10996 // equivalent to the parameter-type-list of an implicit declaration [...]
10997 switch (CSM) {
10998 case CXXSpecialMemberKind::DefaultConstructor:
10999 case CXXSpecialMemberKind::Destructor:
11000 // Trivial default constructors and destructors cannot have parameters.
11001 break;
11002
11003 case CXXSpecialMemberKind::CopyConstructor:
11004 case CXXSpecialMemberKind::CopyAssignment: {
11005 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
11006 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
11007
11008 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
11009 // if they are not user-provided and their parameter-type-list is equivalent
11010 // to the parameter-type-list of an implicit declaration. This maintains the
11011 // behavior before dr2171 was implemented.
11012 //
11013 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
11014 // trivial, if they are not user-provided, regardless of the qualifiers on
11015 // the reference type.
11016 const bool ClangABICompat14 =
11017 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver14);
11018 if (!RT ||
11019 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
11020 ClangABICompat14)) {
11021 if (Diagnose)
11022 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
11023 << Param0->getSourceRange() << Param0->getType()
11024 << Context.getLValueReferenceType(
11025 T: Context.getCanonicalTagType(TD: RD).withConst());
11026 return false;
11027 }
11028
11029 ConstArg = RT->getPointeeType().isConstQualified();
11030 break;
11031 }
11032
11033 case CXXSpecialMemberKind::MoveConstructor:
11034 case CXXSpecialMemberKind::MoveAssignment: {
11035 // Trivial move operations always have non-cv-qualified parameters.
11036 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
11037 const RValueReferenceType *RT =
11038 Param0->getType()->getAs<RValueReferenceType>();
11039 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
11040 if (Diagnose)
11041 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
11042 << Param0->getSourceRange() << Param0->getType()
11043 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
11044 return false;
11045 }
11046 break;
11047 }
11048
11049 case CXXSpecialMemberKind::Invalid:
11050 llvm_unreachable("not a special member");
11051 }
11052
11053 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
11054 if (Diagnose)
11055 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
11056 DiagID: diag::note_nontrivial_default_arg)
11057 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
11058 return false;
11059 }
11060 if (MD->isVariadic()) {
11061 if (Diagnose)
11062 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
11063 return false;
11064 }
11065
11066 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
11067 // A copy/move [constructor or assignment operator] is trivial if
11068 // -- the [member] selected to copy/move each direct base class subobject
11069 // is trivial
11070 //
11071 // C++11 [class.copy]p12, C++11 [class.copy]p25:
11072 // A [default constructor or destructor] is trivial if
11073 // -- all the direct base classes have trivial [default constructors or
11074 // destructors]
11075 for (const auto &BI : RD->bases())
11076 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
11077 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
11078 return false;
11079
11080 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
11081 // A copy/move [constructor or assignment operator] for a class X is
11082 // trivial if
11083 // -- for each non-static data member of X that is of class type (or array
11084 // thereof), the constructor selected to copy/move that member is
11085 // trivial
11086 //
11087 // C++11 [class.copy]p12, C++11 [class.copy]p25:
11088 // A [default constructor or destructor] is trivial if
11089 // -- for all of the non-static data members of its class that are of class
11090 // type (or array thereof), each such class has a trivial [default
11091 // constructor or destructor]
11092 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
11093 return false;
11094
11095 // C++11 [class.dtor]p5:
11096 // A destructor is trivial if [...]
11097 // -- the destructor is not virtual
11098 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
11099 if (Diagnose)
11100 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
11101 return false;
11102 }
11103
11104 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
11105 // A [special member] for class X is trivial if [...]
11106 // -- class X has no virtual functions and no virtual base classes
11107 if (CSM != CXXSpecialMemberKind::Destructor &&
11108 MD->getParent()->isDynamicClass()) {
11109 if (!Diagnose)
11110 return false;
11111
11112 if (RD->getNumVBases()) {
11113 // Check for virtual bases. We already know that the corresponding
11114 // member in all bases is trivial, so vbases must all be direct.
11115 CXXBaseSpecifier &BS = *RD->vbases_begin();
11116 assert(BS.isVirtual());
11117 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
11118 return false;
11119 }
11120
11121 // Must have a virtual method.
11122 for (const auto *MI : RD->methods()) {
11123 if (MI->isVirtual()) {
11124 SourceLocation MLoc = MI->getBeginLoc();
11125 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
11126 return false;
11127 }
11128 }
11129
11130 llvm_unreachable("dynamic class with no vbases and no virtual functions");
11131 }
11132
11133 // Looks like it's trivial!
11134 return true;
11135}
11136
11137namespace {
11138struct FindHiddenVirtualMethod {
11139 Sema *S;
11140 CXXMethodDecl *Method;
11141 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
11142 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
11143
11144private:
11145 /// Check whether any most overridden method from MD in Methods
11146 static bool CheckMostOverridenMethods(
11147 const CXXMethodDecl *MD,
11148 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
11149 if (MD->size_overridden_methods() == 0)
11150 return Methods.count(Ptr: MD->getCanonicalDecl());
11151 for (const CXXMethodDecl *O : MD->overridden_methods())
11152 if (CheckMostOverridenMethods(MD: O, Methods))
11153 return true;
11154 return false;
11155 }
11156
11157public:
11158 /// Member lookup function that determines whether a given C++
11159 /// method overloads virtual methods in a base class without overriding any,
11160 /// to be used with CXXRecordDecl::lookupInBases().
11161 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
11162 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
11163 DeclarationName Name = Method->getDeclName();
11164 assert(Name.getNameKind() == DeclarationName::Identifier);
11165
11166 bool foundSameNameMethod = false;
11167 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
11168 for (Path.Decls = BaseRecord->lookup(Name).begin();
11169 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
11170 NamedDecl *D = *Path.Decls;
11171 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
11172 MD = MD->getCanonicalDecl();
11173 foundSameNameMethod = true;
11174 // Interested only in hidden virtual methods.
11175 if (!MD->isVirtual())
11176 continue;
11177 // If the method we are checking overrides a method from its base
11178 // don't warn about the other overloaded methods. Clang deviates from
11179 // GCC by only diagnosing overloads of inherited virtual functions that
11180 // do not override any other virtual functions in the base. GCC's
11181 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
11182 // function from a base class. These cases may be better served by a
11183 // warning (not specific to virtual functions) on call sites when the
11184 // call would select a different function from the base class, were it
11185 // visible.
11186 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
11187 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
11188 return true;
11189 // Collect the overload only if its hidden.
11190 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
11191 overloadedMethods.push_back(Elt: MD);
11192 }
11193 }
11194
11195 if (foundSameNameMethod)
11196 OverloadedMethods.append(in_start: overloadedMethods.begin(),
11197 in_end: overloadedMethods.end());
11198 return foundSameNameMethod;
11199 }
11200};
11201} // end anonymous namespace
11202
11203/// Add the most overridden methods from MD to Methods
11204static void AddMostOverridenMethods(const CXXMethodDecl *MD,
11205 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
11206 if (MD->size_overridden_methods() == 0)
11207 Methods.insert(Ptr: MD->getCanonicalDecl());
11208 else
11209 for (const CXXMethodDecl *O : MD->overridden_methods())
11210 AddMostOverridenMethods(MD: O, Methods);
11211}
11212
11213void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
11214 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
11215 if (!MD->getDeclName().isIdentifier())
11216 return;
11217
11218 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
11219 /*bool RecordPaths=*/false,
11220 /*bool DetectVirtual=*/false);
11221 FindHiddenVirtualMethod FHVM;
11222 FHVM.Method = MD;
11223 FHVM.S = this;
11224
11225 // Keep the base methods that were overridden or introduced in the subclass
11226 // by 'using' in a set. A base method not in this set is hidden.
11227 CXXRecordDecl *DC = MD->getParent();
11228 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
11229 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
11230 ND = shad->getTargetDecl();
11231 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
11232 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
11233 }
11234
11235 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
11236 OverloadedMethods = FHVM.OverloadedMethods;
11237}
11238
11239void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
11240 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
11241 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
11242 PartialDiagnostic PD = PDiag(
11243 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
11244 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
11245 Diag(Loc: overloadedMD->getLocation(), PD);
11246 }
11247}
11248
11249void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
11250 if (MD->isInvalidDecl())
11251 return;
11252
11253 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
11254 return;
11255
11256 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
11257 FindHiddenVirtualMethods(MD, OverloadedMethods);
11258 if (!OverloadedMethods.empty()) {
11259 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
11260 << MD << (OverloadedMethods.size() > 1);
11261
11262 NoteHiddenVirtualMethods(MD, OverloadedMethods);
11263 }
11264}
11265
11266void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
11267 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
11268 // No diagnostics if this is a template instantiation.
11269 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
11270 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
11271 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
11272 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
11273 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
11274 }
11275 RD.dropAttr<TrivialABIAttr>();
11276 };
11277
11278 // Ill-formed if the struct has virtual functions.
11279 if (RD.isPolymorphic()) {
11280 PrintDiagAndRemoveAttr(1);
11281 return;
11282 }
11283
11284 for (const auto &B : RD.bases()) {
11285 // Ill-formed if the base class is non-trivial for the purpose of calls or a
11286 // virtual base.
11287 if (!B.getType()->isDependentType() &&
11288 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
11289 PrintDiagAndRemoveAttr(2);
11290 return;
11291 }
11292
11293 if (B.isVirtual()) {
11294 PrintDiagAndRemoveAttr(3);
11295 return;
11296 }
11297 }
11298
11299 for (const auto *FD : RD.fields()) {
11300 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
11301 // non-trivial for the purpose of calls.
11302 QualType FT = FD->getType();
11303 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
11304 PrintDiagAndRemoveAttr(4);
11305 return;
11306 }
11307
11308 // Ill-formed if the field is an address-discriminated value.
11309 if (FT.hasAddressDiscriminatedPointerAuth()) {
11310 PrintDiagAndRemoveAttr(6);
11311 return;
11312 }
11313
11314 if (const auto *RT =
11315 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
11316 if (!RT->isDependentType() &&
11317 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
11318 ->canPassInRegisters()) {
11319 PrintDiagAndRemoveAttr(5);
11320 return;
11321 }
11322 }
11323
11324 if (IsCXXTriviallyRelocatableType(RD))
11325 return;
11326
11327 // Ill-formed if the copy and move constructors are deleted.
11328 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
11329 // If the type is dependent, then assume it might have
11330 // implicit copy or move ctor because we won't know yet at this point.
11331 if (RD.isDependentType())
11332 return true;
11333 if (RD.needsImplicitCopyConstructor() &&
11334 !RD.defaultedCopyConstructorIsDeleted())
11335 return true;
11336 if (RD.needsImplicitMoveConstructor() &&
11337 !RD.defaultedMoveConstructorIsDeleted())
11338 return true;
11339 for (const CXXConstructorDecl *CD : RD.ctors())
11340 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
11341 return true;
11342 return false;
11343 };
11344
11345 if (!HasNonDeletedCopyOrMoveConstructor()) {
11346 PrintDiagAndRemoveAttr(0);
11347 return;
11348 }
11349}
11350
11351void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
11352 CXXRecordDecl &RD) {
11353 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
11354 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
11355 return;
11356
11357 const CXXRecordDecl *PrimaryBase = &RD;
11358 if (PrimaryBase->hasAnyDependentBases())
11359 return;
11360
11361 while (1) {
11362 assert(PrimaryBase);
11363 const CXXRecordDecl *Base = nullptr;
11364 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
11365 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
11366 continue;
11367 Base = BasePtr.getType()->getAsCXXRecordDecl();
11368 break;
11369 }
11370 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
11371 break;
11372 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
11373 DiagID: diag::err_non_top_level_vtable_pointer_auth)
11374 << &RD << Base;
11375 PrimaryBase = Base;
11376 }
11377
11378 if (!RD.isPolymorphic())
11379 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
11380 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
11381 << &RD;
11382}
11383
11384void Sema::ActOnFinishCXXMemberSpecification(
11385 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
11386 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
11387 if (!TagDecl)
11388 return;
11389
11390 AdjustDeclIfTemplate(Decl&: TagDecl);
11391
11392 for (const ParsedAttr &AL : AttrList) {
11393 if (AL.getKind() != ParsedAttr::AT_Visibility)
11394 continue;
11395 AL.setInvalid();
11396 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
11397 }
11398
11399 ActOnFields(S, RecLoc: RLoc, TagDecl,
11400 Fields: llvm::ArrayRef(
11401 // strict aliasing violation!
11402 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
11403 FieldCollector->getCurNumFields()),
11404 LBrac, RBrac, AttrList);
11405
11406 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
11407}
11408
11409/// Find the equality comparison functions that should be implicitly declared
11410/// in a given class definition, per C++2a [class.compare.default]p3.
11411static void findImplicitlyDeclaredEqualityComparisons(
11412 ASTContext &Ctx, CXXRecordDecl *RD,
11413 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
11414 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
11415 if (!RD->lookup(Name: EqEq).empty())
11416 // Member operator== explicitly declared: no implicit operator==s.
11417 return;
11418
11419 // Traverse friends looking for an '==' or a '<=>'.
11420 for (FriendDecl *Friend : RD->friends()) {
11421 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
11422 if (!FD) continue;
11423
11424 if (FD->getOverloadedOperator() == OO_EqualEqual) {
11425 // Friend operator== explicitly declared: no implicit operator==s.
11426 Spaceships.clear();
11427 return;
11428 }
11429
11430 if (FD->getOverloadedOperator() == OO_Spaceship &&
11431 FD->isExplicitlyDefaulted())
11432 Spaceships.push_back(Elt: FD);
11433 }
11434
11435 // Look for members named 'operator<=>'.
11436 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
11437 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
11438 // Note that we could find a non-function here (either a function template
11439 // or a using-declaration). Neither case results in an implicit
11440 // 'operator=='.
11441 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
11442 if (FD->isExplicitlyDefaulted())
11443 Spaceships.push_back(Elt: FD);
11444 }
11445}
11446
11447void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
11448 // Don't add implicit special members to templated classes.
11449 // FIXME: This means unqualified lookups for 'operator=' within a class
11450 // template don't work properly.
11451 if (!ClassDecl->isDependentType()) {
11452 if (ClassDecl->needsImplicitDefaultConstructor()) {
11453 ++getASTContext().NumImplicitDefaultConstructors;
11454
11455 if (ClassDecl->hasInheritedConstructor())
11456 DeclareImplicitDefaultConstructor(ClassDecl);
11457 }
11458
11459 if (ClassDecl->needsImplicitCopyConstructor()) {
11460 ++getASTContext().NumImplicitCopyConstructors;
11461
11462 // If the properties or semantics of the copy constructor couldn't be
11463 // determined while the class was being declared, force a declaration
11464 // of it now.
11465 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
11466 ClassDecl->hasInheritedConstructor())
11467 DeclareImplicitCopyConstructor(ClassDecl);
11468 // For the MS ABI we need to know whether the copy ctor is deleted. A
11469 // prerequisite for deleting the implicit copy ctor is that the class has
11470 // a move ctor or move assignment that is either user-declared or whose
11471 // semantics are inherited from a subobject. FIXME: We should provide a
11472 // more direct way for CodeGen to ask whether the constructor was deleted.
11473 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
11474 (ClassDecl->hasUserDeclaredMoveConstructor() ||
11475 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
11476 ClassDecl->hasUserDeclaredMoveAssignment() ||
11477 ClassDecl->needsOverloadResolutionForMoveAssignment()))
11478 DeclareImplicitCopyConstructor(ClassDecl);
11479 }
11480
11481 if (getLangOpts().CPlusPlus11 &&
11482 ClassDecl->needsImplicitMoveConstructor()) {
11483 ++getASTContext().NumImplicitMoveConstructors;
11484
11485 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
11486 ClassDecl->hasInheritedConstructor())
11487 DeclareImplicitMoveConstructor(ClassDecl);
11488 }
11489
11490 if (ClassDecl->needsImplicitCopyAssignment()) {
11491 ++getASTContext().NumImplicitCopyAssignmentOperators;
11492
11493 // If we have a dynamic class, then the copy assignment operator may be
11494 // virtual, so we have to declare it immediately. This ensures that, e.g.,
11495 // it shows up in the right place in the vtable and that we diagnose
11496 // problems with the implicit exception specification.
11497 if (ClassDecl->isDynamicClass() ||
11498 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
11499 ClassDecl->hasInheritedAssignment())
11500 DeclareImplicitCopyAssignment(ClassDecl);
11501 }
11502
11503 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
11504 ++getASTContext().NumImplicitMoveAssignmentOperators;
11505
11506 // Likewise for the move assignment operator.
11507 if (ClassDecl->isDynamicClass() ||
11508 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
11509 ClassDecl->hasInheritedAssignment())
11510 DeclareImplicitMoveAssignment(ClassDecl);
11511 }
11512
11513 if (ClassDecl->needsImplicitDestructor()) {
11514 ++getASTContext().NumImplicitDestructors;
11515
11516 // If we have a dynamic class, then the destructor may be virtual, so we
11517 // have to declare the destructor immediately. This ensures that, e.g., it
11518 // shows up in the right place in the vtable and that we diagnose problems
11519 // with the implicit exception specification.
11520 if (ClassDecl->isDynamicClass() ||
11521 ClassDecl->needsOverloadResolutionForDestructor())
11522 DeclareImplicitDestructor(ClassDecl);
11523 }
11524 }
11525
11526 // C++2a [class.compare.default]p3:
11527 // If the member-specification does not explicitly declare any member or
11528 // friend named operator==, an == operator function is declared implicitly
11529 // for each defaulted three-way comparison operator function defined in
11530 // the member-specification
11531 // FIXME: Consider doing this lazily.
11532 // We do this during the initial parse for a class template, not during
11533 // instantiation, so that we can handle unqualified lookups for 'operator=='
11534 // when parsing the template.
11535 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
11536 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
11537 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
11538 Spaceships&: DefaultedSpaceships);
11539 for (auto *FD : DefaultedSpaceships)
11540 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
11541 }
11542}
11543
11544unsigned
11545Sema::ActOnReenterTemplateScope(Decl *D,
11546 llvm::function_ref<Scope *()> EnterScope) {
11547 if (!D)
11548 return 0;
11549 AdjustDeclIfTemplate(Decl&: D);
11550
11551 // In order to get name lookup right, reenter template scopes in order from
11552 // outermost to innermost.
11553 SmallVector<TemplateParameterList *, 4> ParameterLists;
11554 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
11555
11556 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11557 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11558 ParameterLists.push_back(Elt: TPL);
11559
11560 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
11561 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11562 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
11563 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
11564 LookupDC = VD->getDeclContext();
11565
11566 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
11567 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
11568 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
11569 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11570 }
11571 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
11572 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11573 ParameterLists.push_back(Elt: TPL);
11574
11575 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
11576 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
11577 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
11578 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
11579 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11580 }
11581 }
11582 // FIXME: Alias declarations and concepts.
11583
11584 unsigned Count = 0;
11585 Scope *InnermostTemplateScope = nullptr;
11586 for (TemplateParameterList *Params : ParameterLists) {
11587 // Ignore explicit specializations; they don't contribute to the template
11588 // depth.
11589 if (Params->size() == 0)
11590 continue;
11591
11592 InnermostTemplateScope = EnterScope();
11593 for (NamedDecl *Param : *Params) {
11594 if (Param->getDeclName()) {
11595 InnermostTemplateScope->AddDecl(D: Param);
11596 IdResolver.AddDecl(D: Param);
11597 }
11598 }
11599 ++Count;
11600 }
11601
11602 // Associate the new template scopes with the corresponding entities.
11603 if (InnermostTemplateScope) {
11604 assert(LookupDC && "no enclosing DeclContext for template lookup");
11605 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11606 }
11607
11608 return Count;
11609}
11610
11611void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11612 if (!RecordD) return;
11613 AdjustDeclIfTemplate(Decl&: RecordD);
11614 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11615 PushDeclContext(S, DC: Record);
11616}
11617
11618void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11619 if (!RecordD) return;
11620 PopDeclContext();
11621}
11622
11623void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11624 if (!Param)
11625 return;
11626
11627 S->AddDecl(D: Param);
11628 if (Param->getDeclName())
11629 IdResolver.AddDecl(D: Param);
11630}
11631
11632void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11633}
11634
11635/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11636/// C++ method declaration. We're (re-)introducing the given
11637/// function parameter into scope for use in parsing later parts of
11638/// the method declaration. For example, we could see an
11639/// ActOnParamDefaultArgument event for this parameter.
11640void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11641 if (!ParamD)
11642 return;
11643
11644 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11645
11646 S->AddDecl(D: Param);
11647 if (Param->getDeclName())
11648 IdResolver.AddDecl(D: Param);
11649}
11650
11651void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11652 if (!MethodD)
11653 return;
11654
11655 AdjustDeclIfTemplate(Decl&: MethodD);
11656
11657 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11658
11659 // Now that we have our default arguments, check the constructor
11660 // again. It could produce additional diagnostics or affect whether
11661 // the class has implicitly-declared destructors, among other
11662 // things.
11663 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11664 CheckConstructor(Constructor);
11665
11666 // Check the default arguments, which we may have added.
11667 if (!Method->isInvalidDecl())
11668 CheckCXXDefaultArguments(FD: Method);
11669}
11670
11671// Emit the given diagnostic for each non-address-space qualifier.
11672// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11673static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11674 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11675 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11676 bool DiagOccurred = false;
11677 FTI.MethodQualifiers->forEachQualifier(
11678 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11679 SourceLocation SL) {
11680 // This diagnostic should be emitted on any qualifier except an addr
11681 // space qualifier. However, forEachQualifier currently doesn't visit
11682 // addr space qualifiers, so there's no way to write this condition
11683 // right now; we just diagnose on everything.
11684 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11685 DiagOccurred = true;
11686 });
11687 if (DiagOccurred)
11688 D.setInvalidType();
11689 }
11690}
11691
11692static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11693 unsigned Kind) {
11694 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11695 return;
11696
11697 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11698 if (Chunk.Kind == DeclaratorChunk::Paren ||
11699 Chunk.Kind == DeclaratorChunk::Function)
11700 return;
11701
11702 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11703 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11704 << Kind << Chunk.getSourceRange();
11705 D.setInvalidType();
11706}
11707
11708QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11709 StorageClass &SC) {
11710 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11711
11712 // C++ [class.ctor]p3:
11713 // A constructor shall not be virtual (10.3) or static (9.4). A
11714 // constructor can be invoked for a const, volatile or const
11715 // volatile object. A constructor shall not be declared const,
11716 // volatile, or const volatile (9.3.2).
11717 if (isVirtual) {
11718 if (!D.isInvalidType())
11719 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11720 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11721 << SourceRange(D.getIdentifierLoc());
11722 D.setInvalidType();
11723 }
11724 if (SC == SC_Static) {
11725 if (!D.isInvalidType())
11726 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11727 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11728 << SourceRange(D.getIdentifierLoc());
11729 D.setInvalidType();
11730 SC = SC_None;
11731 }
11732
11733 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11734 diagnoseIgnoredQualifiers(
11735 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11736 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11737 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11738 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11739 D.setInvalidType();
11740 }
11741
11742 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11743 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11744
11745 // C++0x [class.ctor]p4:
11746 // A constructor shall not be declared with a ref-qualifier.
11747 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11748 if (FTI.hasRefQualifier()) {
11749 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11750 << FTI.RefQualifierIsLValueRef
11751 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11752 D.setInvalidType();
11753 }
11754
11755 // Rebuild the function type "R" without any type qualifiers (in
11756 // case any of the errors above fired) and with "void" as the
11757 // return type, since constructors don't have return types.
11758 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11759 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11760 return R;
11761
11762 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11763 EPI.TypeQuals = Qualifiers();
11764 EPI.RefQualifier = RQ_None;
11765
11766 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11767}
11768
11769void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11770 CXXRecordDecl *ClassDecl
11771 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11772 if (!ClassDecl)
11773 return Constructor->setInvalidDecl();
11774
11775 // C++ [class.copy]p3:
11776 // A declaration of a constructor for a class X is ill-formed if
11777 // its first parameter is of type (optionally cv-qualified) X and
11778 // either there are no other parameters or else all other
11779 // parameters have default arguments.
11780 if (!Constructor->isInvalidDecl() &&
11781 Constructor->hasOneParamOrDefaultArgs() &&
11782 !Constructor->isFunctionTemplateSpecialization()) {
11783 CanQualType ParamType =
11784 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11785 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11786 if (ParamType == ClassTy) {
11787 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11788 const char *ConstRef
11789 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11790 : " const &";
11791 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11792 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11793
11794 // FIXME: Rather that making the constructor invalid, we should endeavor
11795 // to fix the type.
11796 Constructor->setInvalidDecl();
11797 }
11798 }
11799}
11800
11801bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11802 CXXRecordDecl *RD = Destructor->getParent();
11803
11804 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11805 SourceLocation Loc;
11806
11807 if (!Destructor->isImplicit())
11808 Loc = Destructor->getLocation();
11809 else
11810 Loc = RD->getLocation();
11811
11812 DeclarationName Name =
11813 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11814 // If we have a virtual destructor, look up the deallocation function
11815 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11816 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11817 Expr *ThisArg = nullptr;
11818
11819 // If the notional 'delete this' expression requires a non-trivial
11820 // conversion from 'this' to the type of a destroying operator delete's
11821 // first parameter, perform that conversion now.
11822 if (OperatorDelete->isDestroyingOperatorDelete()) {
11823 unsigned AddressParamIndex = 0;
11824 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11825 ++AddressParamIndex;
11826 QualType ParamType =
11827 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11828 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11829 // C++ [class.dtor]p13:
11830 // ... as if for the expression 'delete this' appearing in a
11831 // non-virtual destructor of the destructor's class.
11832 ContextRAII SwitchContext(*this, Destructor);
11833 ExprResult This = ActOnCXXThis(
11834 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11835 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11836 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11837 Action: AssignmentAction::Passing);
11838 if (This.isInvalid()) {
11839 // FIXME: Register this as a context note so that it comes out
11840 // in the right order.
11841 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11842 return true;
11843 }
11844 ThisArg = This.get();
11845 }
11846 }
11847
11848 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11849 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11850 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11851
11852 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11853 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11854 Context.getLangOpts())) {
11855 // In Microsoft ABI whenever a class has a defined operator delete,
11856 // scalar deleting destructors check the 3rd bit of the implicit
11857 // parameter and if it is set, then, global operator delete must be
11858 // called instead of the class-specific one. Find and save the global
11859 // operator delete for that case. Do not diagnose at this point because
11860 // the lack of a global operator delete is not an error if there are no
11861 // delete calls that require it.
11862 FunctionDecl *GlobalOperatorDelete =
11863 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11864 /*LookForGlobal*/ true, Name);
11865 if (GlobalOperatorDelete) {
11866 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11867 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11868 }
11869 }
11870
11871 if (Context.getTargetInfo().emitVectorDeletingDtors(
11872 Context.getLangOpts())) {
11873 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11874 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11875 DeclarationName VDeleteName =
11876 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11877 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11878 StartLoc: Loc, RD, /*Diagnose*/ false,
11879 /*LookForGlobal*/ false, Name: VDeleteName);
11880 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11881 FunctionDecl *GlobalArrOperatorDelete =
11882 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11883 /*LookForGlobal*/ true,
11884 Name: VDeleteName);
11885 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11886 if (GlobalArrOperatorDelete &&
11887 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11888 DestructorIsExported))
11889 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11890 } else if (!ArrOperatorDelete) {
11891 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11892 StartLoc: Loc, RD, /*Diagnose*/ false,
11893 /*LookForGlobal*/ true, Name: VDeleteName);
11894 }
11895 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11896 if (ArrOperatorDelete &&
11897 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11898 DestructorIsExported))
11899 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11900 }
11901 }
11902 }
11903
11904 return false;
11905}
11906
11907QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11908 StorageClass& SC) {
11909 // C++ [class.dtor]p1:
11910 // [...] A typedef-name that names a class is a class-name
11911 // (7.1.3); however, a typedef-name that names a class shall not
11912 // be used as the identifier in the declarator for a destructor
11913 // declaration.
11914 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11915 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11916 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11917 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11918 else if (const TemplateSpecializationType *TST =
11919 DeclaratorType->getAs<TemplateSpecializationType>())
11920 if (TST->isTypeAlias())
11921 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11922 << DeclaratorType << 1;
11923
11924 // C++ [class.dtor]p2:
11925 // A destructor is used to destroy objects of its class type. A
11926 // destructor takes no parameters, and no return type can be
11927 // specified for it (not even void). The address of a destructor
11928 // shall not be taken. A destructor shall not be static. A
11929 // destructor can be invoked for a const, volatile or const
11930 // volatile object. A destructor shall not be declared const,
11931 // volatile or const volatile (9.3.2).
11932 if (SC == SC_Static) {
11933 if (!D.isInvalidType())
11934 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11935 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11936 << SourceRange(D.getIdentifierLoc())
11937 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11938
11939 SC = SC_None;
11940 }
11941 if (!D.isInvalidType()) {
11942 // Destructors don't have return types, but the parser will
11943 // happily parse something like:
11944 //
11945 // class X {
11946 // float ~X();
11947 // };
11948 //
11949 // The return type will be eliminated later.
11950 if (D.getDeclSpec().hasTypeSpecifier())
11951 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11952 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11953 << SourceRange(D.getIdentifierLoc());
11954 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11955 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11956 FallbackLoc: SourceLocation(),
11957 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11958 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11959 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11960 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11961 D.setInvalidType();
11962 }
11963 }
11964
11965 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11966 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11967
11968 // C++0x [class.dtor]p2:
11969 // A destructor shall not be declared with a ref-qualifier.
11970 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11971 if (FTI.hasRefQualifier()) {
11972 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11973 << FTI.RefQualifierIsLValueRef
11974 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11975 D.setInvalidType();
11976 }
11977
11978 // Make sure we don't have any parameters.
11979 if (FTIHasNonVoidParameters(FTI)) {
11980 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11981
11982 // Delete the parameters.
11983 FTI.freeParams();
11984 D.setInvalidType();
11985 }
11986
11987 // Make sure the destructor isn't variadic.
11988 if (FTI.isVariadic) {
11989 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11990 D.setInvalidType();
11991 }
11992
11993 // Rebuild the function type "R" without any type qualifiers or
11994 // parameters (in case any of the errors above fired) and with
11995 // "void" as the return type, since destructors don't have return
11996 // types.
11997 if (!D.isInvalidType())
11998 return R;
11999
12000 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
12001 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
12002 EPI.Variadic = false;
12003 EPI.TypeQuals = Qualifiers();
12004 EPI.RefQualifier = RQ_None;
12005 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
12006}
12007
12008static void extendLeft(SourceRange &R, SourceRange Before) {
12009 if (Before.isInvalid())
12010 return;
12011 R.setBegin(Before.getBegin());
12012 if (R.getEnd().isInvalid())
12013 R.setEnd(Before.getEnd());
12014}
12015
12016static void extendRight(SourceRange &R, SourceRange After) {
12017 if (After.isInvalid())
12018 return;
12019 if (R.getBegin().isInvalid())
12020 R.setBegin(After.getBegin());
12021 R.setEnd(After.getEnd());
12022}
12023
12024void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
12025 StorageClass& SC) {
12026 // C++ [class.conv.fct]p1:
12027 // Neither parameter types nor return type can be specified. The
12028 // type of a conversion function (8.3.5) is "function taking no
12029 // parameter returning conversion-type-id."
12030 if (SC == SC_Static) {
12031 if (!D.isInvalidType())
12032 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
12033 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
12034 << D.getName().getSourceRange();
12035 D.setInvalidType();
12036 SC = SC_None;
12037 }
12038
12039 TypeSourceInfo *ConvTSI = nullptr;
12040 QualType ConvType =
12041 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
12042
12043 const DeclSpec &DS = D.getDeclSpec();
12044 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
12045 // Conversion functions don't have return types, but the parser will
12046 // happily parse something like:
12047 //
12048 // class X {
12049 // float operator bool();
12050 // };
12051 //
12052 // The return type will be changed later anyway.
12053 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
12054 << SourceRange(DS.getTypeSpecTypeLoc())
12055 << SourceRange(D.getIdentifierLoc());
12056 D.setInvalidType();
12057 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
12058 // It's also plausible that the user writes type qualifiers in the wrong
12059 // place, such as:
12060 // struct S { const operator int(); };
12061 // FIXME: we could provide a fixit to move the qualifiers onto the
12062 // conversion type.
12063 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
12064 << SourceRange(D.getIdentifierLoc()) << 0;
12065 D.setInvalidType();
12066 }
12067 const auto *Proto = R->castAs<FunctionProtoType>();
12068 // Make sure we don't have any parameters.
12069 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12070 unsigned NumParam = Proto->getNumParams();
12071
12072 // [C++2b]
12073 // A conversion function shall have no non-object parameters.
12074 if (NumParam == 1) {
12075 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12076 if (const auto *First =
12077 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
12078 First && First->isExplicitObjectParameter())
12079 NumParam--;
12080 }
12081
12082 if (NumParam != 0) {
12083 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
12084 // Delete the parameters.
12085 FTI.freeParams();
12086 D.setInvalidType();
12087 } else if (Proto->isVariadic()) {
12088 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
12089 D.setInvalidType();
12090 }
12091
12092 // Diagnose "&operator bool()" and other such nonsense. This
12093 // is actually a gcc extension which we don't support.
12094 if (Proto->getReturnType() != ConvType) {
12095 bool NeedsTypedef = false;
12096 SourceRange Before, After;
12097
12098 // Walk the chunks and extract information on them for our diagnostic.
12099 bool PastFunctionChunk = false;
12100 for (auto &Chunk : D.type_objects()) {
12101 switch (Chunk.Kind) {
12102 case DeclaratorChunk::Function:
12103 if (!PastFunctionChunk) {
12104 if (Chunk.Fun.HasTrailingReturnType) {
12105 TypeSourceInfo *TRT = nullptr;
12106 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
12107 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
12108 }
12109 PastFunctionChunk = true;
12110 break;
12111 }
12112 [[fallthrough]];
12113 case DeclaratorChunk::Array:
12114 NeedsTypedef = true;
12115 extendRight(R&: After, After: Chunk.getSourceRange());
12116 break;
12117
12118 case DeclaratorChunk::Pointer:
12119 case DeclaratorChunk::BlockPointer:
12120 case DeclaratorChunk::Reference:
12121 case DeclaratorChunk::MemberPointer:
12122 case DeclaratorChunk::Pipe:
12123 extendLeft(R&: Before, Before: Chunk.getSourceRange());
12124 break;
12125
12126 case DeclaratorChunk::Paren:
12127 extendLeft(R&: Before, Before: Chunk.Loc);
12128 extendRight(R&: After, After: Chunk.EndLoc);
12129 break;
12130 }
12131 }
12132
12133 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
12134 After.isValid() ? After.getBegin() :
12135 D.getIdentifierLoc();
12136 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
12137 DB << Before << After;
12138
12139 if (!NeedsTypedef) {
12140 DB << /*don't need a typedef*/0;
12141
12142 // If we can provide a correct fix-it hint, do so.
12143 if (After.isInvalid() && ConvTSI) {
12144 SourceLocation InsertLoc =
12145 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
12146 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
12147 << FixItHint::CreateInsertionFromRange(
12148 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
12149 << FixItHint::CreateRemoval(RemoveRange: Before);
12150 }
12151 } else if (!Proto->getReturnType()->isDependentType()) {
12152 DB << /*typedef*/1 << Proto->getReturnType();
12153 } else if (getLangOpts().CPlusPlus11) {
12154 DB << /*alias template*/2 << Proto->getReturnType();
12155 } else {
12156 DB << /*might not be fixable*/3;
12157 }
12158
12159 // Recover by incorporating the other type chunks into the result type.
12160 // Note, this does *not* change the name of the function. This is compatible
12161 // with the GCC extension:
12162 // struct S { &operator int(); } s;
12163 // int &r = s.operator int(); // ok in GCC
12164 // S::operator int&() {} // error in GCC, function name is 'operator int'.
12165 ConvType = Proto->getReturnType();
12166 }
12167
12168 // C++ [class.conv.fct]p4:
12169 // The conversion-type-id shall not represent a function type nor
12170 // an array type.
12171 if (ConvType->isArrayType()) {
12172 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
12173 ConvType = Context.getPointerType(T: ConvType);
12174 D.setInvalidType();
12175 } else if (ConvType->isFunctionType()) {
12176 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
12177 ConvType = Context.getPointerType(T: ConvType);
12178 D.setInvalidType();
12179 }
12180
12181 // Rebuild the function type "R" without any parameters (in case any
12182 // of the errors above fired) and with the conversion type as the
12183 // return type.
12184 if (D.isInvalidType())
12185 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
12186
12187 // C++0x explicit conversion operators.
12188 if (DS.hasExplicitSpecifier())
12189 DiagCompat(Loc: DS.getExplicitSpecLoc(),
12190 CompatDiagId: diag_compat::explicit_conversion_functions)
12191 << SourceRange(DS.getExplicitSpecRange());
12192}
12193
12194Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
12195 assert(Conversion && "Expected to receive a conversion function declaration");
12196
12197 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
12198
12199 // Make sure we aren't redeclaring the conversion function.
12200 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
12201 // C++ [class.conv.fct]p1:
12202 // [...] A conversion function is never used to convert a
12203 // (possibly cv-qualified) object to the (possibly cv-qualified)
12204 // same object type (or a reference to it), to a (possibly
12205 // cv-qualified) base class of that type (or a reference to it),
12206 // or to (possibly cv-qualified) void.
12207 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
12208 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
12209 ConvType = ConvTypeRef->getPointeeType();
12210 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
12211 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
12212 /* Suppress diagnostics for instantiations. */;
12213 else if (Conversion->size_overridden_methods() != 0)
12214 /* Suppress diagnostics for overriding virtual function in a base class. */;
12215 else if (ConvType->isRecordType()) {
12216 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
12217 if (ConvType == ClassType)
12218 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
12219 << ClassType;
12220 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
12221 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
12222 << ClassType << ConvType;
12223 } else if (ConvType->isVoidType()) {
12224 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
12225 << ClassType << ConvType;
12226 }
12227
12228 if (FunctionTemplateDecl *ConversionTemplate =
12229 Conversion->getDescribedFunctionTemplate()) {
12230 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
12231 ConvType = ConvTypePtr->getPointeeType();
12232 }
12233 if (ConvType->isUndeducedAutoType()) {
12234 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
12235 << getReturnTypeLoc(FD: Conversion).getSourceRange()
12236 << ConvType->castAs<AutoType>()->getKeyword()
12237 << /* in declaration of conversion function template= */ 24;
12238 }
12239
12240 return ConversionTemplate;
12241 }
12242
12243 return Conversion;
12244}
12245
12246void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
12247 DeclarationName Name, QualType R) {
12248 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
12249}
12250
12251void Sema::CheckExplicitObjectLambda(Declarator &D) {
12252 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
12253}
12254
12255void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
12256 DeclarationName Name, QualType R,
12257 bool IsLambda, DeclContext *DC) {
12258 if (!D.isFunctionDeclarator())
12259 return;
12260
12261 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
12262 if (FTI.NumParams == 0)
12263 return;
12264 ParmVarDecl *ExplicitObjectParam = nullptr;
12265 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
12266 const auto &ParamInfo = FTI.Params[Idx];
12267 if (!ParamInfo.Param)
12268 continue;
12269 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
12270 if (!Param->isExplicitObjectParameter())
12271 continue;
12272 if (Idx == 0) {
12273 ExplicitObjectParam = Param;
12274 continue;
12275 } else {
12276 Diag(Loc: Param->getLocation(),
12277 DiagID: diag::err_explicit_object_parameter_must_be_first)
12278 << IsLambda << Param->getSourceRange();
12279 }
12280 }
12281 if (!ExplicitObjectParam)
12282 return;
12283
12284 if (ExplicitObjectParam->hasDefaultArg()) {
12285 Diag(Loc: ExplicitObjectParam->getLocation(),
12286 DiagID: diag::err_explicit_object_default_arg)
12287 << ExplicitObjectParam->getSourceRange();
12288 D.setInvalidType();
12289 }
12290
12291 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
12292 (D.getContext() == clang::DeclaratorContext::Member &&
12293 D.isStaticMember())) {
12294 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
12295 DiagID: diag::err_explicit_object_parameter_nonmember)
12296 << D.getSourceRange() << /*static=*/0 << IsLambda;
12297 D.setInvalidType();
12298 }
12299
12300 if (D.getDeclSpec().isVirtualSpecified()) {
12301 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
12302 DiagID: diag::err_explicit_object_parameter_nonmember)
12303 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
12304 D.setInvalidType();
12305 }
12306
12307 // Friend declarations require some care. Consider:
12308 //
12309 // namespace N {
12310 // struct A{};
12311 // int f(A);
12312 // }
12313 //
12314 // struct S {
12315 // struct T {
12316 // int f(this T);
12317 // };
12318 //
12319 // friend int T::f(this T); // Allow this.
12320 // friend int f(this S); // But disallow this.
12321 // friend int N::f(this A); // And disallow this.
12322 // };
12323 //
12324 // Here, it seems to suffice to check whether the scope
12325 // specifier designates a class type.
12326 if (D.getDeclSpec().isFriendSpecified() &&
12327 !isa_and_present<CXXRecordDecl>(
12328 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
12329 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
12330 DiagID: diag::err_explicit_object_parameter_nonmember)
12331 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
12332 D.setInvalidType();
12333 }
12334
12335 if (IsLambda && FTI.hasMutableQualifier()) {
12336 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
12337 DiagID: diag::err_explicit_object_parameter_mutable)
12338 << D.getSourceRange();
12339 }
12340
12341 if (IsLambda)
12342 return;
12343
12344 if (!DC || !DC->isRecord()) {
12345 assert(D.isInvalidType() && "Explicit object parameter in non-member "
12346 "should have been diagnosed already");
12347 return;
12348 }
12349
12350 // CWG2674: constructors and destructors cannot have explicit parameters.
12351 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
12352 Name.getNameKind() == DeclarationName::CXXDestructorName) {
12353 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
12354 DiagID: diag::err_explicit_object_parameter_constructor)
12355 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
12356 << D.getSourceRange();
12357 D.setInvalidType();
12358 }
12359}
12360
12361namespace {
12362/// Utility class to accumulate and print a diagnostic listing the invalid
12363/// specifier(s) on a declaration.
12364struct BadSpecifierDiagnoser {
12365 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
12366 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
12367 ~BadSpecifierDiagnoser() {
12368 Diagnostic << Specifiers;
12369 }
12370
12371 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
12372 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
12373 }
12374 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
12375 return check(SpecLoc,
12376 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
12377 }
12378 void check(SourceLocation SpecLoc, const char *Spec) {
12379 if (SpecLoc.isInvalid()) return;
12380 Diagnostic << SourceRange(SpecLoc, SpecLoc);
12381 if (!Specifiers.empty()) Specifiers += " ";
12382 Specifiers += Spec;
12383 }
12384
12385 Sema &S;
12386 Sema::SemaDiagnosticBuilder Diagnostic;
12387 std::string Specifiers;
12388};
12389}
12390
12391bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
12392 StorageClass &SC) {
12393 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
12394 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
12395 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
12396
12397 // C++ [temp.deduct.guide]p3:
12398 // A deduction-gide shall be declared in the same scope as the
12399 // corresponding class template.
12400 if (!CurContext->getRedeclContext()->Equals(
12401 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
12402 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
12403 << GuidedTemplateDecl;
12404 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
12405 }
12406
12407 auto &DS = D.getMutableDeclSpec();
12408 // We leave 'friend' and 'virtual' to be rejected in the normal way.
12409 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
12410 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
12411 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
12412 BadSpecifierDiagnoser Diagnoser(
12413 *this, D.getIdentifierLoc(),
12414 diag::err_deduction_guide_invalid_specifier);
12415
12416 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
12417 DS.ClearStorageClassSpecs();
12418 SC = SC_None;
12419
12420 // 'explicit' is permitted.
12421 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
12422 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
12423 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
12424 DS.ClearConstexprSpec();
12425
12426 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
12427 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
12428 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
12429 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
12430 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
12431 DS.ClearTypeQualifiers();
12432
12433 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
12434 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
12435 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
12436 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
12437 DS.ClearTypeSpecType();
12438 }
12439
12440 if (D.isInvalidType())
12441 return true;
12442
12443 // Check the declarator is simple enough.
12444 bool FoundFunction = false;
12445 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
12446 if (Chunk.Kind == DeclaratorChunk::Paren)
12447 continue;
12448 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
12449 Diag(Loc: D.getDeclSpec().getBeginLoc(),
12450 DiagID: diag::err_deduction_guide_with_complex_decl)
12451 << D.getSourceRange();
12452 break;
12453 }
12454 if (!Chunk.Fun.hasTrailingReturnType())
12455 return Diag(Loc: D.getName().getBeginLoc(),
12456 DiagID: diag::err_deduction_guide_no_trailing_return_type);
12457
12458 // Check that the return type is written as a specialization of
12459 // the template specified as the deduction-guide's name.
12460 // The template name may not be qualified. [temp.deduct.guide]
12461 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
12462 TypeSourceInfo *TSI = nullptr;
12463 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
12464 assert(TSI && "deduction guide has valid type but invalid return type?");
12465 bool AcceptableReturnType = false;
12466 bool MightInstantiateToSpecialization = false;
12467 if (auto RetTST =
12468 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
12469 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
12470 bool TemplateMatches = Context.hasSameTemplateName(
12471 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
12472
12473 const QualifiedTemplateName *Qualifiers =
12474 SpecifiedName.getAsQualifiedTemplateName();
12475 // A Template template parameter is never wrapped in a
12476 // QualifiedTemplateName, but it's always simply-written.
12477 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
12478 !Qualifiers->getQualifier());
12479 if (SimplyWritten && TemplateMatches)
12480 AcceptableReturnType = true;
12481 else {
12482 // This could still instantiate to the right type, unless we know it
12483 // names the wrong class template.
12484 auto *TD = SpecifiedName.getAsTemplateDecl();
12485 MightInstantiateToSpecialization =
12486 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
12487 }
12488 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
12489 MightInstantiateToSpecialization = true;
12490 }
12491
12492 if (!AcceptableReturnType)
12493 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
12494 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
12495 << GuidedTemplate << TSI->getType()
12496 << MightInstantiateToSpecialization
12497 << TSI->getTypeLoc().getSourceRange();
12498
12499 // Keep going to check that we don't have any inner declarator pieces (we
12500 // could still have a function returning a pointer to a function).
12501 FoundFunction = true;
12502 }
12503
12504 if (D.isFunctionDefinition())
12505 // we can still create a valid deduction guide here.
12506 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
12507 return false;
12508}
12509
12510//===----------------------------------------------------------------------===//
12511// Namespace Handling
12512//===----------------------------------------------------------------------===//
12513
12514/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
12515/// reopened.
12516static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
12517 SourceLocation Loc,
12518 IdentifierInfo *II, bool *IsInline,
12519 NamespaceDecl *PrevNS) {
12520 assert(*IsInline != PrevNS->isInline());
12521
12522 // 'inline' must appear on the original definition, but not necessarily
12523 // on all extension definitions, so the note should point to the first
12524 // definition to avoid confusion.
12525 PrevNS = PrevNS->getFirstDecl();
12526
12527 if (PrevNS->isInline())
12528 // The user probably just forgot the 'inline', so suggest that it
12529 // be added back.
12530 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
12531 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
12532 else
12533 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
12534
12535 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
12536 *IsInline = PrevNS->isInline();
12537}
12538
12539/// ActOnStartNamespaceDef - This is called at the start of a namespace
12540/// definition.
12541Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
12542 SourceLocation InlineLoc,
12543 SourceLocation NamespaceLoc,
12544 SourceLocation IdentLoc, IdentifierInfo *II,
12545 SourceLocation LBrace,
12546 const ParsedAttributesView &AttrList,
12547 UsingDirectiveDecl *&UD, bool IsNested) {
12548 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12549 // For anonymous namespace, take the location of the left brace.
12550 SourceLocation Loc = II ? IdentLoc : LBrace;
12551 bool IsInline = InlineLoc.isValid();
12552 bool IsInvalid = false;
12553 bool IsStd = false;
12554 bool AddToKnown = false;
12555 Scope *DeclRegionScope = NamespcScope->getParent();
12556
12557 NamespaceDecl *PrevNS = nullptr;
12558 if (II) {
12559 // C++ [namespace.std]p7:
12560 // A translation unit shall not declare namespace std to be an inline
12561 // namespace (9.8.2).
12562 //
12563 // Precondition: the std namespace is in the file scope and is declared to
12564 // be inline
12565 auto DiagnoseInlineStdNS = [&]() {
12566 assert(IsInline && II->isStr("std") &&
12567 CurContext->getRedeclContext()->isTranslationUnit() &&
12568 "Precondition of DiagnoseInlineStdNS not met");
12569 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
12570 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
12571 IsInline = false;
12572 };
12573 // C++ [namespace.def]p2:
12574 // The identifier in an original-namespace-definition shall not
12575 // have been previously defined in the declarative region in
12576 // which the original-namespace-definition appears. The
12577 // identifier in an original-namespace-definition is the name of
12578 // the namespace. Subsequently in that declarative region, it is
12579 // treated as an original-namespace-name.
12580 //
12581 // Since namespace names are unique in their scope, and we don't
12582 // look through using directives, just look for any ordinary names
12583 // as if by qualified name lookup.
12584 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12585 RedeclarationKind::ForExternalRedeclaration);
12586 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
12587 NamedDecl *PrevDecl =
12588 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12589 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
12590
12591 if (PrevNS) {
12592 // This is an extended namespace definition.
12593 if (IsInline && II->isStr(Str: "std") &&
12594 CurContext->getRedeclContext()->isTranslationUnit())
12595 DiagnoseInlineStdNS();
12596 else if (IsInline != PrevNS->isInline())
12597 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12598 IsInline: &IsInline, PrevNS);
12599 } else if (PrevDecl) {
12600 // This is an invalid name redefinition.
12601 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12602 << II;
12603 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12604 IsInvalid = true;
12605 // Continue on to push Namespc as current DeclContext and return it.
12606 } else if (II->isStr(Str: "std") &&
12607 CurContext->getRedeclContext()->isTranslationUnit()) {
12608 if (IsInline)
12609 DiagnoseInlineStdNS();
12610 // This is the first "real" definition of the namespace "std", so update
12611 // our cache of the "std" namespace to point at this definition.
12612 PrevNS = getStdNamespace();
12613 IsStd = true;
12614 AddToKnown = !IsInline;
12615 } else {
12616 // We've seen this namespace for the first time.
12617 AddToKnown = !IsInline;
12618 }
12619 } else {
12620 // Anonymous namespaces.
12621
12622 // Determine whether the parent already has an anonymous namespace.
12623 DeclContext *Parent = CurContext->getRedeclContext();
12624 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12625 PrevNS = TU->getAnonymousNamespace();
12626 } else {
12627 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12628 PrevNS = ND->getAnonymousNamespace();
12629 }
12630
12631 if (PrevNS && IsInline != PrevNS->isInline())
12632 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12633 IsInline: &IsInline, PrevNS);
12634 }
12635
12636 // Namespace lookup can find a namespace in an inline namespace. An extension
12637 // of that namespace retains its semantic parent, even when it is written in
12638 // an enclosing namespace.
12639 DeclContext *SemanticContext = CurContext;
12640 if (PrevNS && !CurContext->getRedeclContext()->Equals(
12641 DC: PrevNS->getDeclContext()->getRedeclContext()))
12642 SemanticContext = PrevNS->getDeclContext();
12643 NamespaceDecl *Namespc = NamespaceDecl::Create(
12644 C&: Context, DC: SemanticContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12645 Namespc->setLexicalDeclContext(CurContext);
12646 if (IsInvalid)
12647 Namespc->setInvalidDecl();
12648
12649 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12650 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12651 ProcessAPINotes(D: Namespc);
12652
12653 // FIXME: Should we be merging attributes?
12654 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12655 PushNamespaceVisibilityAttr(Attr, Loc);
12656
12657 if (IsStd)
12658 StdNamespace = Namespc;
12659 if (AddToKnown)
12660 KnownNamespaces[Namespc] = false;
12661
12662 if (II) {
12663 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12664 } else {
12665 // Link the anonymous namespace into its parent.
12666 DeclContext *Parent = CurContext->getRedeclContext();
12667 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12668 TU->setAnonymousNamespace(Namespc);
12669 } else {
12670 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12671 }
12672
12673 CurContext->addDecl(D: Namespc);
12674
12675 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12676 // behaves as if it were replaced by
12677 // namespace unique { /* empty body */ }
12678 // using namespace unique;
12679 // namespace unique { namespace-body }
12680 // where all occurrences of 'unique' in a translation unit are
12681 // replaced by the same identifier and this identifier differs
12682 // from all other identifiers in the entire program.
12683
12684 // We just create the namespace with an empty name and then add an
12685 // implicit using declaration, just like the standard suggests.
12686 //
12687 // CodeGen enforces the "universally unique" aspect by giving all
12688 // declarations semantically contained within an anonymous
12689 // namespace internal linkage.
12690
12691 if (!PrevNS) {
12692 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12693 /* 'using' */ UsingLoc: LBrace,
12694 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12695 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12696 /* identifier */ IdentLoc: SourceLocation(),
12697 Nominated: Namespc,
12698 /* Ancestor */ CommonAncestor: Parent);
12699 UD->setImplicit();
12700 Parent->addDecl(D: UD);
12701 }
12702 }
12703
12704 ActOnDocumentableDecl(D: Namespc);
12705
12706 // Although we could have an invalid decl (i.e. the namespace name is a
12707 // redefinition), push it as current DeclContext and try to continue parsing.
12708 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12709 // for the namespace has the declarations that showed up in that particular
12710 // namespace definition.
12711 PushDeclContext(S: NamespcScope, DC: Namespc);
12712 return Namespc;
12713}
12714
12715/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12716/// is a namespace alias, returns the namespace it points to.
12717static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12718 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12719 return AD->getNamespace();
12720 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12721}
12722
12723void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12724 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12725 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12726 Namespc->setRBraceLoc(RBrace);
12727 PopDeclContext();
12728 if (Namespc->hasAttr<VisibilityAttr>())
12729 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12730 // If this namespace contains an export-declaration, export it now.
12731 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12732 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12733}
12734
12735CXXRecordDecl *Sema::getStdBadAlloc() const {
12736 return cast_or_null<CXXRecordDecl>(
12737 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12738}
12739
12740EnumDecl *Sema::getStdAlignValT() const {
12741 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12742}
12743
12744NamespaceDecl *Sema::getStdNamespace() const {
12745 return cast_or_null<NamespaceDecl>(
12746 Val: StdNamespace.get(Source: Context.getExternalSource()));
12747}
12748
12749namespace {
12750
12751enum UnsupportedSTLSelect {
12752 USS_InvalidMember,
12753 USS_MissingMember,
12754 USS_NonTrivial,
12755 USS_Other
12756};
12757
12758struct InvalidSTLDiagnoser {
12759 Sema &S;
12760 SourceLocation Loc;
12761 QualType TyForDiags;
12762
12763 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12764 const VarDecl *VD = nullptr) {
12765 {
12766 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12767 << TyForDiags << ((int)Sel);
12768 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12769 assert(!Name.empty());
12770 D << Name;
12771 }
12772 }
12773 if (Sel == USS_InvalidMember) {
12774 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12775 << VD << VD->getSourceRange();
12776 }
12777 return QualType();
12778 }
12779};
12780} // namespace
12781
12782QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12783 SourceLocation Loc,
12784 ComparisonCategoryUsage Usage) {
12785 assert(getLangOpts().CPlusPlus &&
12786 "Looking for comparison category type outside of C++.");
12787
12788 // Use an elaborated type for diagnostics which has a name containing the
12789 // prepended 'std' namespace but not any inline namespace names.
12790 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12791 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12792 /*Prefix=*/std::nullopt);
12793 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12794 TD: Info->Record,
12795 /*OwnsTag=*/false);
12796 };
12797
12798 // Check if we've already successfully checked the comparison category type
12799 // before. If so, skip checking it again.
12800 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12801 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12802 // The only thing we need to check is that the type has a reachable
12803 // definition in the current context.
12804 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12805 return QualType();
12806
12807 return Info->getType();
12808 }
12809
12810 // If lookup failed
12811 if (!Info) {
12812 std::string NameForDiags = "std::";
12813 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12814 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12815 << NameForDiags << (int)Usage;
12816 return QualType();
12817 }
12818
12819 assert(Info->Kind == Kind);
12820 assert(Info->Record);
12821
12822 // Update the Record decl in case we encountered a forward declaration on our
12823 // first pass. FIXME: This is a bit of a hack.
12824 if (Info->Record->hasDefinition())
12825 Info->Record = Info->Record->getDefinition();
12826
12827 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12828 return QualType();
12829
12830 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12831
12832 if (!Info->Record->isTriviallyCopyable())
12833 return UnsupportedSTLError(USS_NonTrivial);
12834
12835 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12836 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12837 // Tolerate empty base classes.
12838 if (Base->isEmpty())
12839 continue;
12840 // Reject STL implementations which have at least one non-empty base.
12841 return UnsupportedSTLError();
12842 }
12843
12844 // Check that the STL has implemented the types using a single integer field.
12845 // This expectation allows better codegen for builtin operators. We require:
12846 // (1) The class has exactly one field.
12847 // (2) The field is an integral or enumeration type.
12848 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12849 if (std::distance(first: FIt, last: FEnd) != 1 ||
12850 !FIt->getType()->isIntegralOrEnumerationType()) {
12851 return UnsupportedSTLError();
12852 }
12853
12854 // Build each of the require values and store them in Info.
12855 for (ComparisonCategoryResult CCR :
12856 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12857 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12858 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12859
12860 if (!ValInfo)
12861 return UnsupportedSTLError(USS_MissingMember, MemName);
12862
12863 VarDecl *VD = ValInfo->VD;
12864 assert(VD && "should not be null!");
12865
12866 // Attempt to diagnose reasons why the STL definition of this type
12867 // might be foobar, including it failing to be a constant expression.
12868 // TODO Handle more ways the lookup or result can be invalid.
12869 if (!VD->isStaticDataMember() ||
12870 !VD->isUsableInConstantExpressions(C: Context))
12871 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12872
12873 // Attempt to evaluate the var decl as a constant expression and extract
12874 // the value of its first field as a ICE. If this fails, the STL
12875 // implementation is not supported.
12876 if (!ValInfo->hasValidIntValue())
12877 return UnsupportedSTLError();
12878
12879 MarkVariableReferenced(Loc, Var: VD);
12880 }
12881
12882 // We've successfully built the required types and expressions. Update
12883 // the cache and return the newly cached value.
12884 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12885 return Info->getType();
12886}
12887
12888NamespaceDecl *Sema::getOrCreateStdNamespace() {
12889 if (!StdNamespace) {
12890 // The "std" namespace has not yet been defined, so build one implicitly.
12891 StdNamespace = NamespaceDecl::Create(
12892 C&: Context, DC: Context.getTranslationUnitDecl(),
12893 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12894 Id: &PP.getIdentifierTable().get(Name: "std"),
12895 /*PrevDecl=*/nullptr, /*Nested=*/false);
12896 getStdNamespace()->setImplicit(true);
12897 // We want the created NamespaceDecl to be available for redeclaration
12898 // lookups, but not for regular name lookups.
12899 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12900 getStdNamespace()->clearIdentifierNamespace();
12901 }
12902
12903 return getStdNamespace();
12904}
12905
12906static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12907 const char *ClassName,
12908 ClassTemplateDecl **CachedDecl,
12909 const Decl **MalformedDecl) {
12910 // We're looking for implicit instantiations of
12911 // template <typename U> class std::{ClassName}.
12912
12913 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12914 // it.
12915 return false;
12916
12917 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12918 if (!MalformedDecl)
12919 return;
12920 if (!D)
12921 D = SugaredType->getAsTagDecl();
12922 if (!D || !D->isInStdNamespace())
12923 return;
12924 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12925 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12926 *MalformedDecl = D;
12927 };
12928
12929 ClassTemplateDecl *Template = nullptr;
12930 ArrayRef<TemplateArgument> Arguments;
12931 if (const TemplateSpecializationType *TST =
12932 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12933 Template = dyn_cast_or_null<ClassTemplateDecl>(
12934 Val: TST->getTemplateName().getAsTemplateDecl());
12935 Arguments = TST->template_arguments();
12936 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12937 Template = TT->getTemplateDecl();
12938 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12939 }
12940
12941 if (!Template) {
12942 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12943 return false;
12944 }
12945
12946 if (!*CachedDecl) {
12947 // Haven't recognized std::{ClassName} yet, maybe this is it.
12948 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12949 // semantics of this are slightly different, most notably the existing
12950 // "lookup" semantics explicitly diagnose an invalid definition as an
12951 // error.
12952 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12953 if (TemplateClass->getIdentifier() !=
12954 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12955 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12956 NS: TemplateClass->getNonTransparentDeclContext()))
12957 return false;
12958 // This is a template called std::{ClassName}, but is it the right
12959 // template?
12960 TemplateParameterList *Params = Template->getTemplateParameters();
12961 if (Params->getMinRequiredArguments() != 1 ||
12962 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12963 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12964 if (MalformedDecl)
12965 *MalformedDecl = TemplateClass;
12966 return false;
12967 }
12968
12969 // It's the right template.
12970 *CachedDecl = Template;
12971 }
12972
12973 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12974 return false;
12975
12976 // This is an instance of std::{ClassName}. Find the argument type.
12977 if (TypeArg) {
12978 QualType ArgType = Arguments[0].getAsType();
12979 // FIXME: Since TST only has as-written arguments, we have to perform the
12980 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12981 // - If an explicitly-specified template argument type is a lifetime type
12982 // with no lifetime qualifier, the __strong lifetime qualifier is
12983 // inferred.
12984 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12985 !ArgType.getObjCLifetime()) {
12986 Qualifiers Qs;
12987 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12988 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12989 }
12990 *TypeArg = ArgType;
12991 }
12992
12993 return true;
12994}
12995
12996bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12997 assert(getLangOpts().CPlusPlus &&
12998 "Looking for std::initializer_list outside of C++.");
12999
13000 // We're looking for implicit instantiations of
13001 // template <typename E> class std::initializer_list.
13002
13003 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
13004 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
13005}
13006
13007bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
13008 const Decl **MalformedDecl) {
13009 assert(getLangOpts().CPlusPlus &&
13010 "Looking for std::type_identity outside of C++.");
13011
13012 // We're looking for implicit instantiations of
13013 // template <typename T> struct std::type_identity.
13014
13015 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
13016 CachedDecl: &StdTypeIdentity, MalformedDecl);
13017}
13018
13019static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
13020 const char *ClassName,
13021 bool *WasMalformed) {
13022 if (!S.StdNamespace)
13023 return nullptr;
13024
13025 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
13026 Sema::LookupOrdinaryName);
13027 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
13028 return nullptr;
13029
13030 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
13031 if (!Template) {
13032 Result.suppressDiagnostics();
13033 // We found something weird. Complain about the first thing we found.
13034 NamedDecl *Found = *Result.begin();
13035 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
13036 << ClassName;
13037 if (WasMalformed)
13038 *WasMalformed = true;
13039 return nullptr;
13040 }
13041
13042 // We found some template with the correct name. Now verify that it's
13043 // correct.
13044 TemplateParameterList *Params = Template->getTemplateParameters();
13045 if (Params->getMinRequiredArguments() != 1 ||
13046 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
13047 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
13048 << ClassName;
13049 if (WasMalformed)
13050 *WasMalformed = true;
13051 return nullptr;
13052 }
13053
13054 return Template;
13055}
13056
13057static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
13058 QualType TypeParam, SourceLocation Loc) {
13059 assert(S.getStdNamespace());
13060 TemplateArgumentListInfo Args(Loc, Loc);
13061 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
13062 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
13063
13064 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
13065 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
13066 /*ForNestedNameSpecifier=*/false);
13067}
13068
13069QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
13070 if (!StdInitializerList) {
13071 bool WasMalformed = false;
13072 StdInitializerList =
13073 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
13074 if (!StdInitializerList) {
13075 if (!WasMalformed)
13076 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
13077 return QualType();
13078 }
13079 }
13080 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
13081}
13082
13083QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
13084 if (!StdTypeIdentity) {
13085 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
13086 /*WasMalformed=*/nullptr);
13087 if (!StdTypeIdentity)
13088 return QualType();
13089 }
13090 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
13091}
13092
13093bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
13094 // C++ [dcl.init.list]p2:
13095 // A constructor is an initializer-list constructor if its first parameter
13096 // is of type std::initializer_list<E> or reference to possibly cv-qualified
13097 // std::initializer_list<E> for some type E, and either there are no other
13098 // parameters or else all other parameters have default arguments.
13099 if (!Ctor->hasOneParamOrDefaultArgs())
13100 return false;
13101
13102 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
13103 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
13104 ArgType = RT->getPointeeType().getUnqualifiedType();
13105
13106 return isStdInitializerList(Ty: ArgType, Element: nullptr);
13107}
13108
13109/// Determine whether a using statement is in a context where it will be
13110/// apply in all contexts.
13111static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
13112 switch (CurContext->getDeclKind()) {
13113 case Decl::TranslationUnit:
13114 return true;
13115 case Decl::LinkageSpec:
13116 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
13117 default:
13118 return false;
13119 }
13120}
13121
13122namespace {
13123
13124// Callback to only accept typo corrections that are namespaces.
13125class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
13126public:
13127 bool ValidateCandidate(const TypoCorrection &candidate) override {
13128 if (NamedDecl *ND = candidate.getCorrectionDecl())
13129 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
13130 return false;
13131 }
13132
13133 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13134 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
13135 }
13136};
13137
13138}
13139
13140static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
13141 Sema &S) {
13142 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
13143 Module *M = ND->getOwningModule();
13144 assert(M && "hidden namespace definition not in a module?");
13145
13146 if (M->isExplicitGlobalModule())
13147 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
13148 DiagID: diag::err_module_unimported_use_header)
13149 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
13150 << /*Header Name*/ false;
13151 else
13152 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
13153 DiagID: diag::err_module_unimported_use)
13154 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
13155 << M->getTopLevelModuleName();
13156}
13157
13158static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
13159 CXXScopeSpec &SS,
13160 SourceLocation IdentLoc,
13161 IdentifierInfo *Ident) {
13162 R.clear();
13163 NamespaceValidatorCCC CCC{};
13164 if (TypoCorrection Corrected =
13165 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
13166 Mode: CorrectTypoKind::ErrorRecovery)) {
13167 // Generally we find it is confusing more than helpful to diagnose the
13168 // invisible namespace.
13169 // See https://github.com/llvm/llvm-project/issues/73893.
13170 //
13171 // However, we should diagnose when the users are trying to using an
13172 // invisible namespace. So we handle the case specially here.
13173 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
13174 Corrected.requiresImport()) {
13175 DiagnoseInvisibleNamespace(Corrected, S);
13176 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
13177 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
13178 bool DroppedSpecifier =
13179 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
13180 S.diagnoseTypo(Correction: Corrected,
13181 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
13182 << Ident << DC << DroppedSpecifier << SS.getRange(),
13183 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
13184 } else {
13185 S.diagnoseTypo(Correction: Corrected,
13186 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
13187 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
13188 }
13189 R.addDecl(D: Corrected.getFoundDecl());
13190 return true;
13191 }
13192 return false;
13193}
13194
13195Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
13196 SourceLocation NamespcLoc, CXXScopeSpec &SS,
13197 SourceLocation IdentLoc,
13198 IdentifierInfo *NamespcName,
13199 const ParsedAttributesView &AttrList) {
13200 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13201 assert(NamespcName && "Invalid NamespcName.");
13202 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
13203
13204 // Get the innermost enclosing declaration scope.
13205 S = S->getDeclParent();
13206
13207 UsingDirectiveDecl *UDir = nullptr;
13208 NestedNameSpecifier Qualifier = SS.getScopeRep();
13209
13210 // Lookup namespace name.
13211 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
13212 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
13213 if (R.isAmbiguous())
13214 return nullptr;
13215
13216 if (R.empty()) {
13217 R.clear();
13218 // Allow "using namespace std;" or "using namespace ::std;" even if
13219 // "std" hasn't been defined yet, for GCC compatibility.
13220 if ((!Qualifier ||
13221 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
13222 NamespcName->isStr(Str: "std")) {
13223 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
13224 R.addDecl(D: getOrCreateStdNamespace());
13225 R.resolveKind();
13226 }
13227 // Otherwise, attempt typo correction.
13228 else
13229 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
13230 }
13231
13232 if (!R.empty()) {
13233 NamedDecl *Named = R.getRepresentativeDecl();
13234 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
13235 assert(NS && "expected namespace decl");
13236
13237 // The use of a nested name specifier may trigger deprecation warnings.
13238 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
13239
13240 // C++ [namespace.udir]p1:
13241 // A using-directive specifies that the names in the nominated
13242 // namespace can be used in the scope in which the
13243 // using-directive appears after the using-directive. During
13244 // unqualified name lookup (3.4.1), the names appear as if they
13245 // were declared in the nearest enclosing namespace which
13246 // contains both the using-directive and the nominated
13247 // namespace. [Note: in this context, "contains" means "contains
13248 // directly or indirectly". ]
13249
13250 // Find enclosing context containing both using-directive and
13251 // nominated namespace.
13252 DeclContext *CommonAncestor = NS;
13253 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
13254 CommonAncestor = CommonAncestor->getParent();
13255
13256 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
13257 QualifierLoc: SS.getWithLocInContext(Context),
13258 IdentLoc, Nominated: Named, CommonAncestor);
13259
13260 if (IsUsingDirectiveInToplevelContext(CurContext) &&
13261 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
13262 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
13263 }
13264
13265 PushUsingDirective(S, UDir);
13266 } else {
13267 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
13268 }
13269
13270 if (UDir) {
13271 ProcessDeclAttributeList(S, D: UDir, AttrList);
13272 ProcessAPINotes(D: UDir);
13273 }
13274
13275 return UDir;
13276}
13277
13278void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
13279 // If the scope has an associated entity and the using directive is at
13280 // namespace or translation unit scope, add the UsingDirectiveDecl into
13281 // its lookup structure so qualified name lookup can find it.
13282 DeclContext *Ctx = S->getEntity();
13283 if (Ctx && !Ctx->isFunctionOrMethod())
13284 Ctx->addDecl(D: UDir);
13285 else
13286 // Otherwise, it is at block scope. The using-directives will affect lookup
13287 // only to the end of the scope.
13288 S->PushUsingDirective(UDir);
13289}
13290
13291Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
13292 SourceLocation UsingLoc,
13293 SourceLocation TypenameLoc, CXXScopeSpec &SS,
13294 UnqualifiedId &Name,
13295 SourceLocation EllipsisLoc,
13296 const ParsedAttributesView &AttrList) {
13297 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
13298
13299 if (SS.isEmpty()) {
13300 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
13301 return nullptr;
13302 }
13303
13304 switch (Name.getKind()) {
13305 case UnqualifiedIdKind::IK_ImplicitSelfParam:
13306 case UnqualifiedIdKind::IK_Identifier:
13307 case UnqualifiedIdKind::IK_OperatorFunctionId:
13308 case UnqualifiedIdKind::IK_LiteralOperatorId:
13309 case UnqualifiedIdKind::IK_ConversionFunctionId:
13310 break;
13311
13312 case UnqualifiedIdKind::IK_ConstructorName:
13313 case UnqualifiedIdKind::IK_ConstructorTemplateId:
13314 // C++11 inheriting constructors.
13315 Diag(Loc: Name.getBeginLoc(),
13316 DiagID: getLangOpts().CPlusPlus11
13317 ? diag::warn_cxx98_compat_using_decl_constructor
13318 : diag::err_using_decl_constructor)
13319 << SS.getRange();
13320
13321 if (getLangOpts().CPlusPlus11) break;
13322
13323 return nullptr;
13324
13325 case UnqualifiedIdKind::IK_DestructorName:
13326 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
13327 return nullptr;
13328
13329 case UnqualifiedIdKind::IK_TemplateId:
13330 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
13331 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
13332 return nullptr;
13333
13334 case UnqualifiedIdKind::IK_DeductionGuideName:
13335 llvm_unreachable("cannot parse qualified deduction guide name");
13336 }
13337
13338 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
13339 DeclarationName TargetName = TargetNameInfo.getName();
13340 if (!TargetName)
13341 return nullptr;
13342
13343 // Warn about access declarations.
13344 if (UsingLoc.isInvalid()) {
13345 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
13346 ? diag::err_access_decl
13347 : diag::warn_access_decl_deprecated)
13348 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
13349 }
13350
13351 if (EllipsisLoc.isInvalid()) {
13352 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
13353 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
13354 return nullptr;
13355 } else {
13356 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
13357 !TargetNameInfo.containsUnexpandedParameterPack()) {
13358 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
13359 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
13360 EllipsisLoc = SourceLocation();
13361 }
13362 }
13363
13364 NamedDecl *UD =
13365 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
13366 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
13367 /*IsInstantiation*/ false,
13368 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
13369 if (UD)
13370 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
13371
13372 return UD;
13373}
13374
13375Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13376 SourceLocation UsingLoc,
13377 SourceLocation EnumLoc, SourceRange TyLoc,
13378 const IdentifierInfo &II, ParsedType Ty,
13379 const CXXScopeSpec &SS) {
13380 TypeSourceInfo *TSI = nullptr;
13381 SourceLocation IdentLoc = TyLoc.getBegin();
13382 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
13383 if (EnumTy.isNull()) {
13384 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
13385 ? diag::err_using_enum_is_dependent
13386 : diag::err_unknown_typename)
13387 << II.getName()
13388 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
13389 TyLoc.getEnd());
13390 return nullptr;
13391 }
13392
13393 if (EnumTy->isDependentType()) {
13394 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
13395 return nullptr;
13396 }
13397
13398 auto *Enum = EnumTy->getAsEnumDecl();
13399 if (!Enum) {
13400 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
13401 return nullptr;
13402 }
13403
13404 if (TSI == nullptr)
13405 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
13406
13407 auto *UD =
13408 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
13409
13410 if (UD)
13411 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
13412
13413 return UD;
13414}
13415
13416/// Determine whether a using declaration considers the given
13417/// declarations as "equivalent", e.g., if they are redeclarations of
13418/// the same entity or are both typedefs of the same type.
13419static bool
13420IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
13421 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
13422 return true;
13423
13424 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
13425 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
13426 return Context.hasSameType(T1: TD1->getUnderlyingType(),
13427 T2: TD2->getUnderlyingType());
13428
13429 // Two using_if_exists using-declarations are equivalent if both are
13430 // unresolved.
13431 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
13432 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
13433 return true;
13434
13435 return false;
13436}
13437
13438bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
13439 const LookupResult &Previous,
13440 UsingShadowDecl *&PrevShadow) {
13441 // Diagnose finding a decl which is not from a base class of the
13442 // current class. We do this now because there are cases where this
13443 // function will silently decide not to build a shadow decl, which
13444 // will pre-empt further diagnostics.
13445 //
13446 // We don't need to do this in C++11 because we do the check once on
13447 // the qualifier.
13448 //
13449 // FIXME: diagnose the following if we care enough:
13450 // struct A { int foo; };
13451 // struct B : A { using A::foo; };
13452 // template <class T> struct C : A {};
13453 // template <class T> struct D : C<T> { using B::foo; } // <---
13454 // This is invalid (during instantiation) in C++03 because B::foo
13455 // resolves to the using decl in B, which is not a base class of D<T>.
13456 // We can't diagnose it immediately because C<T> is an unknown
13457 // specialization. The UsingShadowDecl in D<T> then points directly
13458 // to A::foo, which will look well-formed when we instantiate.
13459 // The right solution is to not collapse the shadow-decl chain.
13460 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
13461 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
13462 DeclContext *OrigDC = Orig->getDeclContext();
13463
13464 // Handle enums and anonymous structs.
13465 if (isa<EnumDecl>(Val: OrigDC))
13466 OrigDC = OrigDC->getParent();
13467 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
13468 while (OrigRec->isAnonymousStructOrUnion())
13469 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
13470
13471 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
13472 if (OrigDC == CurContext) {
13473 Diag(Loc: Using->getLocation(),
13474 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13475 << Using->getQualifierLoc().getSourceRange();
13476 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
13477 Using->setInvalidDecl();
13478 return true;
13479 }
13480
13481 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
13482 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13483 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
13484 << Using->getQualifierLoc().getSourceRange();
13485 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
13486 Using->setInvalidDecl();
13487 return true;
13488 }
13489 }
13490
13491 if (Previous.empty()) return false;
13492
13493 NamedDecl *Target = Orig;
13494 if (isa<UsingShadowDecl>(Val: Target))
13495 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13496
13497 // If the target happens to be one of the previous declarations, we
13498 // don't have a conflict.
13499 //
13500 // FIXME: but we might be increasing its access, in which case we
13501 // should redeclare it.
13502 NamedDecl *NonTag = nullptr, *Tag = nullptr;
13503 bool FoundEquivalentDecl = false;
13504 for (NamedDecl *Element : Previous) {
13505 NamedDecl *D = Element->getUnderlyingDecl();
13506 // We can have UsingDecls in our Previous results because we use the same
13507 // LookupResult for checking whether the UsingDecl itself is a valid
13508 // redeclaration.
13509 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
13510 continue;
13511
13512 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
13513 // C++ [class.mem]p19:
13514 // If T is the name of a class, then [every named member other than
13515 // a non-static data member] shall have a name different from T
13516 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
13517 !isa<IndirectFieldDecl>(Val: Target) &&
13518 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
13519 DiagnoseClassNameShadow(
13520 DC: CurContext,
13521 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
13522 return true;
13523 }
13524
13525 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
13526 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
13527 PrevShadow = Shadow;
13528 FoundEquivalentDecl = true;
13529 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
13530 // We don't conflict with an existing using shadow decl of an equivalent
13531 // declaration, but we're not a redeclaration of it.
13532 FoundEquivalentDecl = true;
13533 }
13534
13535 if (isVisible(D))
13536 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
13537 }
13538
13539 if (FoundEquivalentDecl)
13540 return false;
13541
13542 // Always emit a diagnostic for a mismatch between an unresolved
13543 // using_if_exists and a resolved using declaration in either direction.
13544 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
13545 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
13546 if (!NonTag && !Tag)
13547 return false;
13548 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13549 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13550 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
13551 DiagID: diag::note_using_decl_conflict);
13552 BUD->setInvalidDecl();
13553 return true;
13554 }
13555
13556 if (FunctionDecl *FD = Target->getAsFunction()) {
13557 NamedDecl *OldDecl = nullptr;
13558 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
13559 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
13560 case OverloadKind::Overload:
13561 return false;
13562
13563 case OverloadKind::NonFunction:
13564 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13565 break;
13566
13567 // We found a decl with the exact signature.
13568 case OverloadKind::Match:
13569 // If we're in a record, we want to hide the target, so we
13570 // return true (without a diagnostic) to tell the caller not to
13571 // build a shadow decl.
13572 if (CurContext->isRecord())
13573 return true;
13574
13575 // If we're not in a record, this is an error.
13576 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13577 break;
13578 }
13579
13580 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13581 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
13582 BUD->setInvalidDecl();
13583 return true;
13584 }
13585
13586 // Target is not a function.
13587
13588 if (isa<TagDecl>(Val: Target)) {
13589 // No conflict between a tag and a non-tag.
13590 if (!Tag) return false;
13591
13592 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13593 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13594 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
13595 BUD->setInvalidDecl();
13596 return true;
13597 }
13598
13599 // No conflict between a tag and a non-tag.
13600 if (!NonTag) return false;
13601
13602 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13603 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13604 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13605 BUD->setInvalidDecl();
13606 return true;
13607}
13608
13609/// Determine whether a direct base class is a virtual base class.
13610static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13611 if (!Derived->getNumVBases())
13612 return false;
13613 for (auto &B : Derived->bases())
13614 if (B.getType()->getAsCXXRecordDecl() == Base)
13615 return B.isVirtual();
13616 llvm_unreachable("not a direct base class");
13617}
13618
13619UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13620 NamedDecl *Orig,
13621 UsingShadowDecl *PrevDecl) {
13622 // If we resolved to another shadow declaration, just coalesce them.
13623 NamedDecl *Target = Orig;
13624 if (isa<UsingShadowDecl>(Val: Target)) {
13625 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13626 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13627 }
13628
13629 NamedDecl *NonTemplateTarget = Target;
13630 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13631 NonTemplateTarget = TargetTD->getTemplatedDecl();
13632
13633 UsingShadowDecl *Shadow;
13634 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13635 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13636 bool IsVirtualBase =
13637 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13638 Base: Using->getQualifier().getAsRecordDecl());
13639 Shadow = ConstructorUsingShadowDecl::Create(
13640 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13641 } else {
13642 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13643 Name: Target->getDeclName(), Introducer: BUD, Target);
13644 }
13645 BUD->addShadowDecl(S: Shadow);
13646
13647 Shadow->setAccess(BUD->getAccess());
13648 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13649 Shadow->setInvalidDecl();
13650
13651 Shadow->setPreviousDecl(PrevDecl);
13652
13653 if (S)
13654 PushOnScopeChains(D: Shadow, S);
13655 else
13656 CurContext->addDecl(D: Shadow);
13657
13658
13659 return Shadow;
13660}
13661
13662void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13663 if (Shadow->getDeclName().getNameKind() ==
13664 DeclarationName::CXXConversionFunctionName)
13665 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13666
13667 // Remove it from the DeclContext...
13668 Shadow->getDeclContext()->removeDecl(D: Shadow);
13669
13670 // ...and the scope, if applicable...
13671 if (S) {
13672 S->RemoveDecl(D: Shadow);
13673 IdResolver.RemoveDecl(D: Shadow);
13674 }
13675
13676 // ...and the using decl.
13677 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13678
13679 // TODO: complain somehow if Shadow was used. It shouldn't
13680 // be possible for this to happen, because...?
13681}
13682
13683/// Find the base specifier for a base class with the given type.
13684static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13685 QualType DesiredBase,
13686 bool &AnyDependentBases) {
13687 // Check whether the named type is a direct base class.
13688 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13689 for (auto &Base : Derived->bases()) {
13690 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13691 if (CanonicalDesiredBase == BaseType)
13692 return &Base;
13693 if (BaseType->isDependentType())
13694 AnyDependentBases = true;
13695 }
13696 return nullptr;
13697}
13698
13699namespace {
13700class UsingValidatorCCC final : public CorrectionCandidateCallback {
13701public:
13702 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13703 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13704 : HasTypenameKeyword(HasTypenameKeyword),
13705 IsInstantiation(IsInstantiation), OldNNS(NNS),
13706 RequireMemberOf(RequireMemberOf) {}
13707
13708 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13709 NamedDecl *ND = Candidate.getCorrectionDecl();
13710
13711 // Keywords are not valid here.
13712 if (!ND || isa<NamespaceDecl>(Val: ND))
13713 return false;
13714
13715 // Completely unqualified names are invalid for a 'using' declaration.
13716 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13717 return false;
13718
13719 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13720 // reject.
13721
13722 if (RequireMemberOf) {
13723 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13724 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13725 // No-one ever wants a using-declaration to name an injected-class-name
13726 // of a base class, unless they're declaring an inheriting constructor.
13727 ASTContext &Ctx = ND->getASTContext();
13728 if (!Ctx.getLangOpts().CPlusPlus11)
13729 return false;
13730 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13731
13732 // Check that the injected-class-name is named as a member of its own
13733 // type; we don't want to suggest 'using Derived::Base;', since that
13734 // means something else.
13735 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13736 ? Candidate.getCorrectionSpecifier()
13737 : OldNNS;
13738 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13739 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13740 return false;
13741
13742 // Check that this inheriting constructor declaration actually names a
13743 // direct base class of the current class.
13744 bool AnyDependentBases = false;
13745 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13746 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13747 AnyDependentBases) &&
13748 !AnyDependentBases)
13749 return false;
13750 } else {
13751 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13752 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13753 return false;
13754
13755 // FIXME: Check that the base class member is accessible?
13756 }
13757 } else {
13758 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13759 if (FoundRecord && FoundRecord->isInjectedClassName())
13760 return false;
13761 }
13762
13763 if (isa<TypeDecl>(Val: ND))
13764 return HasTypenameKeyword || !IsInstantiation;
13765
13766 return !HasTypenameKeyword;
13767 }
13768
13769 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13770 return std::make_unique<UsingValidatorCCC>(args&: *this);
13771 }
13772
13773private:
13774 bool HasTypenameKeyword;
13775 bool IsInstantiation;
13776 NestedNameSpecifier OldNNS;
13777 CXXRecordDecl *RequireMemberOf;
13778};
13779} // end anonymous namespace
13780
13781void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13782 // It is really dumb that we have to do this.
13783 LookupResult::Filter F = Previous.makeFilter();
13784 while (F.hasNext()) {
13785 NamedDecl *D = F.next();
13786 if (!isDeclInScope(D, Ctx: CurContext, S))
13787 F.erase();
13788 // If we found a local extern declaration that's not ordinarily visible,
13789 // and this declaration is being added to a non-block scope, ignore it.
13790 // We're only checking for scope conflicts here, not also for violations
13791 // of the linkage rules.
13792 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13793 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13794 F.erase();
13795 }
13796 F.done();
13797}
13798
13799NamedDecl *Sema::BuildUsingDeclaration(
13800 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13801 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13802 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13803 const ParsedAttributesView &AttrList, bool IsInstantiation,
13804 bool IsUsingIfExists) {
13805 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13806 SourceLocation IdentLoc = NameInfo.getLoc();
13807 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13808
13809 // FIXME: We ignore attributes for now.
13810
13811 // For an inheriting constructor declaration, the name of the using
13812 // declaration is the name of a constructor in this class, not in the
13813 // base class.
13814 DeclarationNameInfo UsingName = NameInfo;
13815 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13816 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13817 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13818 Ty: Context.getCanonicalTagType(TD: RD)));
13819
13820 // Do the redeclaration lookup in the current scope.
13821 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13822 RedeclarationKind::ForVisibleRedeclaration);
13823 Previous.setHideTags(false);
13824 if (S) {
13825 LookupName(R&: Previous, S);
13826
13827 FilterUsingLookup(S, Previous);
13828 } else {
13829 assert(IsInstantiation && "no scope in non-instantiation");
13830 if (CurContext->isRecord())
13831 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13832 else {
13833 // No redeclaration check is needed here; in non-member contexts we
13834 // diagnosed all possible conflicts with other using-declarations when
13835 // building the template:
13836 //
13837 // For a dependent non-type using declaration, the only valid case is
13838 // if we instantiate to a single enumerator. We check for conflicts
13839 // between shadow declarations we introduce, and we check in the template
13840 // definition for conflicts between a non-type using declaration and any
13841 // other declaration, which together covers all cases.
13842 //
13843 // A dependent typename using declaration will never successfully
13844 // instantiate, since it will always name a class member, so we reject
13845 // that in the template definition.
13846 }
13847 }
13848
13849 // Check for invalid redeclarations.
13850 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13851 SS, NameLoc: IdentLoc, Previous))
13852 return nullptr;
13853
13854 // 'using_if_exists' doesn't make sense on an inherited constructor.
13855 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13856 DeclarationName::CXXConstructorName) {
13857 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13858 return nullptr;
13859 }
13860
13861 DeclContext *LookupContext = computeDeclContext(SS);
13862 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13863 if (!LookupContext || EllipsisLoc.isValid()) {
13864 NamedDecl *D;
13865 // Dependent scope, or an unexpanded pack
13866 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13867 SS, NameInfo, NameLoc: IdentLoc))
13868 return nullptr;
13869
13870 if (Previous.isSingleResult() &&
13871 Previous.getFoundDecl()->isTemplateParameter())
13872 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13873
13874 if (HasTypenameKeyword) {
13875 // FIXME: not all declaration name kinds are legal here
13876 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13877 UsingLoc, TypenameLoc,
13878 QualifierLoc,
13879 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13880 EllipsisLoc);
13881 } else {
13882 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13883 QualifierLoc, NameInfo, EllipsisLoc);
13884 }
13885 D->setAccess(AS);
13886 CurContext->addDecl(D);
13887 ProcessDeclAttributeList(S, D, AttrList);
13888 return D;
13889 }
13890
13891 auto Build = [&](bool Invalid) {
13892 UsingDecl *UD =
13893 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13894 NameInfo: UsingName, HasTypenameKeyword);
13895 UD->setAccess(AS);
13896 CurContext->addDecl(D: UD);
13897 ProcessDeclAttributeList(S, D: UD, AttrList);
13898 UD->setInvalidDecl(Invalid);
13899 return UD;
13900 };
13901 auto BuildInvalid = [&]{ return Build(true); };
13902 auto BuildValid = [&]{ return Build(false); };
13903
13904 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13905 return BuildInvalid();
13906
13907 // Look up the target name.
13908 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13909
13910 // Unlike most lookups, we don't always want to hide tag
13911 // declarations: tag names are visible through the using declaration
13912 // even if hidden by ordinary names, *except* in a dependent context
13913 // where they may be used by two-phase lookup.
13914 if (!IsInstantiation)
13915 R.setHideTags(false);
13916
13917 // For the purposes of this lookup, we have a base object type
13918 // equal to that of the current context.
13919 if (CurContext->isRecord()) {
13920 R.setBaseObjectType(
13921 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13922 }
13923
13924 LookupQualifiedName(R, LookupCtx: LookupContext);
13925
13926 // Validate the context, now we have a lookup
13927 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13928 NameLoc: IdentLoc, R: &R))
13929 return nullptr;
13930
13931 if (R.empty() && IsUsingIfExists)
13932 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13933 Name: UsingName.getName()),
13934 AS: AS_public);
13935
13936 // Try to correct typos if possible. If constructor name lookup finds no
13937 // results, that means the named class has no explicit constructors, and we
13938 // suppressed declaring implicit ones (probably because it's dependent or
13939 // invalid).
13940 if (R.empty() &&
13941 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13942 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13943 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13944 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13945 auto *II = NameInfo.getName().getAsIdentifierInfo();
13946 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13947 CurContext->isStdNamespace() &&
13948 isa<TranslationUnitDecl>(Val: LookupContext) &&
13949 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13950 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13951 return nullptr;
13952 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13953 dyn_cast<CXXRecordDecl>(Val: CurContext));
13954 if (TypoCorrection Corrected =
13955 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13956 Mode: CorrectTypoKind::ErrorRecovery)) {
13957 // We reject candidates where DroppedSpecifier == true, hence the
13958 // literal '0' below.
13959 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13960 << NameInfo.getName() << LookupContext << 0
13961 << SS.getRange());
13962
13963 // If we picked a correction with no attached Decl we can't do anything
13964 // useful with it, bail out.
13965 NamedDecl *ND = Corrected.getCorrectionDecl();
13966 if (!ND)
13967 return BuildInvalid();
13968
13969 // If we corrected to an inheriting constructor, handle it as one.
13970 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13971 if (RD && RD->isInjectedClassName()) {
13972 // The parent of the injected class name is the class itself.
13973 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13974
13975 // Fix up the information we'll use to build the using declaration.
13976 if (Corrected.WillReplaceSpecifier()) {
13977 NestedNameSpecifierLocBuilder Builder;
13978 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13979 R: QualifierLoc.getSourceRange());
13980 QualifierLoc = Builder.getWithLocInContext(Context);
13981 }
13982
13983 // In this case, the name we introduce is the name of a derived class
13984 // constructor.
13985 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13986 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13987 Ty: Context.getCanonicalTagType(TD: CurClass)));
13988 UsingName.setNamedTypeInfo(nullptr);
13989 for (auto *Ctor : LookupConstructors(Class: RD))
13990 R.addDecl(D: Ctor);
13991 R.resolveKind();
13992 } else {
13993 // FIXME: Pick up all the declarations if we found an overloaded
13994 // function.
13995 UsingName.setName(ND->getDeclName());
13996 R.addDecl(D: ND);
13997 }
13998 } else {
13999 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
14000 << NameInfo.getName() << LookupContext << SS.getRange();
14001 return BuildInvalid();
14002 }
14003 }
14004
14005 if (R.isAmbiguous())
14006 return BuildInvalid();
14007
14008 if (HasTypenameKeyword) {
14009 // If we asked for a typename and got a non-type decl, error out.
14010 if (!R.getAsSingle<TypeDecl>() &&
14011 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
14012 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
14013 for (const NamedDecl *D : R)
14014 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
14015 DiagID: diag::note_using_decl_target);
14016 return BuildInvalid();
14017 }
14018 } else {
14019 // If we asked for a non-typename and we got a type, error out,
14020 // but only if this is an instantiation of an unresolved using
14021 // decl. Otherwise just silently find the type name.
14022 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
14023 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
14024 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
14025 return BuildInvalid();
14026 }
14027 }
14028
14029 // C++14 [namespace.udecl]p6:
14030 // A using-declaration shall not name a namespace.
14031 if (R.getAsSingle<NamespaceDecl>()) {
14032 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
14033 << SS.getRange();
14034 // Suggest using 'using namespace ...' instead.
14035 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
14036 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
14037 return BuildInvalid();
14038 }
14039
14040 UsingDecl *UD = BuildValid();
14041
14042 // Some additional rules apply to inheriting constructors.
14043 if (UsingName.getName().getNameKind() ==
14044 DeclarationName::CXXConstructorName) {
14045 // Suppress access diagnostics; the access check is instead performed at the
14046 // point of use for an inheriting constructor.
14047 R.suppressDiagnostics();
14048 if (CheckInheritingConstructorUsingDecl(UD))
14049 return UD;
14050 }
14051
14052 for (NamedDecl *D : R) {
14053 UsingShadowDecl *PrevDecl = nullptr;
14054 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
14055 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
14056 }
14057
14058 return UD;
14059}
14060
14061NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
14062 SourceLocation UsingLoc,
14063 SourceLocation EnumLoc,
14064 SourceLocation NameLoc,
14065 TypeSourceInfo *EnumType,
14066 EnumDecl *ED) {
14067 bool Invalid = false;
14068
14069 if (CurContext->getRedeclContext()->isRecord()) {
14070 /// In class scope, check if this is a duplicate, for better a diagnostic.
14071 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
14072 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
14073 RedeclarationKind::ForVisibleRedeclaration);
14074
14075 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
14076
14077 for (NamedDecl *D : Previous)
14078 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
14079 if (UED->getEnumDecl() == ED) {
14080 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
14081 << SourceRange(EnumLoc, NameLoc);
14082 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
14083 Invalid = true;
14084 break;
14085 }
14086 }
14087
14088 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
14089 Invalid = true;
14090
14091 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
14092 EnumL: EnumLoc, NameL: NameLoc, EnumType);
14093 UD->setAccess(AS);
14094 CurContext->addDecl(D: UD);
14095
14096 if (Invalid) {
14097 UD->setInvalidDecl();
14098 return UD;
14099 }
14100
14101 // Create the shadow decls for each enumerator
14102 for (EnumConstantDecl *EC : ED->enumerators()) {
14103 UsingShadowDecl *PrevDecl = nullptr;
14104 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
14105 LookupResult Previous(*this, DNI, LookupOrdinaryName,
14106 RedeclarationKind::ForVisibleRedeclaration);
14107 LookupName(R&: Previous, S);
14108 FilterUsingLookup(S, Previous);
14109
14110 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
14111 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
14112 }
14113
14114 return UD;
14115}
14116
14117NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
14118 ArrayRef<NamedDecl *> Expansions) {
14119 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
14120 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
14121 isa<UsingPackDecl>(InstantiatedFrom));
14122
14123 auto *UPD =
14124 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
14125 UPD->setAccess(InstantiatedFrom->getAccess());
14126 CurContext->addDecl(D: UPD);
14127 return UPD;
14128}
14129
14130bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
14131 assert(!UD->hasTypename() && "expecting a constructor name");
14132
14133 QualType SourceType(UD->getQualifier().getAsType(), 0);
14134 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
14135
14136 // Check whether the named type is a direct base class.
14137 bool AnyDependentBases = false;
14138 auto *Base =
14139 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
14140 if (!Base && !AnyDependentBases) {
14141 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
14142 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
14143 UD->setInvalidDecl();
14144 return true;
14145 }
14146
14147 if (Base)
14148 Base->setInheritConstructors();
14149
14150 return false;
14151}
14152
14153bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
14154 bool HasTypenameKeyword,
14155 const CXXScopeSpec &SS,
14156 SourceLocation NameLoc,
14157 const LookupResult &Prev) {
14158 NestedNameSpecifier Qual = SS.getScopeRep();
14159
14160 // C++03 [namespace.udecl]p8:
14161 // C++0x [namespace.udecl]p10:
14162 // A using-declaration is a declaration and can therefore be used
14163 // repeatedly where (and only where) multiple declarations are
14164 // allowed.
14165 //
14166 // That's in non-member contexts.
14167 if (!CurContext->getRedeclContext()->isRecord()) {
14168 // A dependent qualifier outside a class can only ever resolve to an
14169 // enumeration type. Therefore it conflicts with any other non-type
14170 // declaration in the same scope.
14171 // FIXME: How should we check for dependent type-type conflicts at block
14172 // scope?
14173 if (Qual.isDependent() && !HasTypenameKeyword) {
14174 for (auto *D : Prev) {
14175 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
14176 bool OldCouldBeEnumerator =
14177 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
14178 Diag(Loc: NameLoc,
14179 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
14180 : diag::err_redefinition_different_kind)
14181 << Prev.getLookupName();
14182 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
14183 return true;
14184 }
14185 }
14186 }
14187 return false;
14188 }
14189
14190 NestedNameSpecifier CNNS = Qual.getCanonical();
14191 for (const NamedDecl *D : Prev) {
14192 bool DTypename;
14193 NestedNameSpecifier DQual = std::nullopt;
14194 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
14195 DTypename = UD->hasTypename();
14196 DQual = UD->getQualifier();
14197 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
14198 DTypename = false;
14199 DQual = UD->getQualifier();
14200 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
14201 DTypename = true;
14202 DQual = UD->getQualifier();
14203 } else
14204 continue;
14205
14206 // using decls differ if one says 'typename' and the other doesn't.
14207 // FIXME: non-dependent using decls?
14208 if (HasTypenameKeyword != DTypename) continue;
14209
14210 // using decls differ if they name different scopes (but note that
14211 // template instantiation can cause this check to trigger when it
14212 // didn't before instantiation).
14213 if (CNNS != DQual.getCanonical())
14214 continue;
14215
14216 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
14217 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
14218 return true;
14219 }
14220
14221 return false;
14222}
14223
14224bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
14225 const CXXScopeSpec &SS,
14226 const DeclarationNameInfo &NameInfo,
14227 SourceLocation NameLoc,
14228 const LookupResult *R, const UsingDecl *UD) {
14229 DeclContext *NamedContext = computeDeclContext(SS);
14230 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
14231 "resolvable context must have exactly one set of decls");
14232
14233 // C++ 20 permits using an enumerator that does not have a class-hierarchy
14234 // relationship.
14235 bool Cxx20Enumerator = false;
14236 if (NamedContext) {
14237 EnumConstantDecl *EC = nullptr;
14238 if (R)
14239 EC = R->getAsSingle<EnumConstantDecl>();
14240 else if (UD && UD->shadow_size() == 1)
14241 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
14242 if (EC)
14243 Cxx20Enumerator = getLangOpts().CPlusPlus20;
14244
14245 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
14246 // C++14 [namespace.udecl]p7:
14247 // A using-declaration shall not name a scoped enumerator.
14248 // C++20 p1099 permits enumerators.
14249 if (EC && R && ED->isScoped())
14250 DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::using_decl_scoped_enumerator)
14251 << SS.getRange();
14252
14253 // We want to consider the scope of the enumerator
14254 NamedContext = ED->getDeclContext();
14255 }
14256 }
14257
14258 if (!CurContext->isRecord()) {
14259 // C++03 [namespace.udecl]p3:
14260 // C++0x [namespace.udecl]p8:
14261 // A using-declaration for a class member shall be a member-declaration.
14262 // C++20 [namespace.udecl]p7
14263 // ... other than an enumerator ...
14264
14265 // If we weren't able to compute a valid scope, it might validly be a
14266 // dependent class or enumeration scope. If we have a 'typename' keyword,
14267 // the scope must resolve to a class type.
14268 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
14269 : !HasTypename)
14270 return false; // OK
14271
14272 Diag(Loc: NameLoc,
14273 DiagID: Cxx20Enumerator
14274 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
14275 : diag::err_using_decl_can_not_refer_to_class_member)
14276 << SS.getRange();
14277
14278 if (Cxx20Enumerator)
14279 return false; // OK
14280
14281 auto *RD = NamedContext
14282 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
14283 : nullptr;
14284 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
14285 // See if there's a helpful fixit
14286
14287 if (!R) {
14288 // We will have already diagnosed the problem on the template
14289 // definition, Maybe we should do so again?
14290 } else if (R->getAsSingle<TypeDecl>()) {
14291 if (getLangOpts().CPlusPlus11) {
14292 // Convert 'using X::Y;' to 'using Y = X::Y;'.
14293 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
14294 << diag::MemClassWorkaround::AliasDecl
14295 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
14296 Code: NameInfo.getName().getAsString() +
14297 " = ");
14298 } else {
14299 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
14300 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
14301 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
14302 << diag::MemClassWorkaround::TypedefDecl
14303 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
14304 << FixItHint::CreateInsertion(
14305 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
14306 }
14307 } else if (R->getAsSingle<VarDecl>()) {
14308 // Don't provide a fixit outside C++11 mode; we don't want to suggest
14309 // repeating the type of the static data member here.
14310 FixItHint FixIt;
14311 if (getLangOpts().CPlusPlus11) {
14312 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
14313 FixIt = FixItHint::CreateReplacement(
14314 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
14315 }
14316
14317 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
14318 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
14319 } else if (R->getAsSingle<EnumConstantDecl>()) {
14320 // Don't provide a fixit outside C++11 mode; we don't want to suggest
14321 // repeating the type of the enumeration here, and we can't do so if
14322 // the type is anonymous.
14323 FixItHint FixIt;
14324 if (getLangOpts().CPlusPlus11) {
14325 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
14326 FixIt = FixItHint::CreateReplacement(
14327 RemoveRange: UsingLoc,
14328 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
14329 }
14330
14331 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
14332 << (getLangOpts().CPlusPlus11
14333 ? diag::MemClassWorkaround::ConstexprVar
14334 : diag::MemClassWorkaround::ConstVar)
14335 << FixIt;
14336 }
14337 }
14338
14339 return true; // Fail
14340 }
14341
14342 // If the named context is dependent, we can't decide much.
14343 if (!NamedContext) {
14344 // FIXME: in C++0x, we can diagnose if we can prove that the
14345 // nested-name-specifier does not refer to a base class, which is
14346 // still possible in some cases.
14347
14348 // Otherwise we have to conservatively report that things might be
14349 // okay.
14350 return false;
14351 }
14352
14353 // The current scope is a record.
14354 if (!NamedContext->isRecord()) {
14355 // Ideally this would point at the last name in the specifier,
14356 // but we don't have that level of source info.
14357 Diag(Loc: SS.getBeginLoc(),
14358 DiagID: Cxx20Enumerator
14359 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
14360 : diag::err_using_decl_nested_name_specifier_is_not_class)
14361 << SS.getScopeRep() << SS.getRange();
14362
14363 if (Cxx20Enumerator)
14364 return false; // OK
14365
14366 return true;
14367 }
14368
14369 if (!NamedContext->isDependentContext() &&
14370 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
14371 return true;
14372
14373 // C++26 [namespace.udecl]p3:
14374 // In a using-declaration used as a member-declaration, each
14375 // using-declarator shall either name an enumerator or have a
14376 // nested-name-specifier naming a base class of the current class
14377 // ([expr.prim.this]). ...
14378 // "have a nested-name-specifier naming a base class of the current class"
14379 // was introduced by CWG400.
14380
14381 if (cast<CXXRecordDecl>(Val: CurContext)
14382 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
14383
14384 if (Cxx20Enumerator) {
14385 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
14386 << SS.getScopeRep() << SS.getRange();
14387 return false;
14388 }
14389
14390 if (CurContext == NamedContext) {
14391 Diag(Loc: SS.getBeginLoc(),
14392 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
14393 << SS.getRange();
14394 return true;
14395 }
14396
14397 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
14398 Diag(Loc: SS.getBeginLoc(),
14399 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
14400 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
14401 << SS.getRange();
14402 }
14403 return true;
14404 }
14405
14406 return false;
14407}
14408
14409Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
14410 MultiTemplateParamsArg TemplateParamLists,
14411 SourceLocation UsingLoc, UnqualifiedId &Name,
14412 const ParsedAttributesView &AttrList,
14413 TypeResult Type, Decl *DeclFromDeclSpec) {
14414
14415 if (Type.isInvalid())
14416 return nullptr;
14417
14418 bool Invalid = false;
14419 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
14420 TypeSourceInfo *TInfo = nullptr;
14421 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
14422
14423 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
14424 return nullptr;
14425
14426 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
14427 UPPC: UPPC_DeclarationType)) {
14428 Invalid = true;
14429 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
14430 Loc: TInfo->getTypeLoc().getBeginLoc());
14431 }
14432
14433 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
14434 TemplateParamLists.size()
14435 ? forRedeclarationInCurContext()
14436 : RedeclarationKind::ForVisibleRedeclaration);
14437 LookupName(R&: Previous, S);
14438
14439 // Warn about shadowing the name of a template parameter.
14440 if (Previous.isSingleResult() &&
14441 Previous.getFoundDecl()->isTemplateParameter()) {
14442 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
14443 Previous.clear();
14444 }
14445
14446 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
14447 "name in alias declaration must be an identifier");
14448 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
14449 IdLoc: Name.StartLocation,
14450 Id: Name.Identifier, TInfo);
14451
14452 NewTD->setAccess(AS);
14453
14454 if (Invalid)
14455 NewTD->setInvalidDecl();
14456
14457 ProcessDeclAttributeList(S, D: NewTD, AttrList);
14458 AddPragmaAttributes(S, D: NewTD);
14459 ProcessAPINotes(D: NewTD);
14460
14461 CheckTypedefForVariablyModifiedType(S, D: NewTD);
14462 Invalid |= NewTD->isInvalidDecl();
14463
14464 // Get the innermost enclosing declaration scope.
14465 S = S->getDeclParent();
14466
14467 bool Redeclaration = false;
14468
14469 NamedDecl *NewND;
14470 if (TemplateParamLists.size()) {
14471 TypeAliasTemplateDecl *OldDecl = nullptr;
14472 TemplateParameterList *OldTemplateParams = nullptr;
14473
14474 TemplateParameterList *TemplateParams = TemplateParamLists[0];
14475 if (TemplateParamLists.size() != 1) {
14476 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
14477 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
14478 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
14479 Invalid = true;
14480
14481 // Recover by picking the last non-empty template parameter list.
14482 auto It = llvm::find_if(
14483 Range: llvm::reverse(C&: TemplateParamLists),
14484 P: [](TemplateParameterList *TPL) { return !TPL->empty(); });
14485 assert(It != TemplateParamLists.rend() &&
14486 "if all template parameter lists were empty, this should have "
14487 "been rejected as an explicit specialization");
14488 TemplateParams = *It;
14489 }
14490
14491 // Check that we can declare a template here.
14492 if (CheckTemplateDeclScope(S, TemplateParams))
14493 return nullptr;
14494
14495 // Only consider previous declarations in the same scope.
14496 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14497 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
14498 if (!Previous.empty()) {
14499 Redeclaration = true;
14500
14501 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
14502 if (!OldDecl && !Invalid) {
14503 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
14504 << Name.Identifier;
14505
14506 NamedDecl *OldD = Previous.getRepresentativeDecl();
14507 if (OldD->getLocation().isValid())
14508 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
14509
14510 Invalid = true;
14511 }
14512
14513 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
14514 if (TemplateParameterListsAreEqual(New: TemplateParams,
14515 Old: OldDecl->getTemplateParameters(),
14516 /*Complain=*/true,
14517 Kind: TPL_TemplateMatch))
14518 OldTemplateParams =
14519 OldDecl->getMostRecentDecl()->getTemplateParameters();
14520 else
14521 Invalid = true;
14522
14523 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
14524 if (!Invalid &&
14525 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
14526 T2: NewTD->getUnderlyingType())) {
14527 // FIXME: The C++0x standard does not clearly say this is ill-formed,
14528 // but we can't reasonably accept it.
14529 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
14530 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
14531 if (OldTD->getLocation().isValid())
14532 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
14533 Invalid = true;
14534 }
14535 }
14536 }
14537
14538 // Merge any previous default template arguments into our parameters,
14539 // and check the parameter list.
14540 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
14541 TPC: TPC_Other))
14542 return nullptr;
14543
14544 TypeAliasTemplateDecl *NewDecl =
14545 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
14546 Name: Name.Identifier, Params: TemplateParams,
14547 Decl: NewTD);
14548 NewTD->setDescribedAliasTemplate(NewDecl);
14549
14550 NewDecl->setAccess(AS);
14551
14552 if (Invalid)
14553 NewDecl->setInvalidDecl();
14554 else if (OldDecl) {
14555 NewDecl->setPreviousDecl(OldDecl);
14556 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
14557 }
14558
14559 NewND = NewDecl;
14560 } else {
14561 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
14562 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
14563 handleTagNumbering(Tag: TD, TagScope: S);
14564 }
14565 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
14566 NewND = NewTD;
14567 }
14568
14569 PushOnScopeChains(D: NewND, S);
14570 ActOnDocumentableDecl(D: NewND);
14571 return NewND;
14572}
14573
14574Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
14575 SourceLocation AliasLoc,
14576 IdentifierInfo *Alias, CXXScopeSpec &SS,
14577 SourceLocation IdentLoc,
14578 IdentifierInfo *Ident) {
14579
14580 // Lookup the namespace name.
14581 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14582 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
14583
14584 if (R.isAmbiguous())
14585 return nullptr;
14586
14587 if (R.empty()) {
14588 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
14589 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
14590 return nullptr;
14591 }
14592 }
14593 assert(!R.isAmbiguous() && !R.empty());
14594 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
14595
14596 // Check if we have a previous declaration with the same name.
14597 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14598 RedeclarationKind::ForVisibleRedeclaration);
14599 LookupName(R&: PrevR, S);
14600
14601 // Check we're not shadowing a template parameter.
14602 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14603 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
14604 PrevR.clear();
14605 }
14606
14607 // Filter out any other lookup result from an enclosing scope.
14608 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14609 /*AllowInlineNamespace*/false);
14610
14611 // Find the previous declaration and check that we can redeclare it.
14612 NamespaceAliasDecl *Prev = nullptr;
14613 if (PrevR.isSingleResult()) {
14614 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14615 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14616 // We already have an alias with the same name that points to the same
14617 // namespace; check that it matches.
14618 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14619 Prev = AD;
14620 } else if (isVisible(D: PrevDecl)) {
14621 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14622 << Alias;
14623 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14624 << AD->getNamespace();
14625 return nullptr;
14626 }
14627 } else if (isVisible(D: PrevDecl)) {
14628 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14629 ? diag::err_redefinition
14630 : diag::err_redefinition_different_kind;
14631 Diag(Loc: AliasLoc, DiagID) << Alias;
14632 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14633 return nullptr;
14634 }
14635 }
14636
14637 // The use of a nested name specifier may trigger deprecation warnings.
14638 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14639
14640 NamespaceAliasDecl *AliasDecl =
14641 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14642 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14643 IdentLoc, Namespace: ND);
14644 if (Prev)
14645 AliasDecl->setPreviousDecl(Prev);
14646
14647 PushOnScopeChains(D: AliasDecl, S);
14648 return AliasDecl;
14649}
14650
14651namespace {
14652struct SpecialMemberExceptionSpecInfo
14653 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14654 SourceLocation Loc;
14655 Sema::ImplicitExceptionSpecification ExceptSpec;
14656
14657 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14658 CXXSpecialMemberKind CSM,
14659 Sema::InheritedConstructorInfo *ICI,
14660 SourceLocation Loc)
14661 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14662
14663 bool visitBase(CXXBaseSpecifier *Base);
14664 bool visitField(FieldDecl *FD);
14665
14666 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14667 unsigned Quals);
14668
14669 void visitSubobjectCall(Subobject Subobj,
14670 Sema::SpecialMemberOverloadResult SMOR);
14671};
14672}
14673
14674bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14675 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14676 if (!BaseClass)
14677 return false;
14678
14679 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14680 if (auto *BaseCtor = SMOR.getMethod()) {
14681 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14682 return false;
14683 }
14684
14685 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14686 return false;
14687}
14688
14689bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14690 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14691 FD->hasInClassInitializer()) {
14692 Expr *E = FD->getInClassInitializer();
14693 if (!E)
14694 // FIXME: It's a little wasteful to build and throw away a
14695 // CXXDefaultInitExpr here.
14696 // FIXME: We should have a single context note pointing at Loc, and
14697 // this location should be MD->getLocation() instead, since that's
14698 // the location where we actually use the default init expression.
14699 E = S.BuildCXXCtorDefaultInitExpr(Loc, Field: FD).get();
14700 if (E)
14701 ExceptSpec.CalledExpr(E);
14702 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14703 ->getAsCXXRecordDecl()) {
14704 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14705 }
14706 return false;
14707}
14708
14709void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14710 Subobject Subobj,
14711 unsigned Quals) {
14712 FieldDecl *Field = dyn_cast<FieldDecl *>(Val&: Subobj);
14713 bool IsMutable = Field && Field->isMutable();
14714 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14715}
14716
14717void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14718 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14719 // Note, if lookup fails, it doesn't matter what exception specification we
14720 // choose because the special member will be deleted.
14721 if (CXXMethodDecl *MD = SMOR.getMethod())
14722 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14723}
14724
14725bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14726 llvm::APSInt Result;
14727 ExprResult Converted = CheckConvertedConstantExpression(
14728 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14729 ExplicitSpec.setExpr(Converted.get());
14730 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14731 ExplicitSpec.setKind(Result.getBoolValue()
14732 ? ExplicitSpecKind::ResolvedTrue
14733 : ExplicitSpecKind::ResolvedFalse);
14734 return true;
14735 }
14736 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14737 return false;
14738}
14739
14740ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14741 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14742 if (!ExplicitExpr->isTypeDependent() && !ExplicitExpr->containsErrors())
14743 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14744 return ES;
14745}
14746
14747static Sema::ImplicitExceptionSpecification
14748ComputeDefaultedSpecialMemberExceptionSpec(
14749 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14750 Sema::InheritedConstructorInfo *ICI) {
14751 ComputingExceptionSpec CES(S, MD, Loc);
14752
14753 CXXRecordDecl *ClassDecl = MD->getParent();
14754
14755 // C++ [except.spec]p14:
14756 // An implicitly declared special member function (Clause 12) shall have an
14757 // exception-specification. [...]
14758 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14759 if (ClassDecl->isInvalidDecl())
14760 return Info.ExceptSpec;
14761
14762 // FIXME: If this diagnostic fires, we're probably missing a check for
14763 // attempting to resolve an exception specification before it's known
14764 // at a higher level.
14765 if (S.RequireCompleteType(Loc: MD->getLocation(),
14766 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14767 DiagID: diag::err_exception_spec_incomplete_type))
14768 return Info.ExceptSpec;
14769
14770 // C++1z [except.spec]p7:
14771 // [Look for exceptions thrown by] a constructor selected [...] to
14772 // initialize a potentially constructed subobject,
14773 // C++1z [except.spec]p8:
14774 // The exception specification for an implicitly-declared destructor, or a
14775 // destructor without a noexcept-specifier, is potentially-throwing if and
14776 // only if any of the destructors for any of its potentially constructed
14777 // subojects is potentially throwing.
14778 // FIXME: We respect the first rule but ignore the "potentially constructed"
14779 // in the second rule to resolve a core issue (no number yet) that would have
14780 // us reject:
14781 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14782 // struct B : A {};
14783 // struct C : B { void f(); };
14784 // ... due to giving B::~B() a non-throwing exception specification.
14785 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14786 : Info.VisitAllBases);
14787
14788 return Info.ExceptSpec;
14789}
14790
14791namespace {
14792/// RAII object to register a special member as being currently declared.
14793struct DeclaringSpecialMember {
14794 Sema &S;
14795 Sema::SpecialMemberDecl D;
14796 Sema::ContextRAII SavedContext;
14797 bool WasAlreadyBeingDeclared;
14798
14799 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14800 : S(S), D(RD, CSM), SavedContext(S, RD) {
14801 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14802 if (WasAlreadyBeingDeclared)
14803 // This almost never happens, but if it does, ensure that our cache
14804 // doesn't contain a stale result.
14805 S.SpecialMemberCache.clear();
14806 else {
14807 // Register a note to be produced if we encounter an error while
14808 // declaring the special member.
14809 Sema::CodeSynthesisContext Ctx;
14810 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14811 // FIXME: We don't have a location to use here. Using the class's
14812 // location maintains the fiction that we declare all special members
14813 // with the class, but (1) it's not clear that lying about that helps our
14814 // users understand what's going on, and (2) there may be outer contexts
14815 // on the stack (some of which are relevant) and printing them exposes
14816 // our lies.
14817 Ctx.PointOfInstantiation = RD->getLocation();
14818 Ctx.Entity = RD;
14819 Ctx.SpecialMember = CSM;
14820 S.pushCodeSynthesisContext(Ctx);
14821 }
14822 }
14823 ~DeclaringSpecialMember() {
14824 if (!WasAlreadyBeingDeclared) {
14825 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14826 S.popCodeSynthesisContext();
14827 }
14828 }
14829
14830 /// Are we already trying to declare this special member?
14831 bool isAlreadyBeingDeclared() const {
14832 return WasAlreadyBeingDeclared;
14833 }
14834};
14835}
14836
14837void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14838 // Look up any existing declarations, but don't trigger declaration of all
14839 // implicit special members with this name.
14840 DeclarationName Name = FD->getDeclName();
14841 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14842 RedeclarationKind::ForExternalRedeclaration);
14843 for (auto *D : FD->getParent()->lookup(Name))
14844 if (auto *Acceptable = R.getAcceptableDecl(D))
14845 R.addDecl(D: Acceptable);
14846 R.resolveKind();
14847 R.suppressDiagnostics();
14848
14849 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14850 DeclIsDefn: FD->isThisDeclarationADefinition());
14851}
14852
14853void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14854 QualType ResultTy,
14855 ArrayRef<QualType> Args) {
14856 // Build an exception specification pointing back at this constructor.
14857 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14858
14859 LangAS AS = getDefaultCXXMethodAddrSpace();
14860 if (AS != LangAS::Default) {
14861 EPI.TypeQuals.addAddressSpace(space: AS);
14862 }
14863
14864 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14865 SpecialMem->setType(QT);
14866
14867 // During template instantiation of implicit special member functions we need
14868 // a reliable TypeSourceInfo for the function prototype in order to allow
14869 // functions to be substituted.
14870 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14871 TypeSourceInfo *TSI =
14872 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14873 SpecialMem->setTypeSourceInfo(TSI);
14874 }
14875}
14876
14877CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14878 CXXRecordDecl *ClassDecl) {
14879 // C++ [class.ctor]p5:
14880 // A default constructor for a class X is a constructor of class X
14881 // that can be called without an argument. If there is no
14882 // user-declared constructor for class X, a default constructor is
14883 // implicitly declared. An implicitly-declared default constructor
14884 // is an inline public member of its class.
14885 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14886 "Should not build implicit default constructor!");
14887
14888 DeclaringSpecialMember DSM(*this, ClassDecl,
14889 CXXSpecialMemberKind::DefaultConstructor);
14890 if (DSM.isAlreadyBeingDeclared())
14891 return nullptr;
14892
14893 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14894 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14895
14896 // Create the actual constructor declaration.
14897 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14898 SourceLocation ClassLoc = ClassDecl->getLocation();
14899 DeclarationName Name
14900 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14901 DeclarationNameInfo NameInfo(Name, ClassLoc);
14902 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14903 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14904 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14905 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14906 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14907 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14908 : ConstexprSpecKind::Unspecified);
14909 DefaultCon->setAccess(AS_public);
14910 DefaultCon->setDefaulted();
14911
14912 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14913
14914 if (getLangOpts().CUDA)
14915 CUDA().inferTargetForImplicitSpecialMember(
14916 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14917 /* ConstRHS */ false,
14918 /* Diagnose */ false);
14919
14920 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14921 // constructors is easy to compute.
14922 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14923
14924 // Note that we have declared this constructor.
14925 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14926
14927 Scope *S = getScopeForContext(Ctx: ClassDecl);
14928 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14929
14930 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14931 CSM: CXXSpecialMemberKind::DefaultConstructor))
14932 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14933
14934 if (S)
14935 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14936 ClassDecl->addDecl(D: DefaultCon);
14937
14938 return DefaultCon;
14939}
14940
14941void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14942 CXXConstructorDecl *Constructor) {
14943 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14944 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14945 !Constructor->doesThisDeclarationHaveABody() &&
14946 !Constructor->isDeleted()) &&
14947 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14948 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14949 return;
14950
14951 CXXRecordDecl *ClassDecl = Constructor->getParent();
14952 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14953 if (ClassDecl->isInvalidDecl()) {
14954 return;
14955 }
14956
14957 SynthesizedFunctionScope Scope(*this, Constructor);
14958
14959 // The exception specification is needed because we are defining the
14960 // function.
14961 ResolveExceptionSpec(Loc: CurrentLocation,
14962 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14963 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14964
14965 // Add a context note for diagnostics produced after this point.
14966 Scope.addContextNote(UseLoc: CurrentLocation);
14967
14968 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14969 Constructor->setInvalidDecl();
14970 return;
14971 }
14972
14973 SourceLocation Loc = Constructor->getEndLoc().isValid()
14974 ? Constructor->getEndLoc()
14975 : Constructor->getLocation();
14976 Constructor->setBody(new (Context) CompoundStmt(Loc));
14977 Constructor->markUsed(C&: Context);
14978
14979 if (ASTMutationListener *L = getASTMutationListener()) {
14980 L->CompletedImplicitDefinition(D: Constructor);
14981 }
14982
14983 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14984
14985 // The synthesized body applies the class's NSDMIs and never reaches the
14986 // normal IssueWarnings path, so run lifetime safety on it here.
14987 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14988}
14989
14990void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14991 // Perform any delayed checks on exception specifications.
14992 CheckDelayedMemberExceptionSpecs();
14993}
14994
14995/// Find or create the fake constructor we synthesize to model constructing an
14996/// object of a derived class via a constructor of a base class.
14997CXXConstructorDecl *
14998Sema::findInheritingConstructor(SourceLocation Loc,
14999 CXXConstructorDecl *BaseCtor,
15000 ConstructorUsingShadowDecl *Shadow) {
15001 CXXRecordDecl *Derived = Shadow->getParent();
15002 SourceLocation UsingLoc = Shadow->getLocation();
15003
15004 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
15005 // For now we use the name of the base class constructor as a member of the
15006 // derived class to indicate a (fake) inherited constructor name.
15007 DeclarationName Name = BaseCtor->getDeclName();
15008
15009 // Check to see if we already have a fake constructor for this inherited
15010 // constructor call.
15011 for (NamedDecl *Ctor : Derived->lookup(Name))
15012 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
15013 ->getInheritedConstructor()
15014 .getConstructor(),
15015 D2: BaseCtor))
15016 return cast<CXXConstructorDecl>(Val: Ctor);
15017
15018 DeclarationNameInfo NameInfo(Name, UsingLoc);
15019 TypeSourceInfo *TInfo =
15020 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
15021 FunctionProtoTypeLoc ProtoLoc =
15022 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
15023
15024 // Check the inherited constructor is valid and find the list of base classes
15025 // from which it was inherited.
15026 InheritedConstructorInfo ICI(*this, Loc, Shadow);
15027
15028 bool Constexpr = BaseCtor->isConstexpr() &&
15029 defaultedSpecialMemberIsConstexpr(
15030 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
15031 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
15032
15033 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
15034 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
15035 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15036 /*isInline=*/true,
15037 /*isImplicitlyDeclared=*/true,
15038 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
15039 Inherited: InheritedConstructor(Shadow, BaseCtor),
15040 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
15041 if (Shadow->isInvalidDecl())
15042 DerivedCtor->setInvalidDecl();
15043
15044 // Build an unevaluated exception specification for this fake constructor.
15045 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
15046 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
15047 EPI.ExceptionSpec.Type = EST_Unevaluated;
15048 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
15049 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
15050 Args: FPT->getParamTypes(), EPI));
15051
15052 // Build the parameter declarations.
15053 SmallVector<ParmVarDecl *, 16> ParamDecls;
15054 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
15055 TypeSourceInfo *TInfo =
15056 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
15057 ParmVarDecl *PD = ParmVarDecl::Create(
15058 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
15059 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
15060 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
15061 PD->setImplicit();
15062 // Ensure attributes are propagated onto parameters (this matters for
15063 // format, pass_object_size, ...).
15064 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
15065 ParamDecls.push_back(Elt: PD);
15066 ProtoLoc.setParam(i: I, VD: PD);
15067 }
15068
15069 // Set up the new constructor.
15070 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
15071 DerivedCtor->setAccess(BaseCtor->getAccess());
15072 DerivedCtor->setParams(ParamDecls);
15073 Derived->addDecl(D: DerivedCtor);
15074
15075 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
15076 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
15077 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
15078
15079 return DerivedCtor;
15080}
15081
15082void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
15083 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
15084 Ctor->getInheritedConstructor().getShadowDecl());
15085 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
15086 ICI: &ICI,
15087 /*Diagnose*/ true);
15088}
15089
15090void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
15091 CXXConstructorDecl *Constructor) {
15092 CXXRecordDecl *ClassDecl = Constructor->getParent();
15093 assert(Constructor->getInheritedConstructor() &&
15094 !Constructor->doesThisDeclarationHaveABody() &&
15095 !Constructor->isDeleted());
15096 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
15097 return;
15098
15099 // Initializations are performed "as if by a defaulted default constructor",
15100 // so enter the appropriate scope.
15101 SynthesizedFunctionScope Scope(*this, Constructor);
15102
15103 // The exception specification is needed because we are defining the
15104 // function.
15105 ResolveExceptionSpec(Loc: CurrentLocation,
15106 FPT: Constructor->getType()->castAs<FunctionProtoType>());
15107 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
15108
15109 // Add a context note for diagnostics produced after this point.
15110 Scope.addContextNote(UseLoc: CurrentLocation);
15111
15112 ConstructorUsingShadowDecl *Shadow =
15113 Constructor->getInheritedConstructor().getShadowDecl();
15114 CXXConstructorDecl *InheritedCtor =
15115 Constructor->getInheritedConstructor().getConstructor();
15116
15117 // [class.inhctor.init]p1:
15118 // initialization proceeds as if a defaulted default constructor is used to
15119 // initialize the D object and each base class subobject from which the
15120 // constructor was inherited
15121
15122 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
15123 CXXRecordDecl *RD = Shadow->getParent();
15124 SourceLocation InitLoc = Shadow->getLocation();
15125
15126 // Build explicit initializers for all base classes from which the
15127 // constructor was inherited.
15128 SmallVector<CXXCtorInitializer*, 8> Inits;
15129 for (bool VBase : {false, true}) {
15130 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
15131 if (B.isVirtual() != VBase)
15132 continue;
15133
15134 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
15135 if (!BaseRD)
15136 continue;
15137
15138 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
15139 if (!BaseCtor.first)
15140 continue;
15141
15142 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
15143 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
15144 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
15145
15146 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
15147 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
15148 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
15149 SourceLocation()));
15150 }
15151 }
15152
15153 // We now proceed as if for a defaulted default constructor, with the relevant
15154 // initializers replaced.
15155
15156 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
15157 Constructor->setInvalidDecl();
15158 return;
15159 }
15160
15161 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
15162 Constructor->markUsed(C&: Context);
15163
15164 if (ASTMutationListener *L = getASTMutationListener()) {
15165 L->CompletedImplicitDefinition(D: Constructor);
15166 }
15167
15168 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
15169
15170 // The synthesized body applies the class's NSDMIs and never reaches the
15171 // normal IssueWarnings path, so run lifetime safety on it here.
15172 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
15173}
15174
15175CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
15176 // C++ [class.dtor]p2:
15177 // If a class has no user-declared destructor, a destructor is
15178 // declared implicitly. An implicitly-declared destructor is an
15179 // inline public member of its class.
15180 assert(ClassDecl->needsImplicitDestructor());
15181
15182 DeclaringSpecialMember DSM(*this, ClassDecl,
15183 CXXSpecialMemberKind::Destructor);
15184 if (DSM.isAlreadyBeingDeclared())
15185 return nullptr;
15186
15187 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15188 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
15189
15190 // Create the actual destructor declaration.
15191 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
15192 SourceLocation ClassLoc = ClassDecl->getLocation();
15193 DeclarationName Name
15194 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
15195 DeclarationNameInfo NameInfo(Name, ClassLoc);
15196 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
15197 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
15198 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15199 /*isInline=*/true,
15200 /*isImplicitlyDeclared=*/true,
15201 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15202 : ConstexprSpecKind::Unspecified);
15203 Destructor->setAccess(AS_public);
15204 Destructor->setDefaulted();
15205
15206 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
15207
15208 if (getLangOpts().CUDA)
15209 CUDA().inferTargetForImplicitSpecialMember(
15210 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
15211 /* ConstRHS */ false,
15212 /* Diagnose */ false);
15213
15214 // We don't need to use SpecialMemberIsTrivial here; triviality for
15215 // destructors is easy to compute.
15216 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
15217 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
15218 ClassDecl->hasTrivialDestructorForCall());
15219
15220 // Note that we have declared this destructor.
15221 ++getASTContext().NumImplicitDestructorsDeclared;
15222
15223 Scope *S = getScopeForContext(Ctx: ClassDecl);
15224 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
15225
15226 // We can't check whether an implicit destructor is deleted before we complete
15227 // the definition of the class, because its validity depends on the alignment
15228 // of the class. We'll check this from ActOnFields once the class is complete.
15229 if (ClassDecl->isCompleteDefinition() &&
15230 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
15231 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
15232
15233 // Introduce this destructor into its scope.
15234 if (S)
15235 PushOnScopeChains(D: Destructor, S, AddToContext: false);
15236 ClassDecl->addDecl(D: Destructor);
15237
15238 return Destructor;
15239}
15240
15241void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
15242 CXXDestructorDecl *Destructor) {
15243 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
15244 assert((Destructor->isDefaulted() &&
15245 !Destructor->doesThisDeclarationHaveABody() &&
15246 !Destructor->isDeleted()) &&
15247 "DefineImplicitDestructor - call it for implicit default dtor");
15248 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
15249 return;
15250
15251 CXXRecordDecl *ClassDecl = Destructor->getParent();
15252 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
15253
15254 SynthesizedFunctionScope Scope(*this, Destructor);
15255
15256 // The exception specification is needed because we are defining the
15257 // function.
15258 ResolveExceptionSpec(Loc: CurrentLocation,
15259 FPT: Destructor->getType()->castAs<FunctionProtoType>());
15260 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
15261
15262 // Add a context note for diagnostics produced after this point.
15263 Scope.addContextNote(UseLoc: CurrentLocation);
15264
15265 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
15266 ClassDecl: Destructor->getParent());
15267
15268 if (CheckDestructor(Destructor)) {
15269 Destructor->setInvalidDecl();
15270 return;
15271 }
15272
15273 SourceLocation Loc = Destructor->getEndLoc().isValid()
15274 ? Destructor->getEndLoc()
15275 : Destructor->getLocation();
15276 Destructor->setBody(new (Context) CompoundStmt(Loc));
15277 Destructor->markUsed(C&: Context);
15278
15279 if (ASTMutationListener *L = getASTMutationListener()) {
15280 L->CompletedImplicitDefinition(D: Destructor);
15281 }
15282}
15283
15284void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
15285 CXXDestructorDecl *Destructor) {
15286 if (Destructor->isInvalidDecl())
15287 return;
15288
15289 CXXRecordDecl *ClassDecl = Destructor->getParent();
15290 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
15291 "implicit complete dtors unneeded outside MS ABI");
15292 assert(ClassDecl->getNumVBases() > 0 &&
15293 "complete dtor only exists for classes with vbases");
15294
15295 SynthesizedFunctionScope Scope(*this, Destructor);
15296
15297 // Add a context note for diagnostics produced after this point.
15298 Scope.addContextNote(UseLoc: CurrentLocation);
15299
15300 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
15301}
15302
15303void Sema::ActOnFinishCXXMemberDecls() {
15304 // If the context is an invalid C++ class, just suppress these checks.
15305 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
15306 if (Record->isInvalidDecl()) {
15307 DelayedOverridingExceptionSpecChecks.clear();
15308 DelayedEquivalentExceptionSpecChecks.clear();
15309 return;
15310 }
15311 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
15312 }
15313}
15314
15315void Sema::ActOnFinishCXXNonNestedClass() {
15316 referenceDLLExportedClassMethods();
15317
15318 if (!DelayedDllExportMemberFunctions.empty()) {
15319 SmallVector<CXXMethodDecl*, 4> WorkList;
15320 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
15321 for (CXXMethodDecl *M : WorkList) {
15322 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
15323
15324 // Pass the method to the consumer to get emitted. This is not necessary
15325 // for explicit instantiation definitions, as they will get emitted
15326 // anyway.
15327 if (M->getParent()->getTemplateSpecializationKind() !=
15328 TSK_ExplicitInstantiationDefinition)
15329 ActOnFinishInlineFunctionDef(D: M);
15330 }
15331 }
15332}
15333
15334void Sema::referenceDLLExportedClassMethods() {
15335 if (!DelayedDllExportClasses.empty()) {
15336 // Calling ReferenceDllExportedMembers might cause the current function to
15337 // be called again, so use a local copy of DelayedDllExportClasses.
15338 SmallVector<CXXRecordDecl *, 4> WorkList;
15339 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
15340 for (CXXRecordDecl *Class : WorkList)
15341 ReferenceDllExportedMembers(S&: *this, Class);
15342 }
15343}
15344
15345void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
15346 assert(getLangOpts().CPlusPlus11 &&
15347 "adjusting dtor exception specs was introduced in c++11");
15348
15349 if (Destructor->isDependentContext())
15350 return;
15351
15352 // C++11 [class.dtor]p3:
15353 // A declaration of a destructor that does not have an exception-
15354 // specification is implicitly considered to have the same exception-
15355 // specification as an implicit declaration.
15356 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
15357 if (DtorType->hasExceptionSpec())
15358 return;
15359
15360 // Replace the destructor's type, building off the existing one. Fortunately,
15361 // the only thing of interest in the destructor type is its extended info.
15362 // The return and arguments are fixed.
15363 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
15364 EPI.ExceptionSpec.Type = EST_Unevaluated;
15365 EPI.ExceptionSpec.SourceDecl = Destructor;
15366 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
15367
15368 // FIXME: If the destructor has a body that could throw, and the newly created
15369 // spec doesn't allow exceptions, we should emit a warning, because this
15370 // change in behavior can break conforming C++03 programs at runtime.
15371 // However, we don't have a body or an exception specification yet, so it
15372 // needs to be done somewhere else.
15373}
15374
15375namespace {
15376/// An abstract base class for all helper classes used in building the
15377// copy/move operators. These classes serve as factory functions and help us
15378// avoid using the same Expr* in the AST twice.
15379class ExprBuilder {
15380 ExprBuilder(const ExprBuilder&) = delete;
15381 ExprBuilder &operator=(const ExprBuilder&) = delete;
15382
15383protected:
15384 static Expr *assertNotNull(Expr *E) {
15385 assert(E && "Expression construction must not fail.");
15386 return E;
15387 }
15388
15389public:
15390 ExprBuilder() {}
15391 virtual ~ExprBuilder() {}
15392
15393 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
15394};
15395
15396class RefBuilder: public ExprBuilder {
15397 VarDecl *Var;
15398 QualType VarType;
15399
15400public:
15401 Expr *build(Sema &S, SourceLocation Loc) const override {
15402 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
15403 }
15404
15405 RefBuilder(VarDecl *Var, QualType VarType)
15406 : Var(Var), VarType(VarType) {}
15407};
15408
15409class ThisBuilder: public ExprBuilder {
15410public:
15411 Expr *build(Sema &S, SourceLocation Loc) const override {
15412 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
15413 }
15414};
15415
15416class CastBuilder: public ExprBuilder {
15417 const ExprBuilder &Builder;
15418 QualType Type;
15419 ExprValueKind Kind;
15420 const CXXCastPath &Path;
15421
15422public:
15423 Expr *build(Sema &S, SourceLocation Loc) const override {
15424 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
15425 CK: CK_UncheckedDerivedToBase, VK: Kind,
15426 BasePath: &Path).get());
15427 }
15428
15429 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
15430 const CXXCastPath &Path)
15431 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
15432};
15433
15434class DerefBuilder: public ExprBuilder {
15435 const ExprBuilder &Builder;
15436
15437public:
15438 Expr *build(Sema &S, SourceLocation Loc) const override {
15439 return assertNotNull(
15440 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
15441 }
15442
15443 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
15444};
15445
15446class MemberBuilder: public ExprBuilder {
15447 const ExprBuilder &Builder;
15448 QualType Type;
15449 CXXScopeSpec SS;
15450 bool IsArrow;
15451 LookupResult &MemberLookup;
15452
15453public:
15454 Expr *build(Sema &S, SourceLocation Loc) const override {
15455 return assertNotNull(E: S.BuildMemberReferenceExpr(
15456 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
15457 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
15458 }
15459
15460 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
15461 LookupResult &MemberLookup)
15462 : Builder(Builder), Type(Type), IsArrow(IsArrow),
15463 MemberLookup(MemberLookup) {}
15464};
15465
15466class MoveCastBuilder: public ExprBuilder {
15467 const ExprBuilder &Builder;
15468
15469public:
15470 Expr *build(Sema &S, SourceLocation Loc) const override {
15471 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
15472 }
15473
15474 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
15475};
15476
15477class LvalueConvBuilder: public ExprBuilder {
15478 const ExprBuilder &Builder;
15479
15480public:
15481 Expr *build(Sema &S, SourceLocation Loc) const override {
15482 return assertNotNull(
15483 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
15484 }
15485
15486 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
15487};
15488
15489class SubscriptBuilder: public ExprBuilder {
15490 const ExprBuilder &Base;
15491 const ExprBuilder &Index;
15492
15493public:
15494 Expr *build(Sema &S, SourceLocation Loc) const override {
15495 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
15496 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
15497 }
15498
15499 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
15500 : Base(Base), Index(Index) {}
15501};
15502
15503} // end anonymous namespace
15504
15505/// When generating a defaulted copy or move assignment operator, if a field
15506/// should be copied with __builtin_memcpy rather than via explicit assignments,
15507/// do so. This optimization only applies for arrays of scalars, and for arrays
15508/// of class type where the selected copy/move-assignment operator is trivial.
15509static StmtResult
15510buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
15511 const ExprBuilder &ToB, const ExprBuilder &FromB) {
15512 // Compute the size of the memory buffer to be copied.
15513 QualType SizeType = S.Context.getSizeType();
15514 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
15515 S.Context.getTypeSizeInChars(T).getQuantity());
15516
15517 // Take the address of the field references for "from" and "to". We
15518 // directly construct UnaryOperators here because semantic analysis
15519 // does not permit us to take the address of an xvalue.
15520 Expr *From = FromB.build(S, Loc);
15521 From = UnaryOperator::Create(
15522 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
15523 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
15524 Expr *To = ToB.build(S, Loc);
15525 To = UnaryOperator::Create(
15526 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
15527 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
15528
15529 bool NeedsCollectableMemCpy = false;
15530 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
15531 NeedsCollectableMemCpy = RD->hasObjectMember();
15532
15533 // Create a reference to the __builtin_objc_memmove_collectable function
15534 StringRef MemCpyName = NeedsCollectableMemCpy ?
15535 "__builtin_objc_memmove_collectable" :
15536 "__builtin_memcpy";
15537 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
15538 Sema::LookupOrdinaryName);
15539 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
15540
15541 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
15542 if (!MemCpy)
15543 // Something went horribly wrong earlier, and we will have complained
15544 // about it.
15545 return StmtError();
15546
15547 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
15548 VK: VK_PRValue, Loc, SS: nullptr);
15549 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
15550
15551 Expr *CallArgs[] = {
15552 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
15553 };
15554 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
15555 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
15556
15557 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15558 return Call.getAs<Stmt>();
15559}
15560
15561/// Builds a statement that copies/moves the given entity from \p From to
15562/// \c To.
15563///
15564/// This routine is used to copy/move the members of a class with an
15565/// implicitly-declared copy/move assignment operator. When the entities being
15566/// copied are arrays, this routine builds for loops to copy them.
15567///
15568/// \param S The Sema object used for type-checking.
15569///
15570/// \param Loc The location where the implicit copy/move is being generated.
15571///
15572/// \param T The type of the expressions being copied/moved. Both expressions
15573/// must have this type.
15574///
15575/// \param To The expression we are copying/moving to.
15576///
15577/// \param From The expression we are copying/moving from.
15578///
15579/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15580/// Otherwise, it's a non-static member subobject.
15581///
15582/// \param Copying Whether we're copying or moving.
15583///
15584/// \param Depth Internal parameter recording the depth of the recursion.
15585///
15586/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15587/// if a memcpy should be used instead.
15588static StmtResult
15589buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
15590 const ExprBuilder &To, const ExprBuilder &From,
15591 bool CopyingBaseSubobject, bool Copying,
15592 unsigned Depth = 0) {
15593 // C++11 [class.copy]p28:
15594 // Each subobject is assigned in the manner appropriate to its type:
15595 //
15596 // - if the subobject is of class type, as if by a call to operator= with
15597 // the subobject as the object expression and the corresponding
15598 // subobject of x as a single function argument (as if by explicit
15599 // qualification; that is, ignoring any possible virtual overriding
15600 // functions in more derived classes);
15601 //
15602 // C++03 [class.copy]p13:
15603 // - if the subobject is of class type, the copy assignment operator for
15604 // the class is used (as if by explicit qualification; that is,
15605 // ignoring any possible virtual overriding functions in more derived
15606 // classes);
15607 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15608 // Look for operator=.
15609 DeclarationName Name
15610 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15611 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15612 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
15613
15614 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15615 // operator.
15616 if (!S.getLangOpts().CPlusPlus11) {
15617 LookupResult::Filter F = OpLookup.makeFilter();
15618 while (F.hasNext()) {
15619 NamedDecl *D = F.next();
15620 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15621 if (Method->isCopyAssignmentOperator() ||
15622 (!Copying && Method->isMoveAssignmentOperator()))
15623 continue;
15624
15625 F.erase();
15626 }
15627 F.done();
15628 }
15629
15630 // Suppress the protected check (C++ [class.protected]) for each of the
15631 // assignment operators we found. This strange dance is required when
15632 // we're assigning via a base classes's copy-assignment operator. To
15633 // ensure that we're getting the right base class subobject (without
15634 // ambiguities), we need to cast "this" to that subobject type; to
15635 // ensure that we don't go through the virtual call mechanism, we need
15636 // to qualify the operator= name with the base class (see below). However,
15637 // this means that if the base class has a protected copy assignment
15638 // operator, the protected member access check will fail. So, we
15639 // rewrite "protected" access to "public" access in this case, since we
15640 // know by construction that we're calling from a derived class.
15641 if (CopyingBaseSubobject) {
15642 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15643 L != LEnd; ++L) {
15644 if (L.getAccess() == AS_protected)
15645 L.setAccess(AS_public);
15646 }
15647 }
15648
15649 // Create the nested-name-specifier that will be used to qualify the
15650 // reference to operator=; this is required to suppress the virtual
15651 // call mechanism.
15652 CXXScopeSpec SS;
15653 // FIXME: Don't canonicalize this.
15654 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15655 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15656
15657 // Create the reference to operator=.
15658 ExprResult OpEqualRef
15659 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15660 SS, /*TemplateKWLoc=*/SourceLocation(),
15661 /*FirstQualifierInScope=*/nullptr,
15662 R&: OpLookup,
15663 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15664 /*SuppressQualifierCheck=*/true);
15665 if (OpEqualRef.isInvalid())
15666 return StmtError();
15667
15668 // Build the call to the assignment operator.
15669
15670 Expr *FromInst = From.build(S, Loc);
15671 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15672 MemExpr: OpEqualRef.getAs<Expr>(),
15673 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15674 if (Call.isInvalid())
15675 return StmtError();
15676
15677 // If we built a call to a trivial 'operator=' while copying an array,
15678 // bail out. We'll replace the whole shebang with a memcpy.
15679 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15680 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15681 return StmtResult((Stmt*)nullptr);
15682
15683 // Convert to an expression-statement, and clean up any produced
15684 // temporaries.
15685 return S.ActOnExprStmt(Arg: Call);
15686 }
15687
15688 // - if the subobject is of scalar type, the built-in assignment
15689 // operator is used.
15690 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15691 if (!ArrayTy) {
15692 ExprResult Assignment = S.CreateBuiltinBinOp(
15693 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15694 if (Assignment.isInvalid())
15695 return StmtError();
15696 return S.ActOnExprStmt(Arg: Assignment);
15697 }
15698
15699 // - if the subobject is an array, each element is assigned, in the
15700 // manner appropriate to the element type;
15701
15702 // Construct a loop over the array bounds, e.g.,
15703 //
15704 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15705 //
15706 // that will copy each of the array elements.
15707 QualType SizeType = S.Context.getSizeType();
15708
15709 // Create the iteration variable.
15710 IdentifierInfo *IterationVarName = nullptr;
15711 {
15712 SmallString<8> Str;
15713 llvm::raw_svector_ostream OS(Str);
15714 OS << "__i" << Depth;
15715 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15716 }
15717 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15718 Id: IterationVarName, T: SizeType,
15719 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15720 S: SC_None);
15721
15722 // Initialize the iteration variable to zero.
15723 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15724 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15725
15726 // Creates a reference to the iteration variable.
15727 RefBuilder IterationVarRef(IterationVar, SizeType);
15728 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15729
15730 // Create the DeclStmt that holds the iteration variable.
15731 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15732
15733 // Subscript the "from" and "to" expressions with the iteration variable.
15734 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15735 MoveCastBuilder FromIndexMove(FromIndexCopy);
15736 const ExprBuilder *FromIndex;
15737 if (Copying)
15738 FromIndex = &FromIndexCopy;
15739 else
15740 FromIndex = &FromIndexMove;
15741
15742 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15743
15744 // Build the copy/move for an individual element of the array.
15745 StmtResult Copy =
15746 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15747 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15748 Copying, Depth: Depth + 1);
15749 // Bail out if copying fails or if we determined that we should use memcpy.
15750 if (Copy.isInvalid() || !Copy.get())
15751 return Copy;
15752
15753 // Create the comparison against the array bound.
15754 llvm::APInt Upper
15755 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15756 Expr *Comparison = BinaryOperator::Create(
15757 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15758 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15759 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15760 FPFeatures: S.CurFPFeatureOverrides());
15761
15762 // Create the pre-increment of the iteration variable. We can determine
15763 // whether the increment will overflow based on the value of the array
15764 // bound.
15765 Expr *Increment = UnaryOperator::Create(
15766 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15767 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15768
15769 // Construct the loop that copies all elements of this array.
15770 return S.ActOnForStmt(
15771 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15772 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15773 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15774}
15775
15776static StmtResult
15777buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15778 const ExprBuilder &To, const ExprBuilder &From,
15779 bool CopyingBaseSubobject, bool Copying) {
15780 // Maybe we should use a memcpy?
15781 if (T->isArrayType() && !T.hasQualifiers() &&
15782 T.isTriviallyCopyableType(Context: S.Context))
15783 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15784
15785 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15786 CopyingBaseSubobject,
15787 Copying, Depth: 0));
15788
15789 // If we ended up picking a trivial assignment operator for an array of a
15790 // non-trivially-copyable class type, just emit a memcpy.
15791 if (!Result.isInvalid() && !Result.get())
15792 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15793
15794 return Result;
15795}
15796
15797CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15798 // Note: The following rules are largely analoguous to the copy
15799 // constructor rules. Note that virtual bases are not taken into account
15800 // for determining the argument type of the operator. Note also that
15801 // operators taking an object instead of a reference are allowed.
15802 assert(ClassDecl->needsImplicitCopyAssignment());
15803
15804 DeclaringSpecialMember DSM(*this, ClassDecl,
15805 CXXSpecialMemberKind::CopyAssignment);
15806 if (DSM.isAlreadyBeingDeclared())
15807 return nullptr;
15808
15809 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15810 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15811 /*OwnsTag=*/false);
15812 LangAS AS = getDefaultCXXMethodAddrSpace();
15813 if (AS != LangAS::Default)
15814 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15815 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15816 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15817 if (Const)
15818 ArgType = ArgType.withConst();
15819
15820 ArgType = Context.getLValueReferenceType(T: ArgType);
15821
15822 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15823 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15824
15825 // An implicitly-declared copy assignment operator is an inline public
15826 // member of its class.
15827 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15828 SourceLocation ClassLoc = ClassDecl->getLocation();
15829 DeclarationNameInfo NameInfo(Name, ClassLoc);
15830 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15831 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15832 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15833 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15834 /*isInline=*/true,
15835 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15836 EndLocation: SourceLocation());
15837 CopyAssignment->setAccess(AS_public);
15838 CopyAssignment->setDefaulted();
15839 CopyAssignment->setImplicit();
15840
15841 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15842
15843 if (getLangOpts().CUDA)
15844 CUDA().inferTargetForImplicitSpecialMember(
15845 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15846 /* ConstRHS */ Const,
15847 /* Diagnose */ false);
15848
15849 // Add the parameter to the operator.
15850 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15851 StartLoc: ClassLoc, IdLoc: ClassLoc,
15852 /*Id=*/nullptr, T: ArgType,
15853 /*TInfo=*/nullptr, S: SC_None,
15854 DefArg: nullptr);
15855 CopyAssignment->setParams(FromParam);
15856
15857 CopyAssignment->setTrivial(
15858 ClassDecl->needsOverloadResolutionForCopyAssignment()
15859 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15860 CSM: CXXSpecialMemberKind::CopyAssignment)
15861 : ClassDecl->hasTrivialCopyAssignment());
15862
15863 // Note that we have added this copy-assignment operator.
15864 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15865
15866 Scope *S = getScopeForContext(Ctx: ClassDecl);
15867 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15868
15869 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15870 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15871 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15872 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15873 }
15874
15875 if (S)
15876 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15877 ClassDecl->addDecl(D: CopyAssignment);
15878
15879 return CopyAssignment;
15880}
15881
15882/// Diagnose an implicit copy operation for a class which is odr-used, but
15883/// which is deprecated because the class has a user-declared copy constructor,
15884/// copy assignment operator, or destructor.
15885static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15886 assert(CopyOp->isImplicit());
15887
15888 CXXRecordDecl *RD = CopyOp->getParent();
15889 CXXMethodDecl *UserDeclaredOperation = nullptr;
15890
15891 if (RD->hasUserDeclaredDestructor()) {
15892 UserDeclaredOperation = RD->getDestructor();
15893 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15894 RD->hasUserDeclaredCopyConstructor()) {
15895 // Find any user-declared copy constructor.
15896 for (auto *I : RD->ctors()) {
15897 if (I->isCopyConstructor()) {
15898 UserDeclaredOperation = I;
15899 break;
15900 }
15901 }
15902 assert(UserDeclaredOperation);
15903 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15904 RD->hasUserDeclaredCopyAssignment()) {
15905 // Find any user-declared move assignment operator.
15906 for (auto *I : RD->methods()) {
15907 if (I->isCopyAssignmentOperator()) {
15908 UserDeclaredOperation = I;
15909 break;
15910 }
15911 }
15912 assert(UserDeclaredOperation);
15913 }
15914
15915 if (UserDeclaredOperation) {
15916 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15917 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15918 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15919 unsigned DiagID =
15920 (UDOIsUserProvided && UDOIsDestructor)
15921 ? diag::warn_deprecated_copy_with_user_provided_dtor
15922 : (UDOIsUserProvided && !UDOIsDestructor)
15923 ? diag::warn_deprecated_copy_with_user_provided_copy
15924 : (!UDOIsUserProvided && UDOIsDestructor)
15925 ? diag::warn_deprecated_copy_with_dtor
15926 : diag::warn_deprecated_copy;
15927 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15928 << RD << IsCopyAssignment;
15929 }
15930}
15931
15932void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15933 CXXMethodDecl *CopyAssignOperator) {
15934 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15935 assert((CopyAssignOperator->isDefaulted() &&
15936 CopyAssignOperator->isOverloadedOperator() &&
15937 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15938 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15939 !CopyAssignOperator->isDeleted()) &&
15940 "DefineImplicitCopyAssignment called for wrong function");
15941 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15942 return;
15943
15944 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15945 if (ClassDecl->isInvalidDecl()) {
15946 CopyAssignOperator->setInvalidDecl();
15947 return;
15948 }
15949
15950 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15951
15952 // The exception specification is needed because we are defining the
15953 // function.
15954 ResolveExceptionSpec(Loc: CurrentLocation,
15955 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15956
15957 // Add a context note for diagnostics produced after this point.
15958 Scope.addContextNote(UseLoc: CurrentLocation);
15959
15960 // C++11 [class.copy]p18:
15961 // The [definition of an implicitly declared copy assignment operator] is
15962 // deprecated if the class has a user-declared copy constructor or a
15963 // user-declared destructor.
15964 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15965 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15966
15967 // C++0x [class.copy]p30:
15968 // The implicitly-defined or explicitly-defaulted copy assignment operator
15969 // for a non-union class X performs memberwise copy assignment of its
15970 // subobjects. The direct base classes of X are assigned first, in the
15971 // order of their declaration in the base-specifier-list, and then the
15972 // immediate non-static data members of X are assigned, in the order in
15973 // which they were declared in the class definition.
15974
15975 // The statements that form the synthesized function body.
15976 SmallVector<Stmt*, 8> Statements;
15977
15978 // The parameter for the "other" object, which we are copying from.
15979 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15980 Qualifiers OtherQuals = Other->getType().getQualifiers();
15981 QualType OtherRefType = Other->getType();
15982 if (OtherRefType->isLValueReferenceType()) {
15983 OtherRefType = OtherRefType->getPointeeType();
15984 OtherQuals = OtherRefType.getQualifiers();
15985 }
15986
15987 // Our location for everything implicitly-generated.
15988 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15989 ? CopyAssignOperator->getEndLoc()
15990 : CopyAssignOperator->getLocation();
15991
15992 // Builds a DeclRefExpr for the "other" object.
15993 RefBuilder OtherRef(Other, OtherRefType);
15994
15995 // Builds the function object parameter.
15996 std::optional<ThisBuilder> This;
15997 std::optional<DerefBuilder> DerefThis;
15998 std::optional<RefBuilder> ExplicitObject;
15999 bool IsArrow = false;
16000 QualType ObjectType;
16001 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
16002 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
16003 if (ObjectType->isReferenceType())
16004 ObjectType = ObjectType->getPointeeType();
16005 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
16006 } else {
16007 ObjectType = getCurrentThisType();
16008 This.emplace();
16009 DerefThis.emplace(args&: *This);
16010 IsArrow = !LangOpts.HLSL;
16011 }
16012 ExprBuilder &ObjectParameter =
16013 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16014 : static_cast<ExprBuilder &>(*This);
16015
16016 // Assign base classes.
16017 bool Invalid = false;
16018 for (auto &Base : ClassDecl->bases()) {
16019 // Form the assignment:
16020 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
16021 QualType BaseType = Base.getType().getUnqualifiedType();
16022 if (!BaseType->isRecordType()) {
16023 Invalid = true;
16024 continue;
16025 }
16026
16027 CXXCastPath BasePath;
16028 BasePath.push_back(Elt: &Base);
16029
16030 // Construct the "from" expression, which is an implicit cast to the
16031 // appropriately-qualified base type.
16032 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
16033 VK_LValue, BasePath);
16034
16035 // Dereference "this".
16036 CastBuilder To(
16037 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16038 : static_cast<ExprBuilder &>(*DerefThis),
16039 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
16040 VK_LValue, BasePath);
16041
16042 // Build the copy.
16043 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
16044 To, From,
16045 /*CopyingBaseSubobject=*/true,
16046 /*Copying=*/true);
16047 if (Copy.isInvalid()) {
16048 CopyAssignOperator->setInvalidDecl();
16049 return;
16050 }
16051
16052 // Success! Record the copy.
16053 Statements.push_back(Elt: Copy.getAs<Expr>());
16054 }
16055
16056 // A defaulted copy assignment operator for a union copies the object
16057 // representation as if by a memcpy, the same way the defaulted union copy
16058 // constructor does. The memberwise loop below skips union members.
16059 if (ClassDecl->isUnion()) {
16060 ExprBuilder &To = ExplicitObject
16061 ? static_cast<ExprBuilder &>(*ExplicitObject)
16062 : static_cast<ExprBuilder &>(*DerefThis);
16063 // Copying the object representation is correct even for a union that is
16064 // not trivially copyable, so -Wnontrivial-memcall is a false positive
16065 // here. Ignoring warnings rather than casting the arguments to void*
16066 // keeps them typed, which preserves their address space.
16067 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
16068 StmtResult Copy = buildMemcpyForAssignmentOp(
16069 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
16070 if (Copy.isInvalid()) {
16071 CopyAssignOperator->setInvalidDecl();
16072 return;
16073 }
16074 Statements.push_back(Elt: Copy.getAs<Stmt>());
16075 }
16076
16077 // Assign non-static members.
16078 for (auto *Field : ClassDecl->fields()) {
16079 // Union members are copied by the whole-object memcpy emitted above.
16080 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
16081 continue;
16082
16083 if (Field->isInvalidDecl()) {
16084 Invalid = true;
16085 continue;
16086 }
16087
16088 // Check for members of reference type; we can't copy those.
16089 if (Field->getType()->isReferenceType()) {
16090 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
16091 << Context.getCanonicalTagType(TD: ClassDecl) << 0
16092 << Field->getDeclName();
16093 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
16094 Invalid = true;
16095 continue;
16096 }
16097
16098 // Check for members of const-qualified, non-class type.
16099 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
16100 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
16101 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
16102 << Context.getCanonicalTagType(TD: ClassDecl) << 1
16103 << Field->getDeclName();
16104 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
16105 Invalid = true;
16106 continue;
16107 }
16108
16109 // Suppress assigning zero-width bitfields.
16110 if (Field->isZeroLengthBitField())
16111 continue;
16112
16113 QualType FieldType = Field->getType().getNonReferenceType();
16114 if (FieldType->isIncompleteArrayType()) {
16115 assert(ClassDecl->hasFlexibleArrayMember() &&
16116 "Incomplete array type is not valid");
16117 continue;
16118 }
16119
16120 // Build references to the field in the object we're copying from and to.
16121 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
16122 LookupMemberName);
16123 MemberLookup.addDecl(D: Field);
16124 MemberLookup.resolveKind();
16125
16126 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
16127 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
16128 // Build the copy of this field.
16129 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
16130 To, From,
16131 /*CopyingBaseSubobject=*/false,
16132 /*Copying=*/true);
16133 if (Copy.isInvalid()) {
16134 CopyAssignOperator->setInvalidDecl();
16135 return;
16136 }
16137
16138 // Success! Record the copy.
16139 Statements.push_back(Elt: Copy.getAs<Stmt>());
16140 }
16141
16142 if (!Invalid) {
16143 // Add a "return *this;"
16144 Expr *ThisExpr =
16145 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16146 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16147 : static_cast<ExprBuilder &>(*DerefThis))
16148 .build(S&: *this, Loc);
16149 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
16150 if (Return.isInvalid())
16151 Invalid = true;
16152 else
16153 Statements.push_back(Elt: Return.getAs<Stmt>());
16154 }
16155
16156 if (Invalid) {
16157 CopyAssignOperator->setInvalidDecl();
16158 return;
16159 }
16160
16161 StmtResult Body;
16162 {
16163 CompoundScopeRAII CompoundScope(*this);
16164 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
16165 /*isStmtExpr=*/false);
16166 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16167 }
16168 CopyAssignOperator->setBody(Body.getAs<Stmt>());
16169 CopyAssignOperator->markUsed(C&: Context);
16170
16171 if (ASTMutationListener *L = getASTMutationListener()) {
16172 L->CompletedImplicitDefinition(D: CopyAssignOperator);
16173 }
16174}
16175
16176CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
16177 assert(ClassDecl->needsImplicitMoveAssignment());
16178
16179 DeclaringSpecialMember DSM(*this, ClassDecl,
16180 CXXSpecialMemberKind::MoveAssignment);
16181 if (DSM.isAlreadyBeingDeclared())
16182 return nullptr;
16183
16184 // Note: The following rules are largely analoguous to the move
16185 // constructor rules.
16186
16187 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16188 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16189 /*OwnsTag=*/false);
16190 LangAS AS = getDefaultCXXMethodAddrSpace();
16191 if (AS != LangAS::Default)
16192 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
16193 QualType RetType = Context.getLValueReferenceType(T: ArgType);
16194 ArgType = Context.getRValueReferenceType(T: ArgType);
16195
16196 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16197 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
16198
16199 // An implicitly-declared move assignment operator is an inline public
16200 // member of its class.
16201 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
16202 SourceLocation ClassLoc = ClassDecl->getLocation();
16203 DeclarationNameInfo NameInfo(Name, ClassLoc);
16204 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
16205 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
16206 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
16207 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16208 /*isInline=*/true,
16209 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
16210 EndLocation: SourceLocation());
16211 MoveAssignment->setAccess(AS_public);
16212 MoveAssignment->setDefaulted();
16213 MoveAssignment->setImplicit();
16214
16215 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
16216
16217 if (getLangOpts().CUDA)
16218 CUDA().inferTargetForImplicitSpecialMember(
16219 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
16220 /* ConstRHS */ false,
16221 /* Diagnose */ false);
16222
16223 // Add the parameter to the operator.
16224 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
16225 StartLoc: ClassLoc, IdLoc: ClassLoc,
16226 /*Id=*/nullptr, T: ArgType,
16227 /*TInfo=*/nullptr, S: SC_None,
16228 DefArg: nullptr);
16229 MoveAssignment->setParams(FromParam);
16230
16231 MoveAssignment->setTrivial(
16232 ClassDecl->needsOverloadResolutionForMoveAssignment()
16233 ? SpecialMemberIsTrivial(MD: MoveAssignment,
16234 CSM: CXXSpecialMemberKind::MoveAssignment)
16235 : ClassDecl->hasTrivialMoveAssignment());
16236
16237 // Note that we have added this copy-assignment operator.
16238 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
16239
16240 Scope *S = getScopeForContext(Ctx: ClassDecl);
16241 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
16242
16243 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
16244 CSM: CXXSpecialMemberKind::MoveAssignment)) {
16245 ClassDecl->setImplicitMoveAssignmentIsDeleted();
16246 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
16247 }
16248
16249 if (S)
16250 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
16251 ClassDecl->addDecl(D: MoveAssignment);
16252
16253 return MoveAssignment;
16254}
16255
16256/// Check if we're implicitly defining a move assignment operator for a class
16257/// with virtual bases. Such a move assignment might move-assign the virtual
16258/// base multiple times.
16259static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
16260 SourceLocation CurrentLocation) {
16261 assert(!Class->isDependentContext() && "should not define dependent move");
16262
16263 // Only a virtual base could get implicitly move-assigned multiple times.
16264 // Only a non-trivial move assignment can observe this. We only want to
16265 // diagnose if we implicitly define an assignment operator that assigns
16266 // two base classes, both of which move-assign the same virtual base.
16267 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
16268 Class->getNumBases() < 2)
16269 return;
16270
16271 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
16272 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
16273 VBaseMap VBases;
16274
16275 for (auto &BI : Class->bases()) {
16276 Worklist.push_back(Elt: &BI);
16277 while (!Worklist.empty()) {
16278 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
16279 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
16280
16281 // If the base has no non-trivial move assignment operators,
16282 // we don't care about moves from it.
16283 if (!Base->hasNonTrivialMoveAssignment())
16284 continue;
16285
16286 // If there's nothing virtual here, skip it.
16287 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
16288 continue;
16289
16290 // If we're not actually going to call a move assignment for this base,
16291 // or the selected move assignment is trivial, skip it.
16292 Sema::SpecialMemberOverloadResult SMOR =
16293 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
16294 /*ConstArg*/ false, /*VolatileArg*/ false,
16295 /*RValueThis*/ true, /*ConstThis*/ false,
16296 /*VolatileThis*/ false);
16297 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
16298 !SMOR.getMethod()->isMoveAssignmentOperator())
16299 continue;
16300
16301 if (BaseSpec->isVirtual()) {
16302 // We're going to move-assign this virtual base, and its move
16303 // assignment operator is not trivial. If this can happen for
16304 // multiple distinct direct bases of Class, diagnose it. (If it
16305 // only happens in one base, we'll diagnose it when synthesizing
16306 // that base class's move assignment operator.)
16307 CXXBaseSpecifier *&Existing =
16308 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
16309 .first->second;
16310 if (Existing && Existing != &BI) {
16311 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
16312 << Class << Base;
16313 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
16314 << (Base->getCanonicalDecl() ==
16315 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
16316 << Base << Existing->getType() << Existing->getSourceRange();
16317 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
16318 << (Base->getCanonicalDecl() ==
16319 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
16320 << Base << BI.getType() << BaseSpec->getSourceRange();
16321
16322 // Only diagnose each vbase once.
16323 Existing = nullptr;
16324 }
16325 } else {
16326 // Only walk over bases that have defaulted move assignment operators.
16327 // We assume that any user-provided move assignment operator handles
16328 // the multiple-moves-of-vbase case itself somehow.
16329 if (!SMOR.getMethod()->isDefaulted())
16330 continue;
16331
16332 // We're going to move the base classes of Base. Add them to the list.
16333 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
16334 }
16335 }
16336 }
16337}
16338
16339void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
16340 CXXMethodDecl *MoveAssignOperator) {
16341 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
16342 assert((MoveAssignOperator->isDefaulted() &&
16343 MoveAssignOperator->isOverloadedOperator() &&
16344 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
16345 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
16346 !MoveAssignOperator->isDeleted()) &&
16347 "DefineImplicitMoveAssignment called for wrong function");
16348 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
16349 return;
16350
16351 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
16352 if (ClassDecl->isInvalidDecl()) {
16353 MoveAssignOperator->setInvalidDecl();
16354 return;
16355 }
16356
16357 // C++0x [class.copy]p28:
16358 // The implicitly-defined or move assignment operator for a non-union class
16359 // X performs memberwise move assignment of its subobjects. The direct base
16360 // classes of X are assigned first, in the order of their declaration in the
16361 // base-specifier-list, and then the immediate non-static data members of X
16362 // are assigned, in the order in which they were declared in the class
16363 // definition.
16364
16365 // Issue a warning if our implicit move assignment operator will move
16366 // from a virtual base more than once.
16367 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
16368
16369 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
16370
16371 // The exception specification is needed because we are defining the
16372 // function.
16373 ResolveExceptionSpec(Loc: CurrentLocation,
16374 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
16375
16376 // Add a context note for diagnostics produced after this point.
16377 Scope.addContextNote(UseLoc: CurrentLocation);
16378
16379 // The statements that form the synthesized function body.
16380 SmallVector<Stmt*, 8> Statements;
16381
16382 // The parameter for the "other" object, which we are move from.
16383 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
16384 QualType OtherRefType =
16385 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
16386
16387 // Our location for everything implicitly-generated.
16388 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
16389 ? MoveAssignOperator->getEndLoc()
16390 : MoveAssignOperator->getLocation();
16391
16392 // Builds a reference to the "other" object.
16393 RefBuilder OtherRef(Other, OtherRefType);
16394 // Cast to rvalue.
16395 MoveCastBuilder MoveOther(OtherRef);
16396
16397 // Builds the function object parameter.
16398 std::optional<ThisBuilder> This;
16399 std::optional<DerefBuilder> DerefThis;
16400 std::optional<RefBuilder> ExplicitObject;
16401 QualType ObjectType;
16402 bool IsArrow = false;
16403 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
16404 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
16405 if (ObjectType->isReferenceType())
16406 ObjectType = ObjectType->getPointeeType();
16407 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
16408 } else {
16409 ObjectType = getCurrentThisType();
16410 This.emplace();
16411 DerefThis.emplace(args&: *This);
16412 IsArrow = !getLangOpts().HLSL;
16413 }
16414 ExprBuilder &ObjectParameter =
16415 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
16416
16417 // Assign base classes.
16418 bool Invalid = false;
16419 for (auto &Base : ClassDecl->bases()) {
16420 // C++11 [class.copy]p28:
16421 // It is unspecified whether subobjects representing virtual base classes
16422 // are assigned more than once by the implicitly-defined copy assignment
16423 // operator.
16424 // FIXME: Do not assign to a vbase that will be assigned by some other base
16425 // class. For a move-assignment, this can result in the vbase being moved
16426 // multiple times.
16427
16428 // Form the assignment:
16429 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
16430 QualType BaseType = Base.getType().getUnqualifiedType();
16431 if (!BaseType->isRecordType()) {
16432 Invalid = true;
16433 continue;
16434 }
16435
16436 CXXCastPath BasePath;
16437 BasePath.push_back(Elt: &Base);
16438
16439 // Construct the "from" expression, which is an implicit cast to the
16440 // appropriately-qualified base type.
16441 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
16442
16443 // Implicitly cast "this" to the appropriately-qualified base type.
16444 // Dereference "this".
16445 CastBuilder To(
16446 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16447 : static_cast<ExprBuilder &>(*DerefThis),
16448 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
16449 VK_LValue, BasePath);
16450
16451 // Build the move.
16452 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
16453 To, From,
16454 /*CopyingBaseSubobject=*/true,
16455 /*Copying=*/false);
16456 if (Move.isInvalid()) {
16457 MoveAssignOperator->setInvalidDecl();
16458 return;
16459 }
16460
16461 // Success! Record the move.
16462 Statements.push_back(Elt: Move.getAs<Expr>());
16463 }
16464
16465 // A defaulted move assignment operator for a union copies the object
16466 // representation as if by a memcpy, the same way the defaulted union copy
16467 // constructor does. The memberwise loop below skips union members.
16468 if (ClassDecl->isUnion()) {
16469 ExprBuilder &To = ExplicitObject
16470 ? static_cast<ExprBuilder &>(*ExplicitObject)
16471 : static_cast<ExprBuilder &>(*DerefThis);
16472 // Copying the object representation is correct even for a union that is
16473 // not trivially copyable, so -Wnontrivial-memcall is a false positive
16474 // here. Ignoring warnings rather than casting the arguments to void*
16475 // keeps them typed, which preserves their address space.
16476 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
16477 StmtResult Copy = buildMemcpyForAssignmentOp(
16478 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
16479 if (Copy.isInvalid()) {
16480 MoveAssignOperator->setInvalidDecl();
16481 return;
16482 }
16483 Statements.push_back(Elt: Copy.getAs<Stmt>());
16484 }
16485
16486 // Assign non-static members.
16487 for (auto *Field : ClassDecl->fields()) {
16488 // Union members are copied by the whole-object memcpy emitted above.
16489 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
16490 continue;
16491
16492 if (Field->isInvalidDecl()) {
16493 Invalid = true;
16494 continue;
16495 }
16496
16497 // Check for members of reference type; we can't move those.
16498 if (Field->getType()->isReferenceType()) {
16499 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
16500 << Context.getCanonicalTagType(TD: ClassDecl) << 0
16501 << Field->getDeclName();
16502 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
16503 Invalid = true;
16504 continue;
16505 }
16506
16507 // Check for members of const-qualified, non-class type.
16508 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
16509 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
16510 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
16511 << Context.getCanonicalTagType(TD: ClassDecl) << 1
16512 << Field->getDeclName();
16513 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
16514 Invalid = true;
16515 continue;
16516 }
16517
16518 // Suppress assigning zero-width bitfields.
16519 if (Field->isZeroLengthBitField())
16520 continue;
16521
16522 QualType FieldType = Field->getType().getNonReferenceType();
16523 if (FieldType->isIncompleteArrayType()) {
16524 assert(ClassDecl->hasFlexibleArrayMember() &&
16525 "Incomplete array type is not valid");
16526 continue;
16527 }
16528
16529 // Build references to the field in the object we're copying from and to.
16530 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
16531 LookupMemberName);
16532 MemberLookup.addDecl(D: Field);
16533 MemberLookup.resolveKind();
16534 MemberBuilder From(MoveOther, OtherRefType,
16535 /*IsArrow=*/false, MemberLookup);
16536 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
16537
16538 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
16539 "Member reference with rvalue base must be rvalue except for reference "
16540 "members, which aren't allowed for move assignment.");
16541
16542 // Build the move of this field.
16543 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
16544 To, From,
16545 /*CopyingBaseSubobject=*/false,
16546 /*Copying=*/false);
16547 if (Move.isInvalid()) {
16548 MoveAssignOperator->setInvalidDecl();
16549 return;
16550 }
16551
16552 // Success! Record the copy.
16553 Statements.push_back(Elt: Move.getAs<Stmt>());
16554 }
16555
16556 if (!Invalid) {
16557 // Add a "return *this;"
16558 Expr *ThisExpr =
16559 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16560 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16561 : static_cast<ExprBuilder &>(*DerefThis))
16562 .build(S&: *this, Loc);
16563
16564 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
16565 if (Return.isInvalid())
16566 Invalid = true;
16567 else
16568 Statements.push_back(Elt: Return.getAs<Stmt>());
16569 }
16570
16571 if (Invalid) {
16572 MoveAssignOperator->setInvalidDecl();
16573 return;
16574 }
16575
16576 StmtResult Body;
16577 {
16578 CompoundScopeRAII CompoundScope(*this);
16579 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
16580 /*isStmtExpr=*/false);
16581 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16582 }
16583 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16584 MoveAssignOperator->markUsed(C&: Context);
16585
16586 if (ASTMutationListener *L = getASTMutationListener()) {
16587 L->CompletedImplicitDefinition(D: MoveAssignOperator);
16588 }
16589}
16590
16591CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
16592 CXXRecordDecl *ClassDecl) {
16593 // C++ [class.copy]p4:
16594 // If the class definition does not explicitly declare a copy
16595 // constructor, one is declared implicitly.
16596 assert(ClassDecl->needsImplicitCopyConstructor());
16597
16598 DeclaringSpecialMember DSM(*this, ClassDecl,
16599 CXXSpecialMemberKind::CopyConstructor);
16600 if (DSM.isAlreadyBeingDeclared())
16601 return nullptr;
16602
16603 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16604 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16605 /*OwnsTag=*/false);
16606 QualType ArgType = ClassType;
16607 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16608 if (Const)
16609 ArgType = ArgType.withConst();
16610
16611 LangAS AS = getDefaultCXXMethodAddrSpace();
16612 if (AS != LangAS::Default)
16613 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
16614
16615 ArgType = Context.getLValueReferenceType(T: ArgType);
16616
16617 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16618 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
16619
16620 DeclarationName Name
16621 = Context.DeclarationNames.getCXXConstructorName(
16622 Ty: Context.getCanonicalType(T: ClassType));
16623 SourceLocation ClassLoc = ClassDecl->getLocation();
16624 DeclarationNameInfo NameInfo(Name, ClassLoc);
16625
16626 // An implicitly-declared copy constructor is an inline public
16627 // member of its class.
16628 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
16629 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16630 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16631 /*isInline=*/true,
16632 /*isImplicitlyDeclared=*/true,
16633 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16634 : ConstexprSpecKind::Unspecified);
16635 CopyConstructor->setAccess(AS_public);
16636 CopyConstructor->setDefaulted();
16637
16638 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16639
16640 if (getLangOpts().CUDA)
16641 CUDA().inferTargetForImplicitSpecialMember(
16642 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
16643 /* ConstRHS */ Const,
16644 /* Diagnose */ false);
16645
16646 // During template instantiation of special member functions we need a
16647 // reliable TypeSourceInfo for the parameter types in order to allow functions
16648 // to be substituted.
16649 TypeSourceInfo *TSI = nullptr;
16650 if (inTemplateInstantiation() && ClassDecl->isLambda())
16651 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
16652
16653 // Add the parameter to the constructor.
16654 ParmVarDecl *FromParam =
16655 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
16656 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
16657 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
16658 CopyConstructor->setParams(FromParam);
16659
16660 CopyConstructor->setTrivial(
16661 ClassDecl->needsOverloadResolutionForCopyConstructor()
16662 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16663 CSM: CXXSpecialMemberKind::CopyConstructor)
16664 : ClassDecl->hasTrivialCopyConstructor());
16665
16666 CopyConstructor->setTrivialForCall(
16667 ClassDecl->hasAttr<TrivialABIAttr>() ||
16668 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16669 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16670 CSM: CXXSpecialMemberKind::CopyConstructor,
16671 TAH: TrivialABIHandling::ConsiderTrivialABI)
16672 : ClassDecl->hasTrivialCopyConstructorForCall()));
16673
16674 // Note that we have declared this constructor.
16675 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16676
16677 Scope *S = getScopeForContext(Ctx: ClassDecl);
16678 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16679
16680 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16681 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16682 ClassDecl->setImplicitCopyConstructorIsDeleted();
16683 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16684 }
16685
16686 if (S)
16687 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16688 ClassDecl->addDecl(D: CopyConstructor);
16689
16690 return CopyConstructor;
16691}
16692
16693void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16694 CXXConstructorDecl *CopyConstructor) {
16695 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16696 assert((CopyConstructor->isDefaulted() &&
16697 CopyConstructor->isCopyConstructor() &&
16698 !CopyConstructor->doesThisDeclarationHaveABody() &&
16699 !CopyConstructor->isDeleted()) &&
16700 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16701 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16702 return;
16703
16704 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16705 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16706
16707 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16708
16709 // The exception specification is needed because we are defining the
16710 // function.
16711 ResolveExceptionSpec(Loc: CurrentLocation,
16712 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16713 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16714
16715 // Add a context note for diagnostics produced after this point.
16716 Scope.addContextNote(UseLoc: CurrentLocation);
16717
16718 // C++11 [class.copy]p7:
16719 // The [definition of an implicitly declared copy constructor] is
16720 // deprecated if the class has a user-declared copy assignment operator
16721 // or a user-declared destructor.
16722 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16723 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16724
16725 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16726 CopyConstructor->setInvalidDecl();
16727 } else {
16728 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16729 ? CopyConstructor->getEndLoc()
16730 : CopyConstructor->getLocation();
16731 Sema::CompoundScopeRAII CompoundScope(*this);
16732 CopyConstructor->setBody(
16733 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16734 CopyConstructor->markUsed(C&: Context);
16735 }
16736
16737 if (ASTMutationListener *L = getASTMutationListener()) {
16738 L->CompletedImplicitDefinition(D: CopyConstructor);
16739 }
16740}
16741
16742CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16743 CXXRecordDecl *ClassDecl) {
16744 assert(ClassDecl->needsImplicitMoveConstructor());
16745
16746 DeclaringSpecialMember DSM(*this, ClassDecl,
16747 CXXSpecialMemberKind::MoveConstructor);
16748 if (DSM.isAlreadyBeingDeclared())
16749 return nullptr;
16750
16751 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16752 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16753 /*OwnsTag=*/false);
16754
16755 QualType ArgType = ClassType;
16756 LangAS AS = getDefaultCXXMethodAddrSpace();
16757 if (AS != LangAS::Default)
16758 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16759 ArgType = Context.getRValueReferenceType(T: ArgType);
16760
16761 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16762 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16763
16764 DeclarationName Name
16765 = Context.DeclarationNames.getCXXConstructorName(
16766 Ty: Context.getCanonicalType(T: ClassType));
16767 SourceLocation ClassLoc = ClassDecl->getLocation();
16768 DeclarationNameInfo NameInfo(Name, ClassLoc);
16769
16770 // C++11 [class.copy]p11:
16771 // An implicitly-declared copy/move constructor is an inline public
16772 // member of its class.
16773 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16774 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16775 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16776 /*isInline=*/true,
16777 /*isImplicitlyDeclared=*/true,
16778 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16779 : ConstexprSpecKind::Unspecified);
16780 MoveConstructor->setAccess(AS_public);
16781 MoveConstructor->setDefaulted();
16782
16783 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16784
16785 if (getLangOpts().CUDA)
16786 CUDA().inferTargetForImplicitSpecialMember(
16787 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16788 /* ConstRHS */ false,
16789 /* Diagnose */ false);
16790
16791 // Add the parameter to the constructor.
16792 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16793 StartLoc: ClassLoc, IdLoc: ClassLoc,
16794 /*IdentifierInfo=*/Id: nullptr,
16795 T: ArgType, /*TInfo=*/nullptr,
16796 S: SC_None, DefArg: nullptr);
16797 MoveConstructor->setParams(FromParam);
16798
16799 MoveConstructor->setTrivial(
16800 ClassDecl->needsOverloadResolutionForMoveConstructor()
16801 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16802 CSM: CXXSpecialMemberKind::MoveConstructor)
16803 : ClassDecl->hasTrivialMoveConstructor());
16804
16805 MoveConstructor->setTrivialForCall(
16806 ClassDecl->hasAttr<TrivialABIAttr>() ||
16807 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16808 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16809 CSM: CXXSpecialMemberKind::MoveConstructor,
16810 TAH: TrivialABIHandling::ConsiderTrivialABI)
16811 : ClassDecl->hasTrivialMoveConstructorForCall()));
16812
16813 // Note that we have declared this constructor.
16814 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16815
16816 Scope *S = getScopeForContext(Ctx: ClassDecl);
16817 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16818
16819 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16820 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16821 ClassDecl->setImplicitMoveConstructorIsDeleted();
16822 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16823 }
16824
16825 if (S)
16826 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16827 ClassDecl->addDecl(D: MoveConstructor);
16828
16829 return MoveConstructor;
16830}
16831
16832void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16833 CXXConstructorDecl *MoveConstructor) {
16834 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16835 assert((MoveConstructor->isDefaulted() &&
16836 MoveConstructor->isMoveConstructor() &&
16837 !MoveConstructor->doesThisDeclarationHaveABody() &&
16838 !MoveConstructor->isDeleted()) &&
16839 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16840 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16841 return;
16842
16843 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16844 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16845
16846 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16847
16848 // The exception specification is needed because we are defining the
16849 // function.
16850 ResolveExceptionSpec(Loc: CurrentLocation,
16851 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16852 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16853
16854 // Add a context note for diagnostics produced after this point.
16855 Scope.addContextNote(UseLoc: CurrentLocation);
16856
16857 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16858 MoveConstructor->setInvalidDecl();
16859 } else {
16860 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16861 ? MoveConstructor->getEndLoc()
16862 : MoveConstructor->getLocation();
16863 Sema::CompoundScopeRAII CompoundScope(*this);
16864 MoveConstructor->setBody(
16865 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16866 MoveConstructor->markUsed(C&: Context);
16867 }
16868
16869 if (ASTMutationListener *L = getASTMutationListener()) {
16870 L->CompletedImplicitDefinition(D: MoveConstructor);
16871 }
16872}
16873
16874bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16875 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16876}
16877
16878void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16879 SourceLocation CurrentLocation,
16880 CXXConversionDecl *Conv) {
16881 SynthesizedFunctionScope Scope(*this, Conv);
16882 assert(!Conv->getReturnType()->isUndeducedType());
16883
16884 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16885 CallingConv CC =
16886 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16887
16888 CXXRecordDecl *Lambda = Conv->getParent();
16889 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16890 FunctionDecl *Invoker =
16891 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16892 ? CallOp
16893 : Lambda->getLambdaStaticInvoker(CC);
16894
16895 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16896 CallOp = InstantiateFunctionDeclaration(
16897 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16898 if (!CallOp)
16899 return;
16900
16901 if (CallOp != Invoker) {
16902 Invoker = InstantiateFunctionDeclaration(
16903 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16904 Loc: CurrentLocation);
16905 if (!Invoker)
16906 return;
16907 }
16908 }
16909
16910 if (CallOp->isInvalidDecl())
16911 return;
16912
16913 // Mark the call operator referenced (and add to pending instantiations
16914 // if necessary).
16915 // For both the conversion and static-invoker template specializations
16916 // we construct their body's in this function, so no need to add them
16917 // to the PendingInstantiations.
16918 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16919
16920 if (Invoker != CallOp) {
16921 // Fill in the __invoke function with a dummy implementation. IR generation
16922 // will fill in the actual details. Update its type in case it contained
16923 // an 'auto'.
16924 Invoker->markUsed(C&: Context);
16925 Invoker->setReferenced();
16926 Invoker->setType(Conv->getReturnType()->getPointeeType());
16927 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16928 }
16929
16930 // Construct the body of the conversion function { return __invoke; }.
16931 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16932 Loc: Conv->getLocation());
16933 assert(FunctionRef && "Can't refer to __invoke function?");
16934 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16935 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16936 LB: Conv->getLocation(), RB: Conv->getLocation()));
16937 Conv->markUsed(C&: Context);
16938 Conv->setReferenced();
16939
16940 if (ASTMutationListener *L = getASTMutationListener()) {
16941 L->CompletedImplicitDefinition(D: Conv);
16942 if (Invoker != CallOp)
16943 L->CompletedImplicitDefinition(D: Invoker);
16944 }
16945}
16946
16947void Sema::DefineImplicitLambdaToBlockPointerConversion(
16948 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16949 assert(!Conv->getParent()->isGenericLambda());
16950
16951 SynthesizedFunctionScope Scope(*this, Conv);
16952
16953 // Copy-initialize the lambda object as needed to capture it.
16954 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16955 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16956
16957 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16958 ConvLocation: Conv->getLocation(),
16959 Conv, Src: DerefThis);
16960
16961 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16962 // behavior. Note that only the general conversion function does this
16963 // (since it's unusable otherwise); in the case where we inline the
16964 // block literal, it has block literal lifetime semantics.
16965 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16966 BuildBlock = ImplicitCastExpr::Create(
16967 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16968 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16969
16970 if (BuildBlock.isInvalid()) {
16971 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16972 Conv->setInvalidDecl();
16973 return;
16974 }
16975
16976 // Create the return statement that returns the block from the conversion
16977 // function.
16978 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16979 if (Return.isInvalid()) {
16980 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16981 Conv->setInvalidDecl();
16982 return;
16983 }
16984
16985 // Set the body of the conversion function.
16986 Stmt *ReturnS = Return.get();
16987 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16988 LB: Conv->getLocation(), RB: Conv->getLocation()));
16989 Conv->markUsed(C&: Context);
16990
16991 // We're done; notify the mutation listener, if any.
16992 if (ASTMutationListener *L = getASTMutationListener()) {
16993 L->CompletedImplicitDefinition(D: Conv);
16994 }
16995}
16996
16997/// Determine whether the given list arguments contains exactly one
16998/// "real" (non-default) argument.
16999static bool hasOneRealArgument(MultiExprArg Args) {
17000 switch (Args.size()) {
17001 case 0:
17002 return false;
17003
17004 default:
17005 if (!Args[1]->isDefaultArgument())
17006 return false;
17007
17008 [[fallthrough]];
17009 case 1:
17010 return !Args[0]->isDefaultArgument();
17011 }
17012
17013 return false;
17014}
17015
17016ExprResult Sema::BuildCXXConstructExpr(
17017 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
17018 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
17019 bool HadMultipleCandidates, bool IsListInitialization,
17020 bool IsStdInitListInitialization, bool RequiresZeroInit,
17021 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
17022 bool Elidable = false;
17023
17024 // C++0x [class.copy]p34:
17025 // When certain criteria are met, an implementation is allowed to
17026 // omit the copy/move construction of a class object, even if the
17027 // copy/move constructor and/or destructor for the object have
17028 // side effects. [...]
17029 // - when a temporary class object that has not been bound to a
17030 // reference (12.2) would be copied/moved to a class object
17031 // with the same cv-unqualified type, the copy/move operation
17032 // can be omitted by constructing the temporary object
17033 // directly into the target of the omitted copy/move
17034 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
17035 // FIXME: Converting constructors should also be accepted.
17036 // But to fix this, the logic that digs down into a CXXConstructExpr
17037 // to find the source object needs to handle it.
17038 // Right now it assumes the source object is passed directly as the
17039 // first argument.
17040 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
17041 Expr *SubExpr = ExprArgs[0];
17042 // FIXME: Per above, this is also incorrect if we want to accept
17043 // converting constructors, as isTemporaryObject will
17044 // reject temporaries with different type from the
17045 // CXXRecord itself.
17046 Elidable = SubExpr->isTemporaryObject(
17047 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
17048 }
17049
17050 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
17051 FoundDecl, Constructor,
17052 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
17053 IsListInitialization,
17054 IsStdInitListInitialization, RequiresZeroInit,
17055 ConstructKind, ParenRange);
17056}
17057
17058ExprResult Sema::BuildCXXConstructExpr(
17059 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
17060 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
17061 bool HadMultipleCandidates, bool IsListInitialization,
17062 bool IsStdInitListInitialization, bool RequiresZeroInit,
17063 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
17064 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
17065 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
17066 // The only way to get here is if we did overload resolution to find the
17067 // shadow decl, so we don't need to worry about re-checking the trailing
17068 // requires clause.
17069 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
17070 return ExprError();
17071 }
17072
17073 return BuildCXXConstructExpr(
17074 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
17075 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
17076 RequiresZeroInit, ConstructKind, ParenRange);
17077}
17078
17079/// BuildCXXConstructExpr - Creates a complete call to a constructor,
17080/// including handling of its default argument expressions.
17081ExprResult Sema::BuildCXXConstructExpr(
17082 SourceLocation ConstructLoc, QualType DeclInitType,
17083 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
17084 bool HadMultipleCandidates, bool IsListInitialization,
17085 bool IsStdInitListInitialization, bool RequiresZeroInit,
17086 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
17087 assert(declaresSameEntity(
17088 Constructor->getParent(),
17089 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
17090 "given constructor for wrong type");
17091 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
17092 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
17093 return ExprError();
17094
17095 return CheckForImmediateInvocation(
17096 E: CXXConstructExpr::Create(
17097 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
17098 HadMultipleCandidates, ListInitialization: IsListInitialization,
17099 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
17100 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
17101 Decl: Constructor);
17102}
17103
17104void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
17105 if (VD->isInvalidDecl()) return;
17106 // If initializing the variable failed, don't also diagnose problems with
17107 // the destructor, they're likely related.
17108 if (VD->getInit() && VD->getInit()->containsErrors())
17109 return;
17110
17111 ClassDecl = ClassDecl->getDefinitionOrSelf();
17112 if (ClassDecl->isInvalidDecl()) return;
17113 if (ClassDecl->hasIrrelevantDestructor()) return;
17114 if (ClassDecl->isDependentContext()) return;
17115
17116 if (VD->isNoDestroy(getASTContext()))
17117 return;
17118
17119 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
17120 // The result of `LookupDestructor` might be nullptr if the destructor is
17121 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
17122 // will not be selected by `CXXRecordDecl::getDestructor()`.
17123 if (!Destructor)
17124 return;
17125 // If this is an array, we'll require the destructor during initialization, so
17126 // we can skip over this. We still want to emit exit-time destructor warnings
17127 // though.
17128 if (!VD->getType()->isArrayType()) {
17129 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
17130 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
17131 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
17132 << VD->getDeclName() << VD->getType());
17133 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
17134 }
17135
17136 if (Destructor->isTrivial()) return;
17137
17138 // If the destructor is constexpr, check whether the variable has constant
17139 // destruction now.
17140 if (Destructor->isConstexpr()) {
17141 bool HasConstantInit = false;
17142 if (VD->getInit() && !VD->getInit()->isValueDependent())
17143 HasConstantInit = VD->evaluateValue();
17144 SmallVector<PartialDiagnosticAt, 8> Notes;
17145 sema::EvalProxy SProxy(*this);
17146 if (!VD->evaluateConstantDestruction(Notes, SProxy) && VD->isConstexpr() &&
17147 HasConstantInit) {
17148 Diag(Loc: VD->getLocation(),
17149 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
17150 for (const PartialDiagnosticAt &Note : Notes)
17151 Diag(Loc: Note.first, PD: Note.second);
17152 }
17153 }
17154
17155 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
17156 return;
17157
17158 // Emit warning for non-trivial dtor in global scope (a real global,
17159 // class-static, function-static).
17160 if (!VD->hasAttr<AlwaysDestroyAttr>())
17161 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
17162
17163 // TODO: this should be re-enabled for static locals by !CXAAtExit
17164 if (!VD->isStaticLocal())
17165 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
17166}
17167
17168bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
17169 QualType DeclInitType, MultiExprArg ArgsPtr,
17170 SourceLocation Loc,
17171 SmallVectorImpl<Expr *> &ConvertedArgs,
17172 bool AllowExplicit,
17173 bool IsListInitialization) {
17174 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
17175 unsigned NumArgs = ArgsPtr.size();
17176 Expr **Args = ArgsPtr.data();
17177
17178 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
17179 unsigned NumParams = Proto->getNumParams();
17180
17181 // If too few arguments are available, we'll fill in the rest with defaults.
17182 if (NumArgs < NumParams)
17183 ConvertedArgs.reserve(N: NumParams);
17184 else
17185 ConvertedArgs.reserve(N: NumArgs);
17186
17187 VariadicCallType CallType = Proto->isVariadic()
17188 ? VariadicCallType::Constructor
17189 : VariadicCallType::DoesNotApply;
17190 SmallVector<Expr *, 8> AllArgs;
17191 bool Invalid = GatherArgumentsForCall(
17192 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
17193 CallType, AllowExplicit, IsListInitialization);
17194 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
17195
17196 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
17197
17198 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
17199 Proto, Loc);
17200
17201 return Invalid;
17202}
17203
17204TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
17205 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
17206 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
17207}
17208
17209FunctionDecl *
17210Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
17211 QualType DeallocType, SourceLocation Loc) {
17212 if (DeallocType.isNull())
17213 return nullptr;
17214
17215 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
17216 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
17217 return nullptr;
17218
17219 if (FnDecl->isVariadic())
17220 return nullptr;
17221
17222 unsigned NumParams = FnDecl->getNumParams();
17223 constexpr unsigned RequiredParameterCount =
17224 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
17225 // A usual deallocation function has no placement parameters
17226 if (NumParams != RequiredParameterCount)
17227 return nullptr;
17228
17229 // A type aware allocation is only usual if the only dependent parameter is
17230 // the first parameter.
17231 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
17232 P: [](const ParmVarDecl *ParamDecl) {
17233 return ParamDecl->getType()->isDependentType();
17234 }))
17235 return nullptr;
17236
17237 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
17238 if (SpecializedTypeIdentity.isNull())
17239 return nullptr;
17240
17241 SmallVector<QualType, RequiredParameterCount> ArgTypes;
17242 ArgTypes.reserve(N: NumParams);
17243
17244 // The first parameter to a type aware operator delete is by definition the
17245 // type-identity argument, so we explicitly set this to the target
17246 // type-identity type, the remaining usual parameters should then simply match
17247 // the type declared in the function template.
17248 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
17249 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
17250 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
17251
17252 FunctionProtoType::ExtProtoInfo EPI;
17253 QualType ExpectedFunctionType =
17254 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
17255 sema::TemplateDeductionInfo Info(Loc);
17256 FunctionDecl *Result;
17257 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
17258 Specialization&: Result, Info) != TemplateDeductionResult::Success)
17259 return nullptr;
17260 return Result;
17261}
17262
17263static inline bool
17264CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
17265 const FunctionDecl *FnDecl) {
17266 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
17267 if (isa<NamespaceDecl>(Val: DC)) {
17268 return SemaRef.Diag(Loc: FnDecl->getLocation(),
17269 DiagID: diag::err_operator_new_delete_declared_in_namespace)
17270 << FnDecl->getDeclName();
17271 }
17272
17273 if (isa<TranslationUnitDecl>(Val: DC) &&
17274 FnDecl->getStorageClass() == SC_Static) {
17275 return SemaRef.Diag(Loc: FnDecl->getLocation(),
17276 DiagID: diag::err_operator_new_delete_declared_static)
17277 << FnDecl->getDeclName();
17278 }
17279
17280 return false;
17281}
17282
17283static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
17284 const PointerType *PtrTy) {
17285 auto &Ctx = SemaRef.Context;
17286 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
17287 PtrQuals.removeAddressSpace();
17288 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
17289 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
17290}
17291
17292enum class AllocationOperatorKind { New, Delete };
17293
17294static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
17295 const FunctionDecl *FD,
17296 bool *WasMalformed) {
17297 const Decl *MalformedDecl = nullptr;
17298 if (FD->getNumParams() > 0 &&
17299 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
17300 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
17301 return true;
17302
17303 if (!MalformedDecl)
17304 return false;
17305
17306 if (WasMalformed)
17307 *WasMalformed = true;
17308
17309 return true;
17310}
17311
17312static bool isDestroyingDeleteT(QualType Type) {
17313 auto *RD = Type->getAsCXXRecordDecl();
17314 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
17315 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
17316}
17317
17318static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
17319 const FunctionDecl *FD) {
17320 // C++ P0722:
17321 // Within a class C, a single object deallocation function with signature
17322 // (T, std::destroying_delete_t, <more params>)
17323 // is a destroying operator delete.
17324 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
17325 SemaRef, FD, /*WasMalformed=*/nullptr);
17326 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
17327 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
17328 FD->getNumParams() > DestroyingDeleteIdx &&
17329 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
17330}
17331
17332static inline bool CheckOperatorNewDeleteTypes(
17333 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
17334 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
17335 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
17336 auto NormalizeType = [&SemaRef](QualType T) {
17337 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
17338 // The operator is valid on any address space for OpenCL.
17339 // Drop address space from actual and expected result types.
17340 if (const auto PtrTy = T->template getAs<PointerType>())
17341 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
17342 }
17343 return SemaRef.Context.getCanonicalType(T);
17344 };
17345
17346 const unsigned NumParams = FnDecl->getNumParams();
17347 unsigned FirstNonTypeParam = 0;
17348 bool MalformedTypeIdentity = false;
17349 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
17350 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
17351 unsigned MinimumMandatoryArgumentCount = 1;
17352 unsigned SizeParameterIndex = 0;
17353 if (IsPotentiallyTypeAware) {
17354 // We don't emit this diagnosis for template instantiations as we will
17355 // have already emitted it for the original template declaration.
17356 if (!FnDecl->isTemplateInstantiation())
17357 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
17358
17359 if (OperatorKind == AllocationOperatorKind::New) {
17360 SizeParameterIndex = 1;
17361 MinimumMandatoryArgumentCount =
17362 FunctionDecl::RequiredTypeAwareNewParameterCount;
17363 } else {
17364 SizeParameterIndex = 2;
17365 MinimumMandatoryArgumentCount =
17366 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
17367 }
17368 FirstNonTypeParam = 1;
17369 }
17370
17371 bool IsPotentiallyDestroyingDelete =
17372 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
17373
17374 if (IsPotentiallyDestroyingDelete) {
17375 ++MinimumMandatoryArgumentCount;
17376 ++SizeParameterIndex;
17377 }
17378
17379 if (NumParams < MinimumMandatoryArgumentCount)
17380 return SemaRef.Diag(Loc: FnDecl->getLocation(),
17381 DiagID: diag::err_operator_new_delete_too_few_parameters)
17382 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
17383 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
17384
17385 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
17386 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
17387 if (ParamDecl->hasDefaultArg())
17388 return SemaRef.Diag(Loc: FnDecl->getLocation(),
17389 DiagID: diag::err_operator_new_default_arg)
17390 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
17391 }
17392
17393 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
17394 QualType CanResultType = NormalizeType(FnType->getReturnType());
17395 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
17396 QualType CanExpectedSizeOrAddressParamType =
17397 NormalizeType(ExpectedSizeOrAddressParamType);
17398
17399 // Check that the result type is what we expect.
17400 if (CanResultType != CanExpectedResultType) {
17401 // Reject even if the type is dependent; an operator delete function is
17402 // required to have a non-dependent result type.
17403 return SemaRef.Diag(
17404 Loc: FnDecl->getLocation(),
17405 DiagID: CanResultType->isDependentType()
17406 ? diag::err_operator_new_delete_dependent_result_type
17407 : diag::err_operator_new_delete_invalid_result_type)
17408 << FnDecl->getDeclName() << ExpectedResultType;
17409 }
17410
17411 // A function template must have at least 2 parameters.
17412 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
17413 return SemaRef.Diag(Loc: FnDecl->getLocation(),
17414 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
17415 << FnDecl->getDeclName();
17416
17417 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
17418 auto FallbackType) -> bool {
17419 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
17420 if (ExpectedType.isNull()) {
17421 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
17422 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
17423 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
17424 << ParamDecl->getSourceRange();
17425 }
17426 CanQualType CanExpectedTy =
17427 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
17428 auto ActualParamType =
17429 NormalizeType(ParamDecl->getType().getUnqualifiedType());
17430 if (ActualParamType == CanExpectedTy)
17431 return false;
17432 unsigned Diagnostic = ActualParamType->isDependentType()
17433 ? DependentParamTypeDiag
17434 : InvalidParamTypeDiag;
17435 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
17436 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
17437 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
17438 << FallbackType << ParamDecl->getSourceRange();
17439 };
17440
17441 // Check that the first parameter type is what we expect.
17442 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
17443 return true;
17444
17445 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
17446
17447 // If the first parameter type is not a type-identity we're done, otherwise
17448 // we need to ensure the size and alignment parameters have the correct type
17449 if (!IsPotentiallyTypeAware)
17450 return false;
17451
17452 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
17453 return true;
17454 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
17455 CanQualType StdAlignValT =
17456 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
17457 : CanQualType();
17458 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
17459 return true;
17460
17461 FnDecl->setIsTypeAwareOperatorNewOrDelete();
17462 return MalformedTypeIdentity;
17463}
17464
17465static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
17466 // C++ [basic.stc.dynamic.allocation]p1:
17467 // A program is ill-formed if an allocation function is declared in a
17468 // namespace scope other than global scope or declared static in global
17469 // scope.
17470 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
17471 return true;
17472
17473 CanQualType SizeTy =
17474 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
17475
17476 // C++ [basic.stc.dynamic.allocation]p1:
17477 // The return type shall be void*. The first parameter shall have type
17478 // std::size_t.
17479 return CheckOperatorNewDeleteTypes(
17480 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
17481 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
17482 InvalidParamTypeDiag: diag::err_operator_new_param_type);
17483}
17484
17485static bool
17486CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
17487 // C++ [basic.stc.dynamic.deallocation]p1:
17488 // A program is ill-formed if deallocation functions are declared in a
17489 // namespace scope other than global scope or declared static in global
17490 // scope.
17491 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
17492 return true;
17493
17494 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
17495 auto ConstructDestroyingDeleteAddressType = [&]() {
17496 assert(MD);
17497 return SemaRef.Context.getPointerType(
17498 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
17499 };
17500
17501 // C++ P2719: A destroying operator delete cannot be type aware
17502 // so for QoL we actually check for this explicitly by considering
17503 // an destroying-delete appropriate address type and the presence of
17504 // any parameter of type destroying_delete_t as an erroneous attempt
17505 // to declare a type aware destroying delete, rather than emitting a
17506 // pile of incorrect parameter type errors.
17507 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
17508 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
17509 QualType AddressParamType =
17510 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
17511 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
17512 AddressParamType == ConstructDestroyingDeleteAddressType()) {
17513 // The address parameter type implies an author trying to construct a
17514 // type aware destroying delete, so we'll see if we can find a parameter
17515 // of type `std::destroying_delete_t`, and if we find it we'll report
17516 // this as being an attempt at a type aware destroying delete just stop
17517 // here. If we don't do this, the resulting incorrect parameter ordering
17518 // results in a pile mismatched argument type errors that don't explain
17519 // the core problem.
17520 for (auto Param : MD->parameters()) {
17521 if (isDestroyingDeleteT(Type: Param->getType())) {
17522 SemaRef.Diag(Loc: MD->getLocation(),
17523 DiagID: diag::err_type_aware_destroying_operator_delete)
17524 << Param->getSourceRange();
17525 return true;
17526 }
17527 }
17528 }
17529 }
17530
17531 // C++ P0722:
17532 // Within a class C, the first parameter of a destroying operator delete
17533 // shall be of type C *. The first parameter of any other deallocation
17534 // function shall be of type void *.
17535 CanQualType ExpectedAddressParamType =
17536 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
17537 ? SemaRef.Context.getPointerType(
17538 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
17539 : SemaRef.Context.VoidPtrTy;
17540
17541 // C++ [basic.stc.dynamic.deallocation]p2:
17542 // Each deallocation function shall return void
17543 if (CheckOperatorNewDeleteTypes(
17544 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
17545 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
17546 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
17547 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
17548 return true;
17549
17550 // C++ P0722:
17551 // A destroying operator delete shall be a usual deallocation function.
17552 if (MD && !MD->getParent()->isDependentContext() &&
17553 MD->isDestroyingOperatorDelete()) {
17554 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
17555 SemaRef.Diag(Loc: MD->getLocation(),
17556 DiagID: diag::err_destroying_operator_delete_not_usual);
17557 return true;
17558 }
17559 }
17560
17561 return false;
17562}
17563
17564bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
17565 assert(FnDecl && FnDecl->isOverloadedOperator() &&
17566 "Expected an overloaded operator declaration");
17567
17568 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
17569
17570 // C++ [over.oper]p5:
17571 // The allocation and deallocation functions, operator new,
17572 // operator new[], operator delete and operator delete[], are
17573 // described completely in 3.7.3. The attributes and restrictions
17574 // found in the rest of this subclause do not apply to them unless
17575 // explicitly stated in 3.7.3.
17576 if (Op == OO_Delete || Op == OO_Array_Delete)
17577 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
17578
17579 if (Op == OO_New || Op == OO_Array_New)
17580 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
17581
17582 // C++ [over.oper]p7:
17583 // An operator function shall either be a member function or
17584 // be a non-member function and have at least one parameter
17585 // whose type is a class, a reference to a class, an enumeration,
17586 // or a reference to an enumeration.
17587 // Note: Before C++23, a member function could not be static. The only member
17588 // function allowed to be static is the call operator function.
17589 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
17590 if (MethodDecl->isStatic()) {
17591 if (Op == OO_Call || Op == OO_Subscript)
17592 DiagCompat(Loc: FnDecl->getLocation(), CompatDiagId: diag_compat::operator_overload_static)
17593 << FnDecl;
17594 else
17595 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
17596 << FnDecl;
17597 }
17598 } else {
17599 bool ClassOrEnumParam = false;
17600 for (auto *Param : FnDecl->parameters()) {
17601 QualType ParamType = Param->getType().getNonReferenceType();
17602 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17603 ParamType->isEnumeralType()) {
17604 ClassOrEnumParam = true;
17605 break;
17606 }
17607 }
17608
17609 if (!ClassOrEnumParam)
17610 return Diag(Loc: FnDecl->getLocation(),
17611 DiagID: diag::err_operator_overload_needs_class_or_enum)
17612 << FnDecl->getDeclName();
17613 }
17614
17615 // C++ [over.oper]p8:
17616 // An operator function cannot have default arguments (8.3.6),
17617 // except where explicitly stated below.
17618 //
17619 // Only the function-call operator (C++ [over.call]p1) and the subscript
17620 // operator (CWG2507) allow default arguments.
17621 if (Op != OO_Call) {
17622 ParmVarDecl *FirstDefaultedParam = nullptr;
17623 for (auto *Param : FnDecl->parameters()) {
17624 if (Param->hasDefaultArg()) {
17625 FirstDefaultedParam = Param;
17626 break;
17627 }
17628 }
17629 if (FirstDefaultedParam) {
17630 if (Op == OO_Subscript) {
17631 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17632 ? diag::ext_subscript_overload
17633 : diag::error_subscript_overload)
17634 << FnDecl->getDeclName() << 1
17635 << FirstDefaultedParam->getDefaultArgRange();
17636 } else {
17637 return Diag(Loc: FirstDefaultedParam->getLocation(),
17638 DiagID: diag::err_operator_overload_default_arg)
17639 << FnDecl->getDeclName()
17640 << FirstDefaultedParam->getDefaultArgRange();
17641 }
17642 }
17643 }
17644
17645 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17646 { false, false, false }
17647#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17648 , { Unary, Binary, MemberOnly }
17649#include "clang/Basic/OperatorKinds.def"
17650 };
17651
17652 bool CanBeUnaryOperator = OperatorUses[Op][0];
17653 bool CanBeBinaryOperator = OperatorUses[Op][1];
17654 bool MustBeMemberOperator = OperatorUses[Op][2];
17655
17656 // C++ [over.oper]p8:
17657 // [...] Operator functions cannot have more or fewer parameters
17658 // than the number required for the corresponding operator, as
17659 // described in the rest of this subclause.
17660 unsigned NumParams = FnDecl->getNumParams() +
17661 (isa<CXXMethodDecl>(Val: FnDecl) &&
17662 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17663 ? 1
17664 : 0);
17665 if (Op != OO_Call && Op != OO_Subscript &&
17666 ((NumParams == 1 && !CanBeUnaryOperator) ||
17667 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17668 (NumParams > 2))) {
17669 // We have the wrong number of parameters.
17670 unsigned ErrorKind;
17671 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17672 ErrorKind = 2; // 2 -> unary or binary.
17673 } else if (CanBeUnaryOperator) {
17674 ErrorKind = 0; // 0 -> unary
17675 } else {
17676 assert(CanBeBinaryOperator &&
17677 "All non-call overloaded operators are unary or binary!");
17678 ErrorKind = 1; // 1 -> binary
17679 }
17680 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17681 << FnDecl->getDeclName() << NumParams << ErrorKind;
17682 }
17683
17684 if (Op == OO_Subscript && NumParams != 2) {
17685 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17686 ? diag::ext_subscript_overload
17687 : diag::error_subscript_overload)
17688 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17689 }
17690
17691 // Overloaded operators other than operator() and operator[] cannot be
17692 // variadic.
17693 if (Op != OO_Call &&
17694 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17695 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17696 << FnDecl->getDeclName();
17697 }
17698
17699 // Some operators must be member functions.
17700 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17701 return Diag(Loc: FnDecl->getLocation(),
17702 DiagID: diag::err_operator_overload_must_be_member)
17703 << FnDecl->getDeclName();
17704 }
17705
17706 // C++ [over.inc]p1:
17707 // The user-defined function called operator++ implements the
17708 // prefix and postfix ++ operator. If this function is a member
17709 // function with no parameters, or a non-member function with one
17710 // parameter of class or enumeration type, it defines the prefix
17711 // increment operator ++ for objects of that type. If the function
17712 // is a member function with one parameter (which shall be of type
17713 // int) or a non-member function with two parameters (the second
17714 // of which shall be of type int), it defines the postfix
17715 // increment operator ++ for objects of that type.
17716 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17717 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17718 QualType ParamType = LastParam->getType();
17719
17720 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17721 !ParamType->isDependentType())
17722 return Diag(Loc: LastParam->getLocation(),
17723 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17724 << LastParam->getType() << (Op == OO_MinusMinus);
17725 }
17726
17727 return false;
17728}
17729
17730static bool
17731checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17732 FunctionTemplateDecl *TpDecl) {
17733 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17734
17735 // Must have one or two template parameters.
17736 if (TemplateParams->size() == 1) {
17737 NonTypeTemplateParmDecl *PmDecl =
17738 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17739
17740 // The template parameter must be a char parameter pack.
17741 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17742 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17743 return false;
17744
17745 // C++20 [over.literal]p5:
17746 // A string literal operator template is a literal operator template
17747 // whose template-parameter-list comprises a single non-type
17748 // template-parameter of class type.
17749 //
17750 // As a DR resolution, we also allow placeholders for deduced class
17751 // template specializations.
17752 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17753 !PmDecl->isTemplateParameterPack() &&
17754 (PmDecl->getType()->isRecordType() ||
17755 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17756 return false;
17757 } else if (TemplateParams->size() == 2) {
17758 TemplateTypeParmDecl *PmType =
17759 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17760 NonTypeTemplateParmDecl *PmArgs =
17761 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17762
17763 // The second template parameter must be a parameter pack with the
17764 // first template parameter as its type.
17765 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17766 PmArgs->isTemplateParameterPack()) {
17767 if (const auto *TArgs =
17768 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17769 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17770 TArgs->getIndex() == PmType->getIndex()) {
17771 if (!SemaRef.inTemplateInstantiation())
17772 SemaRef.Diag(Loc: TpDecl->getLocation(),
17773 DiagID: diag::ext_string_literal_operator_template);
17774 return false;
17775 }
17776 }
17777 }
17778
17779 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17780 DiagID: diag::err_literal_operator_template)
17781 << TpDecl->getTemplateParameters()->getSourceRange();
17782 return true;
17783}
17784
17785bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17786 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17787 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17788 << FnDecl->getDeclName();
17789 return true;
17790 }
17791
17792 if (FnDecl->isExternC()) {
17793 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17794 if (const LinkageSpecDecl *LSD =
17795 FnDecl->getDeclContext()->getExternCContext())
17796 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17797 return true;
17798 }
17799
17800 // This might be the definition of a literal operator template.
17801 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17802
17803 // This might be a specialization of a literal operator template.
17804 if (!TpDecl)
17805 TpDecl = FnDecl->getPrimaryTemplate();
17806
17807 // template <char...> type operator "" name() and
17808 // template <class T, T...> type operator "" name() are the only valid
17809 // template signatures, and the only valid signatures with no parameters.
17810 //
17811 // C++20 also allows template <SomeClass T> type operator "" name().
17812 if (TpDecl) {
17813 if (FnDecl->param_size() != 0) {
17814 Diag(Loc: FnDecl->getLocation(),
17815 DiagID: diag::err_literal_operator_template_with_params);
17816 return true;
17817 }
17818
17819 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17820 return true;
17821
17822 } else if (FnDecl->param_size() == 1) {
17823 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17824
17825 QualType ParamType = Param->getType().getUnqualifiedType();
17826
17827 // Only unsigned long long int, long double, any character type, and const
17828 // char * are allowed as the only parameters.
17829 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17830 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17831 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17832 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17833 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17834 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17835 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17836 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17837 QualType InnerType = Ptr->getPointeeType();
17838
17839 // Pointer parameter must be a const char *.
17840 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17841 T2: Context.CharTy) &&
17842 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17843 Diag(Loc: Param->getSourceRange().getBegin(),
17844 DiagID: diag::err_literal_operator_param)
17845 << ParamType << "'const char *'" << Param->getSourceRange();
17846 return true;
17847 }
17848
17849 } else if (ParamType->isRealFloatingType()) {
17850 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17851 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17852 return true;
17853
17854 } else if (ParamType->isIntegerType()) {
17855 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17856 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17857 return true;
17858
17859 } else {
17860 Diag(Loc: Param->getSourceRange().getBegin(),
17861 DiagID: diag::err_literal_operator_invalid_param)
17862 << ParamType << Param->getSourceRange();
17863 return true;
17864 }
17865
17866 } else if (FnDecl->param_size() == 2) {
17867 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17868
17869 // First, verify that the first parameter is correct.
17870
17871 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17872
17873 // Two parameter function must have a pointer to const as a
17874 // first parameter; let's strip those qualifiers.
17875 const PointerType *PT = FirstParamType->getAs<PointerType>();
17876
17877 if (!PT) {
17878 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17879 DiagID: diag::err_literal_operator_param)
17880 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17881 return true;
17882 }
17883
17884 QualType PointeeType = PT->getPointeeType();
17885 // First parameter must be const
17886 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17887 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17888 DiagID: diag::err_literal_operator_param)
17889 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17890 return true;
17891 }
17892
17893 QualType InnerType = PointeeType.getUnqualifiedType();
17894 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17895 // const char32_t* are allowed as the first parameter to a two-parameter
17896 // function
17897 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17898 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17899 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17900 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17901 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17902 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17903 DiagID: diag::err_literal_operator_param)
17904 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17905 return true;
17906 }
17907
17908 // Move on to the second and final parameter.
17909 ++Param;
17910
17911 // The second parameter must be a std::size_t.
17912 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17913 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17914 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17915 DiagID: diag::err_literal_operator_param)
17916 << SecondParamType << Context.getSizeType()
17917 << (*Param)->getSourceRange();
17918 return true;
17919 }
17920 } else {
17921 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17922 return true;
17923 }
17924
17925 // Parameters are good.
17926
17927 // A parameter-declaration-clause containing a default argument is not
17928 // equivalent to any of the permitted forms.
17929 for (auto *Param : FnDecl->parameters()) {
17930 if (Param->hasDefaultArg()) {
17931 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17932 DiagID: diag::err_literal_operator_default_argument)
17933 << Param->getDefaultArgRange();
17934 break;
17935 }
17936 }
17937
17938 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17939 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17940 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17941 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17942 // C++23 [usrlit.suffix]p1:
17943 // Literal suffix identifiers that do not start with an underscore are
17944 // reserved for future standardization. Literal suffix identifiers that
17945 // contain a double underscore __ are reserved for use by C++
17946 // implementations.
17947 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17948 << static_cast<int>(Status)
17949 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17950 }
17951
17952 return false;
17953}
17954
17955Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17956 Expr *LangStr,
17957 SourceLocation LBraceLoc) {
17958 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17959 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17960
17961 StringRef Lang = Lit->getString();
17962 LinkageSpecLanguageIDs Language;
17963 if (Lang == "C")
17964 Language = LinkageSpecLanguageIDs::C;
17965 else if (Lang == "C++")
17966 Language = LinkageSpecLanguageIDs::CXX;
17967 else {
17968 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17969 << LangStr->getSourceRange();
17970 return nullptr;
17971 }
17972
17973 // FIXME: Add all the various semantics of linkage specifications
17974
17975 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17976 LangLoc: LangStr->getExprLoc(), Lang: Language,
17977 HasBraces: LBraceLoc.isValid());
17978
17979 /// C++ [module.unit]p7.2.3
17980 /// - Otherwise, if the declaration
17981 /// - ...
17982 /// - ...
17983 /// - appears within a linkage-specification,
17984 /// it is attached to the global module.
17985 ///
17986 /// If the declaration is already in global module fragment, we don't
17987 /// need to attach it again.
17988 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17989 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17990 D->setLocalOwningModule(GlobalModule);
17991 }
17992
17993 CurContext->addDecl(D);
17994 PushDeclContext(S, DC: D);
17995 return D;
17996}
17997
17998Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17999 Decl *LinkageSpec,
18000 SourceLocation RBraceLoc) {
18001 if (RBraceLoc.isValid()) {
18002 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
18003 LSDecl->setRBraceLoc(RBraceLoc);
18004 }
18005
18006 // If the current module doesn't has Parent, it implies that the
18007 // LinkageSpec isn't in the module created by itself. So we don't
18008 // need to pop it.
18009 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
18010 getCurrentModule()->isImplicitGlobalModule() &&
18011 getCurrentModule()->Parent)
18012 PopImplicitGlobalModuleFragment();
18013
18014 PopDeclContext();
18015 return LinkageSpec;
18016}
18017
18018Decl *Sema::ActOnEmptyDeclaration(Scope *S,
18019 const ParsedAttributesView &AttrList,
18020 SourceLocation SemiLoc) {
18021 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
18022 // Attribute declarations appertain to empty declaration so we handle
18023 // them here.
18024 ProcessDeclAttributeList(S, D: ED, AttrList);
18025
18026 CurContext->addDecl(D: ED);
18027 return ED;
18028}
18029
18030VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
18031 SourceLocation StartLoc,
18032 SourceLocation Loc,
18033 const IdentifierInfo *Name) {
18034 bool Invalid = false;
18035 QualType ExDeclType = TInfo->getType();
18036
18037 // Arrays and functions decay.
18038 if (ExDeclType->isArrayType())
18039 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
18040 else if (ExDeclType->isFunctionType())
18041 ExDeclType = Context.getPointerType(T: ExDeclType);
18042
18043 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
18044 // The exception-declaration shall not denote a pointer or reference to an
18045 // incomplete type, other than [cv] void*.
18046 // N2844 forbids rvalue references.
18047 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
18048 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
18049 Invalid = true;
18050 }
18051
18052 if (ExDeclType->isVariablyModifiedType()) {
18053 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
18054 Invalid = true;
18055 }
18056
18057 QualType BaseType = ExDeclType;
18058 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
18059 unsigned DK = diag::err_catch_incomplete;
18060 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
18061 BaseType = Ptr->getPointeeType();
18062 Mode = 1;
18063 DK = diag::err_catch_incomplete_ptr;
18064 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
18065 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
18066 BaseType = Ref->getPointeeType();
18067 Mode = 2;
18068 DK = diag::err_catch_incomplete_ref;
18069 }
18070 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
18071 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
18072 Invalid = true;
18073
18074 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
18075 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
18076 Invalid = true;
18077 }
18078
18079 // Reject catch types that need a cross-AS conversion.
18080 // cause runtimes don't yet support cross-address-
18081 // space conversions
18082 if (Mode == 1) {
18083 if (ExDeclType.getAddressSpace() != LangAS::Default ||
18084 BaseType.getAddressSpace() != LangAS::Default) {
18085 Diag(Loc, DiagID: diag::err_throw_or_catch_address_space_qualified_ptr)
18086 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
18087 Invalid = true;
18088 }
18089 } else if (Mode == 2) {
18090 if (const PointerType *PT = BaseType->getAs<PointerType>();
18091 PT && (BaseType.getAddressSpace() != LangAS::Default ||
18092 PT->getPointeeType().getAddressSpace() != LangAS::Default)) {
18093 Diag(Loc, DiagID: diag::err_throw_or_catch_address_space_qualified_ptr)
18094 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
18095 Invalid = true;
18096 } else if (BaseType.getAddressSpace() != LangAS::Default) {
18097 Diag(Loc, DiagID: diag::err_throw_or_catch_address_space_qualified_ptr)
18098 << /*IsCatch=*/1 << /*IsRef=*/1 << ExDeclType;
18099 Invalid = true;
18100 }
18101 }
18102
18103 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
18104 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
18105 Invalid = true;
18106 }
18107
18108 if (!Invalid && !ExDeclType->isDependentType() &&
18109 RequireNonAbstractType(Loc, T: ExDeclType,
18110 DiagID: diag::err_abstract_type_in_decl,
18111 Args: AbstractVariableType))
18112 Invalid = true;
18113
18114 // Only the non-fragile NeXT runtime currently supports C++ catches
18115 // of ObjC types, and no runtime supports catching ObjC types by value.
18116 if (!Invalid && getLangOpts().ObjC) {
18117 QualType T = ExDeclType;
18118 if (const ReferenceType *RT = T->getAs<ReferenceType>())
18119 T = RT->getPointeeType();
18120
18121 if (T->isObjCObjectType()) {
18122 Diag(Loc, DiagID: diag::err_objc_object_catch);
18123 Invalid = true;
18124 } else if (T->isObjCObjectPointerType()) {
18125 // FIXME: should this be a test for macosx-fragile specifically?
18126 if (getLangOpts().ObjCRuntime.isFragile())
18127 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
18128 }
18129 }
18130
18131 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
18132 T: ExDeclType, TInfo, S: SC_None);
18133 ExDecl->setExceptionVariable(true);
18134
18135 // In ARC, infer 'retaining' for variables of retainable type.
18136 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
18137 Invalid = true;
18138
18139 if (!Invalid && !ExDeclType->isDependentType()) {
18140 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
18141 // Insulate this from anything else we might currently be parsing.
18142 EnterExpressionEvaluationContext scope(
18143 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
18144
18145 // C++ [except.handle]p16:
18146 // The object declared in an exception-declaration or, if the
18147 // exception-declaration does not specify a name, a temporary (12.2) is
18148 // copy-initialized (8.5) from the exception object. [...]
18149 // The object is destroyed when the handler exits, after the destruction
18150 // of any automatic objects initialized within the handler.
18151 //
18152 // We just pretend to initialize the object with itself, then make sure
18153 // it can be destroyed later.
18154 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
18155
18156 InitializedEntity entity =
18157 InitializedEntity::InitializeVariable(Var: ExDecl);
18158 InitializationKind initKind =
18159 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
18160
18161 Expr *opaqueValue =
18162 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
18163 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
18164 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
18165 if (result.isInvalid())
18166 Invalid = true;
18167 else {
18168 // If the constructor used was non-trivial, set this as the
18169 // "initializer".
18170 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
18171 if (!construct->getConstructor()->isTrivial()) {
18172 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
18173 ExDecl->setInit(init);
18174 }
18175
18176 // And make sure it's destructable.
18177 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
18178 }
18179 }
18180 }
18181
18182 if (Invalid)
18183 ExDecl->setInvalidDecl();
18184
18185 return ExDecl;
18186}
18187
18188Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
18189 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18190 bool Invalid = D.isInvalidType();
18191
18192 // Check for unexpanded parameter packs.
18193 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
18194 UPPC: UPPC_ExceptionType)) {
18195 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
18196 Loc: D.getIdentifierLoc());
18197 Invalid = true;
18198 }
18199
18200 const IdentifierInfo *II = D.getIdentifier();
18201 if (NamedDecl *PrevDecl =
18202 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
18203 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
18204 // The scope should be freshly made just for us. There is just no way
18205 // it contains any previous declaration, except for function parameters in
18206 // a function-try-block's catch statement.
18207 assert(!S->isDeclScope(PrevDecl));
18208 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
18209 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
18210 << D.getIdentifier();
18211 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
18212 Invalid = true;
18213 } else if (PrevDecl->isTemplateParameter())
18214 // Maybe we will complain about the shadowed template parameter.
18215 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
18216 }
18217
18218 if (D.getCXXScopeSpec().isSet() && !Invalid) {
18219 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
18220 << D.getCXXScopeSpec().getRange();
18221 Invalid = true;
18222 }
18223
18224 VarDecl *ExDecl = BuildExceptionDeclaration(
18225 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
18226 if (Invalid)
18227 ExDecl->setInvalidDecl();
18228
18229 // Add the exception declaration into this scope.
18230 if (II)
18231 PushOnScopeChains(D: ExDecl, S);
18232 else
18233 CurContext->addDecl(D: ExDecl);
18234
18235 ProcessDeclAttributes(S, D: ExDecl, PD: D);
18236 return ExDecl;
18237}
18238
18239Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
18240 Expr *AssertExpr,
18241 Expr *AssertMessageExpr,
18242 SourceLocation RParenLoc) {
18243 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
18244 return nullptr;
18245
18246 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
18247 AssertMessageExpr, RParenLoc, Failed: false);
18248}
18249
18250static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
18251 switch (BTK) {
18252 case BuiltinType::Char_S:
18253 case BuiltinType::Char_U:
18254 break;
18255 case BuiltinType::Char8:
18256 OS << "u8";
18257 break;
18258 case BuiltinType::Char16:
18259 OS << 'u';
18260 break;
18261 case BuiltinType::Char32:
18262 OS << 'U';
18263 break;
18264 case BuiltinType::WChar_S:
18265 case BuiltinType::WChar_U:
18266 OS << 'L';
18267 break;
18268 default:
18269 llvm_unreachable("Non-character type");
18270 }
18271}
18272
18273/// Convert character's value, interpreted as a code unit, to a string.
18274/// The value needs to be zero-extended to 32-bits.
18275/// FIXME: This assumes Unicode literal encodings
18276static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
18277 unsigned TyWidth,
18278 SmallVectorImpl<char> &Str) {
18279 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
18280 char *Ptr = Arr;
18281 BuiltinType::Kind K = BTy->getKind();
18282 llvm::raw_svector_ostream OS(Str);
18283
18284 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
18285 // other types.
18286 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
18287 K == BuiltinType::Char8 || Value <= 0x7F) {
18288 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
18289 if (!Escaped.empty())
18290 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
18291 else
18292 OS << static_cast<char>(Value);
18293 return;
18294 }
18295
18296 switch (K) {
18297 case BuiltinType::Char16:
18298 case BuiltinType::Char32:
18299 case BuiltinType::WChar_S:
18300 case BuiltinType::WChar_U: {
18301 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
18302 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
18303 else
18304 OS << "\\x"
18305 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
18306 break;
18307 }
18308 default:
18309 llvm_unreachable("Non-character type is passed");
18310 }
18311}
18312
18313/// Convert \V to a string we can present to the user in a diagnostic
18314/// \T is the type of the expression that has been evaluated into \V
18315static bool ConvertAPValueToString(const APValue &V, QualType T,
18316 SmallVectorImpl<char> &Str,
18317 ASTContext &Context) {
18318 if (!V.hasValue())
18319 return false;
18320
18321 switch (V.getKind()) {
18322 case APValue::ValueKind::Int:
18323 if (T->isBooleanType()) {
18324 // Bools are reduced to ints during evaluation, but for
18325 // diagnostic purposes we want to print them as
18326 // true or false.
18327 int64_t BoolValue = V.getInt().getExtValue();
18328 assert((BoolValue == 0 || BoolValue == 1) &&
18329 "Bool type, but value is not 0 or 1");
18330 llvm::raw_svector_ostream OS(Str);
18331 OS << (BoolValue ? "true" : "false");
18332 } else {
18333 llvm::raw_svector_ostream OS(Str);
18334 // Same is true for chars.
18335 // We want to print the character representation for textual types
18336 const auto *BTy = T->getAs<BuiltinType>();
18337 if (BTy) {
18338 switch (BTy->getKind()) {
18339 case BuiltinType::Char_S:
18340 case BuiltinType::Char_U:
18341 case BuiltinType::Char8:
18342 case BuiltinType::Char16:
18343 case BuiltinType::Char32:
18344 case BuiltinType::WChar_S:
18345 case BuiltinType::WChar_U: {
18346 unsigned TyWidth = Context.getIntWidth(T);
18347 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
18348 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
18349 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
18350 OS << '\'';
18351 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
18352 OS << "' (0x"
18353 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
18354 /*Upper=*/true)
18355 << ", " << V.getInt() << ')';
18356 return true;
18357 }
18358 default:
18359 break;
18360 }
18361 }
18362 V.getInt().toString(Str);
18363 }
18364
18365 break;
18366
18367 case APValue::ValueKind::Float:
18368 V.getFloat().toString(Str);
18369 break;
18370
18371 case APValue::ValueKind::LValue:
18372 if (V.isNullPointer()) {
18373 llvm::raw_svector_ostream OS(Str);
18374 OS << "nullptr";
18375 } else
18376 return false;
18377 break;
18378
18379 case APValue::ValueKind::ComplexFloat: {
18380 llvm::raw_svector_ostream OS(Str);
18381 OS << '(';
18382 V.getComplexFloatReal().toString(Str);
18383 OS << " + ";
18384 V.getComplexFloatImag().toString(Str);
18385 OS << "i)";
18386 } break;
18387
18388 case APValue::ValueKind::ComplexInt: {
18389 llvm::raw_svector_ostream OS(Str);
18390 OS << '(';
18391 V.getComplexIntReal().toString(Str);
18392 OS << " + ";
18393 V.getComplexIntImag().toString(Str);
18394 OS << "i)";
18395 } break;
18396
18397 default:
18398 return false;
18399 }
18400
18401 return true;
18402}
18403
18404/// Some Expression types are not useful to print notes about,
18405/// e.g. literals and values that have already been expanded
18406/// before such as int-valued template parameters.
18407static bool UsefulToPrintExpr(const Expr *E) {
18408 E = E->IgnoreParenImpCasts();
18409 // Literals are pretty easy for humans to understand.
18410 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
18411 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
18412 return false;
18413
18414 // These have been substituted from template parameters
18415 // and appear as literals in the static assert error.
18416 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
18417 return false;
18418
18419 // -5 is also simple to understand.
18420 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
18421 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
18422
18423 // Only print nested arithmetic operators.
18424 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
18425 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
18426 BO->isBitwiseOp());
18427
18428 return true;
18429}
18430
18431void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
18432 // FIXME: Should we also ignore explicit casts?
18433 E = E->IgnoreParenImpCasts();
18434 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
18435 Op && Op->getOpcode() != BO_LOr) {
18436 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
18437 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
18438
18439 // Ignore comparisons of boolean expressions with a boolean literal.
18440 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
18441 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
18442 return;
18443
18444 // Don't print obvious expressions.
18445 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
18446 return;
18447
18448 struct {
18449 const clang::Expr *Cond;
18450 Expr::EvalResult Result;
18451 SmallString<12> ValueString;
18452 bool Print;
18453 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
18454 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
18455 for (auto &DiagSide : DiagSides) {
18456 const Expr *Side = DiagSide.Cond;
18457
18458 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
18459
18460 DiagSide.Print = ConvertAPValueToString(
18461 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
18462 }
18463 if (DiagSides[0].Print && DiagSides[1].Print) {
18464 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
18465 << DiagSides[0].ValueString << Op->getOpcodeStr()
18466 << DiagSides[1].ValueString << Op->getSourceRange();
18467 }
18468 } else if (const auto *RE = dyn_cast<RequiresExpr>(Val: E)) {
18469 DiagnoseUnsatisfiedRequiresExpr(RequiresExpr: RE);
18470 } else {
18471 DiagnoseTypeTraitDetails(E);
18472 }
18473}
18474
18475template <typename ResultType>
18476static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
18477 ResultType &Result, ASTContext &Ctx,
18478 Sema::StringEvaluationContext EvalContext,
18479 bool ErrorOnInvalidMessage) {
18480
18481 assert(Message);
18482 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
18483 "can't evaluate a dependant static assert message");
18484
18485 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
18486 assert(SL->isUnevaluated() && "expected an unevaluated string");
18487 if constexpr (std::is_same_v<APValue, ResultType>) {
18488 Result =
18489 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
18490 const ConstantArrayType *CAT =
18491 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
18492 assert(CAT && "string literal isn't an array");
18493 QualType CharType = CAT->getElementType();
18494 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
18495 CharType->isUnsignedIntegerType());
18496 for (unsigned I = 0; I < SL->getLength(); I++) {
18497 Value = SL->getCodeUnit(I);
18498 Result.getArrayInitializedElt(I) = APValue(Value);
18499 }
18500 } else {
18501 Result.assign(SL->getString().begin(), SL->getString().end());
18502 }
18503 return true;
18504 }
18505
18506 SourceLocation Loc = Message->getBeginLoc();
18507 QualType T = Message->getType().getNonReferenceType();
18508 auto *RD = T->getAsCXXRecordDecl();
18509 if (!RD) {
18510 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
18511 return false;
18512 }
18513
18514 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
18515 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
18516 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
18517 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
18518 if (MemberLookup.empty())
18519 return std::nullopt;
18520 return std::move(MemberLookup);
18521 };
18522
18523 std::optional<LookupResult> SizeMember = FindMember("size");
18524 std::optional<LookupResult> DataMember = FindMember("data");
18525 if (!SizeMember || !DataMember) {
18526 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
18527 << EvalContext
18528 << ((!SizeMember && !DataMember) ? 2
18529 : !SizeMember ? 0
18530 : 1);
18531 return false;
18532 }
18533
18534 auto BuildExpr = [&](LookupResult &LR) {
18535 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
18536 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
18537 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
18538 if (Res.isInvalid())
18539 return ExprError();
18540 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
18541 IsExecConfig: false, AllowRecovery: true);
18542 if (Res.isInvalid())
18543 return ExprError();
18544 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
18545 return ExprError();
18546 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
18547 };
18548
18549 ExprResult SizeE = BuildExpr(*SizeMember);
18550 ExprResult DataE = BuildExpr(*DataMember);
18551
18552 QualType SizeT = SemaRef.Context.getSizeType();
18553 QualType ConstCharPtr = SemaRef.Context.getPointerType(
18554 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
18555
18556 ExprResult EvaluatedSize =
18557 SizeE.isInvalid()
18558 ? ExprError()
18559 : SemaRef.BuildConvertedConstantExpression(
18560 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
18561 if (EvaluatedSize.isInvalid()) {
18562 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18563 << EvalContext << /*size*/ 0;
18564 return false;
18565 }
18566
18567 ExprResult EvaluatedData =
18568 DataE.isInvalid()
18569 ? ExprError()
18570 : SemaRef.BuildConvertedConstantExpression(
18571 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
18572 if (EvaluatedData.isInvalid()) {
18573 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18574 << EvalContext << /*data*/ 1;
18575 return false;
18576 }
18577
18578 if (!ErrorOnInvalidMessage &&
18579 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
18580 return true;
18581
18582 Expr::EvalResult Status;
18583 SmallVector<PartialDiagnosticAt, 8> Notes;
18584 Status.Diag = &Notes;
18585 sema::EvalProxy SProxy(SemaRef);
18586 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18587 EvaluatedData.get(), Ctx, SProxy,
18588 Status) ||
18589 !Notes.empty()) {
18590 SemaRef.Diag(Loc: Message->getBeginLoc(),
18591 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18592 : diag::warn_user_defined_msg_constexpr)
18593 << EvalContext;
18594 for (const auto &Note : Notes)
18595 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18596 return !ErrorOnInvalidMessage;
18597 }
18598 return true;
18599}
18600
18601bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
18602 StringEvaluationContext EvalContext,
18603 bool ErrorOnInvalidMessage) {
18604 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18605 ErrorOnInvalidMessage);
18606}
18607
18608bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18609 StringEvaluationContext EvalContext,
18610 bool ErrorOnInvalidMessage) {
18611 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18612 ErrorOnInvalidMessage);
18613}
18614
18615Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
18616 Expr *AssertExpr, Expr *AssertMessage,
18617 SourceLocation RParenLoc,
18618 bool Failed) {
18619 assert(AssertExpr != nullptr && "Expected non-null condition");
18620 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18621 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18622 !AssertMessage->isValueDependent())) &&
18623 !Failed) {
18624 // In a static_assert-declaration, the constant-expression shall be a
18625 // constant expression that can be contextually converted to bool.
18626 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
18627 if (Converted.isInvalid())
18628 Failed = true;
18629
18630 ExprResult FullAssertExpr =
18631 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
18632 /*DiscardedValue*/ false,
18633 /*IsConstexpr*/ true);
18634 if (FullAssertExpr.isInvalid())
18635 Failed = true;
18636 else
18637 AssertExpr = FullAssertExpr.get();
18638
18639 llvm::APSInt Cond;
18640 Expr *BaseExpr = AssertExpr;
18641 AllowFoldKind FoldKind = AllowFoldKind::No;
18642
18643 if (!getLangOpts().CPlusPlus) {
18644 // In C mode, allow folding as an extension for better compatibility with
18645 // C++ in terms of expressions like static_assert("test") or
18646 // static_assert(nullptr).
18647 FoldKind = AllowFoldKind::Allow;
18648 }
18649
18650 if (!Failed && VerifyIntegerConstantExpression(
18651 E: BaseExpr, Result: &Cond,
18652 DiagID: diag::err_static_assert_expression_is_not_constant,
18653 CanFold: FoldKind).isInvalid())
18654 Failed = true;
18655
18656 // If the static_assert passes, only verify that
18657 // the message is grammatically valid without evaluating it.
18658 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18659 std::string Str;
18660 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18661 EvalContext: StringEvaluationContext::StaticAssert,
18662 /*ErrorOnInvalidMessage=*/false);
18663 }
18664
18665 // CWG2518
18666 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18667 // template definition, the declaration has no effect.
18668 bool InTemplateDefinition =
18669 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18670
18671 if (!Failed && !Cond && !InTemplateDefinition) {
18672 SmallString<256> MsgBuffer;
18673 llvm::raw_svector_ostream Msg(MsgBuffer);
18674 bool HasMessage = AssertMessage;
18675 if (AssertMessage) {
18676 std::string Str;
18677 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18678 EvalContext: StringEvaluationContext::StaticAssert,
18679 /*ErrorOnInvalidMessage=*/true) ||
18680 !Str.empty();
18681 Msg << Str;
18682 }
18683 Expr *InnerCond = nullptr;
18684 std::string InnerCondDescription;
18685 std::tie(args&: InnerCond, args&: InnerCondDescription) =
18686 findFailedBooleanCondition(Cond: Converted.get());
18687 if (const auto *ConceptIDExpr =
18688 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18689 const ASTConstraintSatisfaction &Satisfaction =
18690 ConceptIDExpr->getSatisfaction();
18691 if (!Satisfaction.containsErrors() || Satisfaction.record_size()) {
18692 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18693 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18694 // Drill down into concept specialization expressions to see why they
18695 // weren't satisfied.
18696 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18697 }
18698 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18699 !isa<IntegerLiteral>(Val: InnerCond)) {
18700 Diag(Loc: InnerCond->getBeginLoc(),
18701 DiagID: diag::err_static_assert_requirement_failed)
18702 << InnerCondDescription << !HasMessage << Msg.str()
18703 << InnerCond->getSourceRange();
18704 DiagnoseStaticAssertDetails(E: InnerCond);
18705 } else {
18706 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18707 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18708 PrintContextStack();
18709 }
18710 Failed = true;
18711 }
18712 } else {
18713 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18714 /*DiscardedValue*/false,
18715 /*IsConstexpr*/true);
18716 if (FullAssertExpr.isInvalid())
18717 Failed = true;
18718 else
18719 AssertExpr = FullAssertExpr.get();
18720 }
18721
18722 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18723 AssertExpr, Message: AssertMessage, RParenLoc,
18724 Failed);
18725
18726 CurContext->addDecl(D: Decl);
18727 return Decl;
18728}
18729
18730static QualType IgnorePackIndexing(QualType T) {
18731 if (const auto *PIT = dyn_cast<PackIndexingType>(Val&: T))
18732 return PIT->getPattern();
18733 return T;
18734}
18735
18736static const TemplateSpecializationType *
18737GetClassTemplateSpecializationType(ASTContext &Context, QualType T) {
18738 T = IgnorePackIndexing(T);
18739 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val&: T))
18740 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Ctx: Context);
18741
18742 const auto *TST = dyn_cast<TemplateSpecializationType>(Val&: T);
18743 if (!TST)
18744 return nullptr;
18745
18746 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18747 if (!TD || isa<ClassTemplateDecl>(Val: TD))
18748 return TST;
18749 return nullptr;
18750}
18751
18752bool Sema::DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
18753 NestedNameSpecifierLoc NNSLoc) {
18754 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18755 TL = TL.getPrefix().getAsTypeLoc()) {
18756 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18757 continue;
18758
18759 Diag(Loc, DiagID: diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18760 return true;
18761 }
18762 return false;
18763}
18764
18765static void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc,
18766 NestedNameSpecifier NNS) {
18767 QualType T(NNS.getAsType(), 0);
18768 if (const auto *TST =
18769 dyn_cast<TemplateSpecializationType>(Val: IgnorePackIndexing(T))) {
18770 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18771 Val: TST->getTemplateName().getAsTemplateDecl())) {
18772 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec)
18773 << NNS;
18774 return;
18775 }
18776 }
18777
18778 if (NNS.getAsRecordDecl()) {
18779 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18780 } else {
18781 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member);
18782 }
18783}
18784
18785bool Sema::CheckDependentFriend(SourceLocation Loc,
18786 NestedNameSpecifierLoc NNSLoc,
18787 ArrayRef<TemplateParameterList *> TPLs,
18788 bool IsInstantiation) {
18789 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
18790 if (!NNS.isDependent() && !IsInstantiation)
18791 return false;
18792
18793 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18794 "nested-name-specifier of dependent friend must be a type");
18795
18796 QualType T(NNS.getAsType(), 0);
18797 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18798 return true;
18799
18800 const TemplateSpecializationType *TST =
18801 GetClassTemplateSpecializationType(Context, T);
18802 if (!TST) {
18803 DiagnoseDependentFriendNotMember(S&: *this, Loc, NNS);
18804 return true;
18805 }
18806
18807 if (TPLs.empty())
18808 return false;
18809
18810 SmallVector<NamedDecl *, 4> UndeducedParameters;
18811 for (TemplateParameterList *Params : TPLs) {
18812 llvm::SmallBitVector UsedParameters(Params->size());
18813 MarkUsedTemplateParameters(TemplateArgs: TST->template_arguments(),
18814 /*OnlyDeduced=*/true, Depth: Params->getDepth(),
18815 Used&: UsedParameters);
18816
18817 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18818 if (!UsedParameters[I])
18819 UndeducedParameters.push_back(Elt: Params->getParam(Idx: I));
18820 }
18821
18822 if (UndeducedParameters.empty())
18823 return false;
18824
18825 Diag(Loc, DiagID: diag::err_dependent_friend_undeduced_params)
18826 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18827
18828 for (NamedDecl *Param : UndeducedParameters) {
18829 if (Param->getDeclName())
18830 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18831 << Param->getDeclName();
18832 else
18833 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18834 << "(anonymous)";
18835 }
18836
18837 return true;
18838}
18839
18840DeclResult Sema::ActOnTemplatedFriendTag(
18841 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18842 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18843 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18844 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18845 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18846
18847 bool IsMemberSpecialization = false;
18848 bool Invalid = false;
18849
18850 TemplateParameterList *TemplateParams =
18851 MatchTemplateParametersToScopeSpecifier(DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId,
18852 ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18853 IsMemberSpecialization, Invalid);
18854 if (TemplateId) {
18855 if (Invalid)
18856 return true;
18857
18858 if (TemplateParams) {
18859 Diag(Loc: NameLoc, DiagID: diag::err_not_class_template_specialization) << 0;
18860 return true;
18861 }
18862 }
18863
18864 if (TemplateParams) {
18865 if (TemplateParams->size() > 0) {
18866 if (Invalid)
18867 return true;
18868
18869 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18870 DeclResult Result = CheckClassTemplate(
18871 S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc, Attr,
18872 TemplateParams, AS: AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18873 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1, OuterTemplateParamLists: TempParamLists.data(),
18874 IsMemberSpecialization);
18875 return Result.get();
18876 }
18877 } else {
18878 // The "template<>" header is extraneous.
18879 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18880 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18881 }
18882 }
18883
18884 if (Invalid)
18885 return true;
18886
18887 bool IsAllExplicitSpecializations =
18888 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18889 return List->size() == 0;
18890 });
18891
18892 // FIXME: don't ignore attributes.
18893
18894 // If it's explicit specializations all the way down, just forget
18895 // about the template header and build an appropriate non-templated
18896 // friend. TODO: for source fidelity, remember the headers.
18897 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18898 if (!TemplateId && IsAllExplicitSpecializations) {
18899 if (SS.isEmpty()) {
18900 bool Owned = false;
18901 bool IsDependent = false;
18902 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18903 Attr, AS: AS_public,
18904 /*ModulePrivateLoc=*/SourceLocation(),
18905 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18906 /*ScopedEnumKWLoc=*/SourceLocation(),
18907 /*ScopedEnumUsesClassTag=*/false,
18908 /*UnderlyingType=*/TypeResult(),
18909 /*IsTypeSpecifier=*/false,
18910 /*IsTemplateParamOrArg=*/false,
18911 /*OOK=*/OffsetOfKind::Outside);
18912 }
18913
18914 TypeSourceInfo *TSI = nullptr;
18915 ElaboratedTypeKeyword Keyword =
18916 TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18917 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18918 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18919 if (T.isNull())
18920 return true;
18921
18922 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI,
18923 FriendL: FriendLoc, EllipsisLoc);
18924 Friend->setAccess(AS_public);
18925 CurContext->addDecl(D: Friend);
18926 return Friend;
18927 }
18928
18929 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18930
18931 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18932 if (TemplateParams)
18933 TPLs = TPLs.drop_back();
18934 if (CheckDependentFriend(Loc: TagLoc, NNSLoc: QualifierLoc, TPLs,
18935 /*IsInstantiation=*/false))
18936 return true;
18937
18938 TypeSourceInfo *TSI = nullptr;
18939 if (TemplateId) {
18940 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18941 TemplateId->NumArgs);
18942 TypeResult ParsedType = ActOnTagTemplateIdType(
18943 TUK: TagUseKind::Friend, TagSpec: static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18944 TemplateKWLoc: TemplateId->TemplateKWLoc, TemplateD: TemplateId->Template, TemplateLoc: NameLoc,
18945 LAngleLoc: TemplateId->LAngleLoc, TemplateArgsIn: ParsedArgs, RAngleLoc: TemplateId->RAngleLoc);
18946 if (ParsedType.isInvalid())
18947 return true;
18948
18949 GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TSI);
18950 } else {
18951 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18952 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18953 TSI = Context.CreateTypeSourceInfo(T);
18954
18955 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18956 TL.setElaboratedKeywordLoc(TagLoc);
18957 TL.setQualifierLoc(QualifierLoc);
18958 TL.setNameLoc(NameLoc);
18959 }
18960
18961 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18962 collectUnexpandedParameterPacks(TL: TSI->getTypeLoc(), Unexpanded);
18963 if (EllipsisLoc.isInvalid()) {
18964 if (DiagnoseUnexpandedParameterPack(Loc: TagLoc, T: TSI, UPPC: UPPC_FriendDeclaration))
18965 return true;
18966 } else if (Unexpanded.empty()) {
18967 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18968 << TSI->getTypeLoc().getSourceRange();
18969 return true;
18970 } else {
18971 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18972 // introduced by the template-declaration containing that specifier.
18973 if (!TempParamLists.empty()) {
18974 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18975 for (UnexpandedParameterPack &U : Unexpanded) {
18976 if (std::optional<std::pair<unsigned, unsigned>> DI =
18977 getDepthAndIndex(UPP: U);
18978 DI && DI->first >= FriendDeclDepth) {
18979 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18980 if (!ND)
18981 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18982 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18983 << ND->getDeclName()
18984 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18985 return true;
18986 }
18987 }
18988 }
18989 }
18990
18991 FriendDecl *Friend;
18992 if (TempParamLists.empty())
18993 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI, FriendL: FriendLoc,
18994 EllipsisLoc);
18995 else {
18996 if (CheckTemplateDeclScope(S, TemplateParams: TempParamLists.back()))
18997 return true;
18998
18999 TemplateName FriendTemplate;
19000 if (TemplateParams)
19001 FriendTemplate = Context.getDependentTemplateName(
19002 Name: {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
19003 Friend =
19004 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: NameLoc, Friend: TSI, FriendLoc,
19005 FriendTPLists: TempParamLists, EllipsisLoc, Template: FriendTemplate);
19006 }
19007
19008 Friend->setAccess(AS_public);
19009 CurContext->addDecl(D: Friend);
19010
19011 return Friend;
19012}
19013
19014Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
19015 MultiTemplateParamsArg TempParams,
19016 SourceLocation EllipsisLoc) {
19017 SourceLocation Loc = DS.getBeginLoc();
19018 SourceLocation FriendLoc = DS.getFriendSpecLoc();
19019
19020 assert(DS.isFriendSpecified());
19021 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
19022
19023 // C++ [class.friend]p3:
19024 // A friend declaration that does not declare a function shall have one of
19025 // the following forms:
19026 // friend elaborated-type-specifier ;
19027 // friend simple-type-specifier ;
19028 // friend typename-specifier ;
19029 //
19030 // If the friend keyword isn't first, or if the declarations has any type
19031 // qualifiers, then the declaration doesn't have that form.
19032 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
19033 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
19034 if (DS.getTypeQualifiers()) {
19035 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
19036 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
19037 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
19038 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
19039 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
19040 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
19041 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
19042 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
19043 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
19044 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
19045 }
19046
19047 // Try to convert the decl specifier to a type. This works for
19048 // friend templates because ActOnTag never produces a ClassTemplateDecl
19049 // for a TagUseKind::Friend.
19050 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
19051 DeclaratorContext::Member);
19052 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
19053 QualType T = TSI->getType();
19054 if (TheDeclarator.isInvalidType())
19055 return nullptr;
19056
19057 // If '...' is present, the type must contain an unexpanded parameter
19058 // pack, and vice versa.
19059 bool Invalid = false;
19060 if (EllipsisLoc.isInvalid() &&
19061 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
19062 return nullptr;
19063 if (EllipsisLoc.isValid() &&
19064 !TSI->getType()->containsUnexpandedParameterPack()) {
19065 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
19066 << TSI->getTypeLoc().getSourceRange();
19067 Invalid = true;
19068 }
19069
19070 if (!T->isElaboratedTypeSpecifier()) {
19071 if (TempParams.size()) {
19072 // C++23 [dcl.pre]p5:
19073 // In a simple-declaration, the optional init-declarator-list can be
19074 // omitted only when declaring a class or enumeration, that is, when
19075 // the decl-specifier-seq contains either a class-specifier, an
19076 // elaborated-type-specifier with a class-key, or an enum-specifier.
19077 //
19078 // The declaration of a template-declaration or explicit-specialization
19079 // is never a member-declaration, so this must be a simple-declaration
19080 // with no init-declarator-list. Therefore, this is ill-formed.
19081 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
19082 return nullptr;
19083 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
19084 SmallString<16> InsertionText(" ");
19085 InsertionText += RD->getKindName();
19086
19087 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
19088 ? diag::warn_cxx98_compat_unelaborated_friend_type
19089 : diag::ext_unelaborated_friend_type)
19090 << (unsigned)RD->getTagKind() << T
19091 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
19092 Code: InsertionText);
19093 } else {
19094 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
19095 << T << DS.getSourceRange();
19096 }
19097 }
19098
19099 // C++98 [class.friend]p1: A friend of a class is a function
19100 // or class that is not a member of the class . . .
19101 // This is fixed in DR77, which just barely didn't make the C++03
19102 // deadline. It's also a very silly restriction that seriously
19103 // affects inner classes and which nobody else seems to implement;
19104 // thus we never diagnose it, not even in -pedantic.
19105 //
19106 // But note that we could warn about it: it's always useless to
19107 // friend one of your own members (it's not, however, worthless to
19108 // friend a member of an arbitrary specialization of your template).
19109
19110 Decl *D;
19111 if (!TempParams.empty()) {
19112 if (CheckTemplateDeclScope(S, TemplateParams: TempParams.back()))
19113 return nullptr;
19114
19115 // TODO: Support variadic friend template decls?
19116 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Friend: TSI, FriendLoc,
19117 FriendTPLists: TempParams, EllipsisLoc);
19118 } else
19119 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
19120 Friend: TSI, FriendL: FriendLoc, EllipsisLoc);
19121
19122 if (!D)
19123 return nullptr;
19124
19125 D->setAccess(AS_public);
19126 CurContext->addDecl(D);
19127
19128 if (Invalid)
19129 D->setInvalidDecl();
19130
19131 return D;
19132}
19133
19134NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
19135 MultiTemplateParamsArg TemplateParams) {
19136 const DeclSpec &DS = D.getDeclSpec();
19137
19138 assert(DS.isFriendSpecified());
19139 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
19140
19141 SourceLocation Loc = D.getIdentifierLoc();
19142 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19143
19144 // C++ [class.friend]p1
19145 // A friend of a class is a function or class....
19146 // Note that this sees through typedefs, which is intended.
19147 // It *doesn't* see through dependent types, which is correct
19148 // according to [temp.arg.type]p3:
19149 // If a declaration acquires a function type through a
19150 // type dependent on a template-parameter and this causes
19151 // a declaration that does not use the syntactic form of a
19152 // function declarator to have a function type, the program
19153 // is ill-formed.
19154 if (!TInfo->getType()->isFunctionType()) {
19155 Diag(Loc, DiagID: diag::err_unexpected_friend);
19156
19157 // It might be worthwhile to try to recover by creating an
19158 // appropriate declaration.
19159 return nullptr;
19160 }
19161
19162 // C++ [namespace.memdef]p3
19163 // - If a friend declaration in a non-local class first declares a
19164 // class or function, the friend class or function is a member
19165 // of the innermost enclosing namespace.
19166 // - The name of the friend is not found by simple name lookup
19167 // until a matching declaration is provided in that namespace
19168 // scope (either before or after the class declaration granting
19169 // friendship).
19170 // - If a friend function is called, its name may be found by the
19171 // name lookup that considers functions from namespaces and
19172 // classes associated with the types of the function arguments.
19173 // - When looking for a prior declaration of a class or a function
19174 // declared as a friend, scopes outside the innermost enclosing
19175 // namespace scope are not considered.
19176
19177 CXXScopeSpec &SS = D.getCXXScopeSpec();
19178 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
19179 assert(NameInfo.getName());
19180
19181 if (SS.isValid() && DiagnosePackIndexingInFriendNNS(
19182 Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context)))
19183 return nullptr;
19184
19185 // Check for unexpanded parameter packs.
19186 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
19187 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
19188 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
19189 return nullptr;
19190
19191 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
19192
19193 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
19194 auto Kind = SS.getScopeRep().getKind();
19195 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
19196 Kind == NestedNameSpecifier::Kind::Namespace;
19197 if (IsNamespaceOrGlobal) {
19198 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def)
19199 << SS.getScopeRep();
19200 SS.clear();
19201 }
19202 }
19203
19204 // The context we found the declaration in, or in which we should
19205 // create the declaration.
19206 DeclContext *DC;
19207 Scope *DCScope = S;
19208 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
19209 RedeclarationKind::ForExternalRedeclaration);
19210
19211 // There are five cases here.
19212 // - There's no scope specifier and we're in a local class. Only look
19213 // for functions declared in the immediately-enclosing block scope.
19214 // We recover from invalid scope qualifiers as if they just weren't there.
19215 FunctionDecl *FunctionContainingLocalClass = nullptr;
19216 if ((SS.isInvalid() || !SS.isSet()) &&
19217 (FunctionContainingLocalClass =
19218 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
19219 // C++11 [class.friend]p11:
19220 // If a friend declaration appears in a local class and the name
19221 // specified is an unqualified name, a prior declaration is
19222 // looked up without considering scopes that are outside the
19223 // innermost enclosing non-class scope. For a friend function
19224 // declaration, if there is no prior declaration, the program is
19225 // ill-formed.
19226
19227 // Find the innermost enclosing non-class scope. This is the block
19228 // scope containing the local class definition (or for a nested class,
19229 // the outer local class).
19230 DCScope = S->getFnParent();
19231
19232 // Look up the function name in the scope.
19233 Previous.clear(Kind: LookupLocalFriendName);
19234 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
19235
19236 if (!Previous.empty()) {
19237 // All possible previous declarations must have the same context:
19238 // either they were declared at block scope or they are members of
19239 // one of the enclosing local classes.
19240 DC = Previous.getRepresentativeDecl()->getDeclContext();
19241 } else {
19242 // This is ill-formed, but provide the context that we would have
19243 // declared the function in, if we were permitted to, for error recovery.
19244 DC = FunctionContainingLocalClass;
19245 }
19246 adjustContextForLocalExternDecl(DC);
19247
19248 // - There's no scope specifier, in which case we just go to the
19249 // appropriate scope and look for a function or function template
19250 // there as appropriate.
19251 } else if (SS.isInvalid() || !SS.isSet()) {
19252 // C++11 [namespace.memdef]p3:
19253 // If the name in a friend declaration is neither qualified nor
19254 // a template-id and the declaration is a function or an
19255 // elaborated-type-specifier, the lookup to determine whether
19256 // the entity has been previously declared shall not consider
19257 // any scopes outside the innermost enclosing namespace.
19258
19259 // Find the appropriate context according to the above.
19260 DC = CurContext;
19261
19262 // Skip class contexts. If someone can cite chapter and verse
19263 // for this behavior, that would be nice --- it's what GCC and
19264 // EDG do, and it seems like a reasonable intent, but the spec
19265 // really only says that checks for unqualified existing
19266 // declarations should stop at the nearest enclosing namespace,
19267 // not that they should only consider the nearest enclosing
19268 // namespace.
19269 while (DC->isRecord())
19270 DC = DC->getParent();
19271
19272 DeclContext *LookupDC = DC->getNonTransparentContext();
19273 while (true) {
19274 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
19275
19276 if (!Previous.empty()) {
19277 DC = LookupDC;
19278 break;
19279 }
19280
19281 if (isTemplateId) {
19282 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
19283 } else {
19284 if (LookupDC->isFileContext()) break;
19285 }
19286 LookupDC = LookupDC->getParent();
19287 }
19288
19289 DCScope = getScopeForDeclContext(S, DC);
19290
19291 // - There's a non-dependent scope specifier, in which case we
19292 // compute it and do a previous lookup there for a function
19293 // or function template.
19294 } else if (!SS.getScopeRep().isDependent()) {
19295 DC = computeDeclContext(SS);
19296 if (!DC) return nullptr;
19297
19298 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
19299
19300 LookupQualifiedName(R&: Previous, LookupCtx: DC);
19301
19302 // C++ [class.friend]p1: A friend of a class is a function or
19303 // class that is not a member of the class . . .
19304 if (DC->Equals(DC: CurContext))
19305 Diag(Loc: DS.getFriendSpecLoc(),
19306 DiagID: getLangOpts().CPlusPlus11 ?
19307 diag::warn_cxx98_compat_friend_is_member :
19308 diag::err_friend_is_member);
19309
19310 // - There's a dependent scope specifier, in which case we use an
19311 // arbitrary context and wait for instantiation.
19312 } else {
19313 DC = CurContext;
19314 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
19315 }
19316
19317 if (!DC->isRecord()) {
19318 int DiagArg = -1;
19319 switch (D.getName().getKind()) {
19320 case UnqualifiedIdKind::IK_ConstructorTemplateId:
19321 case UnqualifiedIdKind::IK_ConstructorName:
19322 DiagArg = 0;
19323 break;
19324 case UnqualifiedIdKind::IK_DestructorName:
19325 DiagArg = 1;
19326 break;
19327 case UnqualifiedIdKind::IK_ConversionFunctionId:
19328 DiagArg = 2;
19329 break;
19330 case UnqualifiedIdKind::IK_DeductionGuideName:
19331 DiagArg = 3;
19332 break;
19333 case UnqualifiedIdKind::IK_Identifier:
19334 case UnqualifiedIdKind::IK_ImplicitSelfParam:
19335 case UnqualifiedIdKind::IK_LiteralOperatorId:
19336 case UnqualifiedIdKind::IK_OperatorFunctionId:
19337 case UnqualifiedIdKind::IK_TemplateId:
19338 break;
19339 }
19340 // This implies that it has to be an operator or function.
19341 if (DiagArg >= 0) {
19342 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
19343 return nullptr;
19344 }
19345 } else {
19346 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(Val: DC);
19347 if (RC->isLambda()) {
19348 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_lambda_decl);
19349 }
19350 }
19351
19352 // FIXME: This is an egregious hack to cope with cases where the scope stack
19353 // does not contain the declaration context, i.e., in an out-of-line
19354 // definition of a class.
19355 Scope FakeDCScope(S, Scope::DeclScope, Diags);
19356 if (!DCScope) {
19357 FakeDCScope.setEntity(DC);
19358 DCScope = &FakeDCScope;
19359 }
19360
19361 bool AddToScope = true;
19362 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
19363 TemplateParamLists: TemplateParams, AddToScope);
19364 if (!ND) return nullptr;
19365
19366 assert(ND->getLexicalDeclContext() == CurContext);
19367
19368 // If we performed typo correction, we might have added a scope specifier
19369 // and changed the decl context.
19370 DC = ND->getDeclContext();
19371
19372 // Add the function declaration to the appropriate lookup tables,
19373 // adjusting the redeclarations list as necessary. We don't
19374 // want to do this yet if the friending class is dependent.
19375 //
19376 // Also update the scope-based lookup if the target context's
19377 // lookup context is in lexical scope.
19378 if (!CurContext->isDependentContext()) {
19379 DC = DC->getRedeclContext();
19380 DC->makeDeclVisibleInContext(D: ND);
19381 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
19382 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
19383 }
19384
19385 warnOnReservedIdentifier(D: ND);
19386
19387 if (ND->isInvalidDecl()) {
19388 FriendDecl *Friend = FriendDecl::Create(
19389 C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND, FriendL: DS.getFriendSpecLoc());
19390 Friend->setAccess(AS_public);
19391 Friend->setInvalidDecl();
19392 CurContext->addDecl(D: Friend);
19393 return ND;
19394 }
19395
19396 FunctionDecl *FD = ND->getAsFunction();
19397 assert(FD && "Expected a function declaration!");
19398
19399 ArrayRef<TemplateParameterList *> TPLs = FD->getTemplateParameterLists();
19400 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TemplateParams: TPLs.back()))
19401 return nullptr;
19402
19403 FriendDecl *Friend;
19404 if (!TPLs.empty() && SS.isValid())
19405 Friend =
19406 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: D.getIdentifierLoc(),
19407 Friend: ND, FriendLoc: DS.getFriendSpecLoc(), FriendTPLists: TPLs);
19408 else
19409 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND,
19410 FriendL: DS.getFriendSpecLoc());
19411
19412 Friend->setAccess(AS_public);
19413 CurContext->addDecl(D: Friend);
19414
19415 if (DC->isRecord())
19416 CheckFriendAccess(D: ND);
19417
19418 if (!TemplateParams.empty() && SS.isValid() &&
19419 CheckDependentFriend(Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context),
19420 TPLs: FD->getTemplateParameterLists(),
19421 /*IsInstantiation=*/false))
19422 return ND;
19423
19424 // C++ [class.friend]p6:
19425 // A function may be defined in a friend declaration of a class if and
19426 // only if the class is a non-local class, and the function name is
19427 // unqualified.
19428 if (D.isFunctionDefinition()) {
19429 // Qualified friend function definition.
19430 if (SS.isNotEmpty()) {
19431 SemaDiagnosticBuilder DB =
19432 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
19433
19434 DB << SS.getScopeRep();
19435
19436 // Friend function defined in a local class.
19437 } else if (FunctionContainingLocalClass) {
19438 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
19439
19440 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
19441 // a template-id, the function name is not unqualified because these is
19442 // no name. While the wording requires some reading in-between the
19443 // lines, GCC, MSVC, and EDG all consider a friend function
19444 // specialization definitions to be de facto explicit specialization
19445 // and diagnose them as such.
19446 } else if (isTemplateId) {
19447 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
19448 }
19449 }
19450
19451 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
19452 // default argument expression, that declaration shall be a definition
19453 // and shall be the only declaration of the function or function
19454 // template in the translation unit.
19455 if (functionDeclHasDefaultArgument(FD)) {
19456 // We can't look at FD->getPreviousDecl() because it may not have been set
19457 // if we're in a dependent context. If the function is known to be a
19458 // redeclaration, we will have narrowed Previous down to the right decl.
19459 if (D.isRedeclaration()) {
19460 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
19461 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
19462 DiagID: diag::note_previous_declaration);
19463 } else if (!D.isFunctionDefinition())
19464 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
19465 }
19466
19467 return ND;
19468}
19469
19470void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
19471 StringLiteral *Message) {
19472 AdjustDeclIfTemplate(Decl&: Dcl);
19473
19474 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
19475 if (!Fn) {
19476 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
19477 return;
19478 }
19479
19480 // Deleted function does not have a body.
19481 Fn->setWillHaveBody(false);
19482
19483 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
19484 // Don't consider the implicit declaration we generate for explicit
19485 // specializations. FIXME: Do not generate these implicit declarations.
19486 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
19487 Prev->getPreviousDecl()) &&
19488 !Prev->isDefined()) {
19489 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
19490 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
19491 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
19492 : diag::note_previous_declaration);
19493 // We can't recover from this; the declaration might have already
19494 // been used.
19495 Fn->setInvalidDecl();
19496 return;
19497 }
19498
19499 // To maintain the invariant that functions are only deleted on their first
19500 // declaration, mark the implicitly-instantiated declaration of the
19501 // explicitly-specialized function as deleted instead of marking the
19502 // instantiated redeclaration.
19503 Fn = Fn->getCanonicalDecl();
19504 }
19505
19506 // dllimport/dllexport cannot be deleted.
19507 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
19508 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
19509 Fn->setInvalidDecl();
19510 }
19511
19512 // C++11 [basic.start.main]p3:
19513 // A program that defines main as deleted [...] is ill-formed.
19514 if (Fn->isMain())
19515 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
19516
19517 // C++11 [dcl.fct.def.delete]p4:
19518 // A deleted function is implicitly inline.
19519 Fn->setImplicitlyInline();
19520 Fn->setDeletedAsWritten(D: true, Message);
19521}
19522
19523void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc, Scope *S) {
19524 if (!Dcl || Dcl->isInvalidDecl())
19525 return;
19526
19527 // Which kinds of functions can be defaulted in the current language mode.
19528 unsigned DefaultableKinds = diag::DefaultableFunctionKinds::Default;
19529 if (getLangOpts().CPlusPlus29)
19530 DefaultableKinds = diag::DefaultableFunctionKinds::Cxx29;
19531 else if (getLangOpts().CPlusPlus20)
19532 DefaultableKinds = diag::DefaultableFunctionKinds::Cxx20;
19533
19534 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
19535 if (!FD) {
19536 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
19537 FunctionDecl::DefaultedFunctionKind DFK =
19538 FTD->getTemplatedDecl()->getDefaultedFunctionKind();
19539 if (DFK.isComparison() || DFK.isPostfixOperator()) {
19540 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_operator_template)
19541 << DFK.isPostfixOperator() << (int)DFK.asPostfixOperator();
19542 return;
19543 }
19544 }
19545
19546 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members) << DefaultableKinds;
19547 return;
19548 }
19549
19550 // Reject if this can't possibly be a defaultable function.
19551 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
19552 if (!DefKind &&
19553 // A dependent function that doesn't locally look defaultable can
19554 // still instantiate to a defaultable function if it's a constructor
19555 // or assignment operator.
19556 (!FD->isDependentContext() ||
19557 (!isa<CXXConstructorDecl>(Val: FD) &&
19558 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
19559 OverloadedOperatorKind OO = FD->getDeclName().getCXXOverloadedOperator();
19560 if (OO == OO_PlusPlus || OO == OO_MinusMinus)
19561 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_prefix_operator)
19562 << (OO == OO_MinusMinus);
19563 else
19564 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members) << DefaultableKinds;
19565 return;
19566 }
19567
19568 // Issue compatibility warning. We already warned if the operator is
19569 // 'operator<=>' when parsing the '<=>' token.
19570 if (DefKind.isComparison() &&
19571 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
19572 DiagCompat(Loc: DefaultLoc, CompatDiagId: diag_compat::defaulted_comparison);
19573 }
19574 // Defaulted postfix increment and decrement operators (P3668R4) are a C++2d
19575 // feature that we support in all C++ language modes as an extension.
19576 if (DefKind.isPostfixOperator() && !inTemplateInstantiation())
19577 DiagCompat(Loc: DefaultLoc, CompatDiagId: diag_compat::defaulted_postfix_operator);
19578
19579 FD->setDefaulted();
19580 FD->setExplicitlyDefaulted();
19581 FD->setDefaultLoc(DefaultLoc);
19582
19583 // Defer checking functions that are defaulted in a dependent context.
19584 if (FD->isDependentContext()) {
19585 // A function defaulted outside its class is not defaulted when its
19586 // declaration is instantiated, so record what the instantiation of its
19587 // definition needs from here: the floating-point features in effect and,
19588 // for a postfix operator, the unqualified lookup of the prefix operator,
19589 // which can only be performed now, while we have the scope of the
19590 // function-body. The info is recorded even for default floating-point
19591 // features, so that the instantiation does not take those in effect at its
19592 // point of instantiation. (When the function is defaulted in its class,
19593 // the lookup is performed once the class is complete.)
19594 if (!isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
19595 if (DefKind.isPostfixOperator())
19596 CheckExplicitlyDefaultedPostfixOperator(S, FD,
19597 Kind: DefKind.asPostfixOperator());
19598 else if (!FD->getDefaultedOrDeletedInfo())
19599 FD->setDefaultedOrDeletedInfo(
19600 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
19601 Context, /*Lookups=*/{}, FPFeatures: CurFPFeatureOverrides()));
19602 }
19603 return;
19604 }
19605
19606 // Unset that we will have a body for this function. We might not,
19607 // if it turns out to be trivial, and we don't need this marking now
19608 // that we've marked it as defaulted.
19609 FD->setWillHaveBody(false);
19610
19611 if (DefKind.isComparison() || DefKind.isPostfixOperator()) {
19612 // If this function's defaulting occurs within the definition of its
19613 // lexical class context, we have to do the checking when complete.
19614 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
19615 if (!RD->isCompleteDefinition())
19616 return;
19617 }
19618
19619 // If this member fn was defaulted on its first declaration, we will have
19620 // already performed the checking in CheckCompletedCXXClass. Such a
19621 // declaration doesn't trigger an implicit definition.
19622 if (isa<CXXMethodDecl>(Val: FD)) {
19623 const FunctionDecl *Primary = FD;
19624 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19625 // Ask the template instantiation pattern that actually had the
19626 // '= default' on it.
19627 Primary = Pattern;
19628 if (Primary->getCanonicalDecl()->isDefaulted())
19629 return;
19630 }
19631
19632 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19633 // non-default FP features to stash. This avoids memory overhead for
19634 // the vast majority of defaulted functions. A postfix operator defaulted
19635 // with a scope gets its info, which includes these features, when the
19636 // lookup of its prefix operator is performed below.
19637 if (!FD->getDefaultedOrDeletedInfo() && !(DefKind.isPostfixOperator() && S) &&
19638 CurFPFeatureOverrides().requiresTrailingStorage()) {
19639 FD->setDefaultedOrDeletedInfo(
19640 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
19641 Context, /*Lookups=*/{}, FPFeatures: CurFPFeatureOverrides()));
19642 }
19643
19644 if (DefKind.isComparison()) {
19645 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
19646 FD->setInvalidDecl();
19647 else
19648 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
19649 } else if (DefKind.isPostfixOperator()) {
19650 if (CheckExplicitlyDefaultedPostfixOperator(S, FD,
19651 Kind: DefKind.asPostfixOperator()))
19652 FD->setInvalidDecl();
19653 else if (!FD->isDeleted())
19654 DefineDefaultedPostfixOperator(UseLoc: DefaultLoc, FD,
19655 Kind: DefKind.asPostfixOperator());
19656 } else {
19657 auto *MD = cast<CXXMethodDecl>(Val: FD);
19658
19659 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
19660 DefaultLoc))
19661 MD->setInvalidDecl();
19662 else
19663 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
19664 }
19665}
19666
19667static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
19668 for (Stmt *SubStmt : S->children()) {
19669 if (!SubStmt)
19670 continue;
19671 if (isa<ReturnStmt>(Val: SubStmt))
19672 Self.Diag(Loc: SubStmt->getBeginLoc(),
19673 DiagID: diag::err_return_in_constructor_handler);
19674 if (!isa<Expr>(Val: SubStmt))
19675 SearchForReturnInStmt(Self, S: SubStmt);
19676 }
19677}
19678
19679void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
19680 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19681 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
19682 SearchForReturnInStmt(Self&: *this, S: Handler);
19683 }
19684}
19685
19686void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
19687 StringLiteral *DeletedMessage, Scope *S) {
19688 switch (BodyKind) {
19689 case FnBodyKind::Delete:
19690 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
19691 break;
19692 case FnBodyKind::Default:
19693 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc, S);
19694 break;
19695 case FnBodyKind::Other:
19696 llvm_unreachable(
19697 "Parsed function body should be '= delete;' or '= default;'");
19698 }
19699}
19700
19701bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
19702 const CXXMethodDecl *Old) {
19703 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19704 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19705
19706 if (OldFT->hasExtParameterInfos()) {
19707 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19708 // A parameter of the overriding method should be annotated with noescape
19709 // if the corresponding parameter of the overridden method is annotated.
19710 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19711 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19712 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
19713 DiagID: diag::warn_overriding_method_missing_noescape);
19714 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
19715 DiagID: diag::note_overridden_marked_noescape);
19716 }
19717 }
19718
19719 // SME attributes must match when overriding a function declaration.
19720 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
19721 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
19722 << New << New->getType() << Old->getType();
19723 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19724 return true;
19725 }
19726
19727 // Virtual overrides must have the same code_seg.
19728 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19729 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19730 if ((NewCSA || OldCSA) &&
19731 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19732 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
19733 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
19734 return true;
19735 }
19736
19737 // Virtual overrides: check for matching effects.
19738 if (Context.hasAnyFunctionEffects()) {
19739 const auto OldFX = Old->getFunctionEffects();
19740 const auto NewFXOrig = New->getFunctionEffects();
19741
19742 if (OldFX != NewFXOrig) {
19743 FunctionEffectSet NewFX(NewFXOrig);
19744 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19745 FunctionEffectSet::Conflicts Errs;
19746 for (const auto &Diff : Diffs) {
19747 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
19748 case FunctionEffectDiff::OverrideResult::NoAction:
19749 break;
19750 case FunctionEffectDiff::OverrideResult::Warn:
19751 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
19752 << Diff.effectName();
19753 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19754 << Old->getReturnTypeSourceRange();
19755 break;
19756 case FunctionEffectDiff::OverrideResult::Merge: {
19757 NewFX.insert(NewEC: Diff.Old.value(), Errs);
19758 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19759 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19760 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
19761 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
19762 Args: NewFT->getParamTypes(), EPI);
19763 New->setType(ModQT);
19764 if (Errs.empty()) {
19765 // A warning here is somewhat pedantic. Skip this if there was
19766 // already a merge conflict, which is more serious.
19767 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
19768 << Diff.effectName();
19769 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19770 << Old->getReturnTypeSourceRange();
19771 }
19772 break;
19773 }
19774 }
19775 }
19776 if (!Errs.empty())
19777 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
19778 OldLoc: Old->getLocation());
19779 }
19780 }
19781
19782 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19783
19784 // If the calling conventions match, everything is fine
19785 if (NewCC == OldCC)
19786 return false;
19787
19788 // If the calling conventions mismatch because the new function is static,
19789 // suppress the calling convention mismatch error; the error about static
19790 // function override (err_static_overrides_virtual from
19791 // Sema::CheckFunctionDeclaration) is more clear.
19792 if (New->getStorageClass() == SC_Static)
19793 return false;
19794
19795 Diag(Loc: New->getLocation(),
19796 DiagID: diag::err_conflicting_overriding_cc_attributes)
19797 << New->getDeclName() << New->getType() << Old->getType();
19798 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19799 return true;
19800}
19801
19802bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
19803 const CXXMethodDecl *Old) {
19804 // CWG2553
19805 // A virtual function shall not be an explicit object member function.
19806 if (!New->isExplicitObjectMemberFunction())
19807 return true;
19808 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
19809 DiagID: diag::err_explicit_object_parameter_nonmember)
19810 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19811 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19812 New->setInvalidDecl();
19813 return false;
19814}
19815
19816bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
19817 const CXXMethodDecl *Old) {
19818 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19819 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19820
19821 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
19822 NewTy->isDependentType() || OldTy->isDependentType())
19823 return false;
19824
19825 // Check if the return types are covariant
19826 QualType NewClassTy, OldClassTy;
19827
19828 /// Both types must be pointers or references to classes.
19829 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19830 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19831 NewClassTy = NewPT->getPointeeType();
19832 OldClassTy = OldPT->getPointeeType();
19833 }
19834 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19835 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19836 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19837 NewClassTy = NewRT->getPointeeType();
19838 OldClassTy = OldRT->getPointeeType();
19839 }
19840 }
19841 }
19842
19843 // The return types aren't either both pointers or references to a class type.
19844 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19845 Diag(Loc: New->getLocation(),
19846 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
19847 << New->getDeclName() << NewTy << OldTy
19848 << New->getReturnTypeSourceRange();
19849 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19850 << Old->getReturnTypeSourceRange();
19851
19852 return true;
19853 }
19854
19855 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
19856 // C++14 [class.virtual]p8:
19857 // If the class type in the covariant return type of D::f differs from
19858 // that of B::f, the class type in the return type of D::f shall be
19859 // complete at the point of declaration of D::f or shall be the class
19860 // type D.
19861 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19862 if (!RD->isBeingDefined() &&
19863 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
19864 DiagID: diag::err_covariant_return_incomplete,
19865 Args: New->getDeclName()))
19866 return true;
19867 }
19868
19869 // Check if the new class derives from the old class.
19870 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
19871 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
19872 << New->getDeclName() << NewTy << OldTy
19873 << New->getReturnTypeSourceRange();
19874 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19875 << Old->getReturnTypeSourceRange();
19876 return true;
19877 }
19878
19879 // Check if we the conversion from derived to base is valid.
19880 if (CheckDerivedToBaseConversion(
19881 Derived: NewClassTy, Base: OldClassTy,
19882 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
19883 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
19884 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
19885 Name: New->getDeclName(), BasePath: nullptr)) {
19886 // FIXME: this note won't trigger for delayed access control
19887 // diagnostics, and it's impossible to get an undelayed error
19888 // here from access control during the original parse because
19889 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19890 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19891 << Old->getReturnTypeSourceRange();
19892 return true;
19893 }
19894 }
19895
19896 // The qualifiers of the return types must be the same.
19897 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19898 Diag(Loc: New->getLocation(),
19899 DiagID: diag::err_covariant_return_type_different_qualifications)
19900 << New->getDeclName() << NewTy << OldTy
19901 << New->getReturnTypeSourceRange();
19902 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19903 << Old->getReturnTypeSourceRange();
19904 return true;
19905 }
19906
19907
19908 // The new class type must have the same or less qualifiers as the old type.
19909 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
19910 Diag(Loc: New->getLocation(),
19911 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19912 << New->getDeclName() << NewTy << OldTy
19913 << New->getReturnTypeSourceRange();
19914 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19915 << Old->getReturnTypeSourceRange();
19916 return true;
19917 }
19918
19919 return false;
19920}
19921
19922bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
19923 SourceLocation EndLoc = InitRange.getEnd();
19924 if (EndLoc.isValid())
19925 Method->setRangeEnd(EndLoc);
19926
19927 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19928 Method->setIsPureVirtual();
19929 return false;
19930 }
19931
19932 if (!Method->isInvalidDecl())
19933 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19934 << Method->getDeclName() << InitRange;
19935 return true;
19936}
19937
19938void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19939 if (D->getFriendObjectKind())
19940 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19941 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19942 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19943 else
19944 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19945}
19946
19947/// Invoked when we are about to parse an initializer for the declaration
19948/// 'Dcl'.
19949///
19950/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19951/// static data member of class X, names should be looked up in the scope of
19952/// class X. If the declaration had a scope specifier, a scope will have
19953/// been created and passed in for this purpose. Otherwise, S will be null.
19954void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19955 assert(D && !D->isInvalidDecl());
19956
19957 // We will always have a nested name specifier here, but this declaration
19958 // might not be out of line if the specifier names the current namespace:
19959 // extern int n;
19960 // int ::n = 0;
19961 if (S && D->isOutOfLine())
19962 EnterDeclaratorContext(S, DC: D->getDeclContext());
19963
19964 PushExpressionEvaluationContext(
19965 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19966 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19967}
19968
19969void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19970 assert(D);
19971
19972 if (S && D->isOutOfLine())
19973 ExitDeclaratorContext(S);
19974
19975 PopExpressionEvaluationContext();
19976}
19977
19978DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19979 // C++ 6.4p2:
19980 // The declarator shall not specify a function or an array.
19981 // The type-specifier-seq shall not contain typedef and shall not declare a
19982 // new class or enumeration.
19983 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19984 "Parser allowed 'typedef' as storage class of condition decl.");
19985
19986 Decl *Dcl = ActOnDeclarator(S, D);
19987 if (!Dcl)
19988 return true;
19989
19990 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19991 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19992 << D.getSourceRange();
19993 return true;
19994 }
19995
19996 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19997 VD->setCXXCondDecl();
19998
19999 return Dcl;
20000}
20001
20002void Sema::LoadExternalVTableUses() {
20003 if (!ExternalSource)
20004 return;
20005
20006 SmallVector<ExternalVTableUse, 4> VTables;
20007 ExternalSource->ReadUsedVTables(VTables);
20008 SmallVector<VTableUse, 4> NewUses;
20009 for (const ExternalVTableUse &VTable : VTables) {
20010 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
20011 VTablesUsed.find(Val: VTable.Record);
20012 // Even if a definition wasn't required before, it may be required now.
20013 if (Pos != VTablesUsed.end()) {
20014 if (!Pos->second && VTable.DefinitionRequired)
20015 Pos->second = true;
20016 continue;
20017 }
20018
20019 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
20020 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
20021 }
20022
20023 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
20024}
20025
20026void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
20027 bool DefinitionRequired) {
20028 // Ignore any vtable uses in unevaluated operands or for classes that do
20029 // not have a vtable.
20030 if (!Class->isDynamicClass() || Class->isDependentContext() ||
20031 CurContext->isDependentContext() || isUnevaluatedContext())
20032 return;
20033 // Do not mark as used if compiling for the device outside of the target
20034 // region.
20035 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
20036 !OpenMP().isInOpenMPDeclareTargetContext() &&
20037 !OpenMP().isInOpenMPTargetExecutionDirective()) {
20038 if (!DefinitionRequired)
20039 MarkVirtualMembersReferenced(Loc, RD: Class);
20040 return;
20041 }
20042
20043 // Try to insert this class into the map.
20044 LoadExternalVTableUses();
20045 Class = Class->getCanonicalDecl();
20046 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
20047 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
20048 if (!Pos.second) {
20049 // If we already had an entry, check to see if we are promoting this vtable
20050 // to require a definition. If so, we need to reappend to the VTableUses
20051 // list, since we may have already processed the first entry.
20052 if (DefinitionRequired && !Pos.first->second) {
20053 Pos.first->second = true;
20054 } else {
20055 // Otherwise, we can early exit.
20056 return;
20057 }
20058 } else {
20059 // The Microsoft ABI requires that we perform the destructor body
20060 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
20061 // the deleting destructor is emitted with the vtable, not with the
20062 // destructor definition as in the Itanium ABI.
20063 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
20064 CXXDestructorDecl *DD = Class->getDestructor();
20065 if (DD && DD->isVirtual() && !DD->isDeleted()) {
20066 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
20067 // If this is an out-of-line declaration, marking it referenced will
20068 // not do anything. Manually call CheckDestructor to look up operator
20069 // delete().
20070 ContextRAII SavedContext(*this, DD);
20071 CheckDestructor(Destructor: DD);
20072 if (!DD->getOperatorDelete())
20073 DD->setInvalidDecl();
20074 } else {
20075 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
20076 }
20077 }
20078 }
20079 }
20080
20081 // Local classes need to have their virtual members marked
20082 // immediately. For all other classes, we mark their virtual members
20083 // at the end of the translation unit.
20084 if (Class->isLocalClass())
20085 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
20086 else
20087 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
20088}
20089
20090bool Sema::DefineUsedVTables() {
20091 LoadExternalVTableUses();
20092 if (VTableUses.empty())
20093 return false;
20094
20095 // Note: The VTableUses vector could grow as a result of marking
20096 // the members of a class as "used", so we check the size each
20097 // time through the loop and prefer indices (which are stable) to
20098 // iterators (which are not).
20099 bool DefinedAnything = false;
20100 for (unsigned I = 0; I != VTableUses.size(); ++I) {
20101 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
20102 if (!Class)
20103 continue;
20104 TemplateSpecializationKind ClassTSK =
20105 Class->getTemplateSpecializationKind();
20106
20107 SourceLocation Loc = VTableUses[I].second;
20108
20109 bool DefineVTable = true;
20110
20111 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
20112 // V-tables for non-template classes with an owning module are always
20113 // uniquely emitted in that module.
20114 if (Class->isInCurrentModuleUnit()) {
20115 DefineVTable = true;
20116 } else if (KeyFunction && !KeyFunction->hasBody()) {
20117 // If this class has a key function, but that key function is
20118 // defined in another translation unit, we don't need to emit the
20119 // vtable even though we're using it.
20120 // The key function is in another translation unit.
20121 DefineVTable = false;
20122 TemplateSpecializationKind TSK =
20123 KeyFunction->getTemplateSpecializationKind();
20124 assert(TSK != TSK_ExplicitInstantiationDefinition &&
20125 TSK != TSK_ImplicitInstantiation &&
20126 "Instantiations don't have key functions");
20127 (void)TSK;
20128 } else if (!KeyFunction) {
20129 // If we have a class with no key function that is the subject
20130 // of an explicit instantiation declaration, suppress the
20131 // vtable; it will live with the explicit instantiation
20132 // definition.
20133 bool IsExplicitInstantiationDeclaration =
20134 ClassTSK == TSK_ExplicitInstantiationDeclaration;
20135 for (auto *R : Class->redecls()) {
20136 TemplateSpecializationKind TSK
20137 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
20138 if (TSK == TSK_ExplicitInstantiationDeclaration)
20139 IsExplicitInstantiationDeclaration = true;
20140 else if (TSK == TSK_ExplicitInstantiationDefinition) {
20141 IsExplicitInstantiationDeclaration = false;
20142 break;
20143 }
20144 }
20145
20146 if (IsExplicitInstantiationDeclaration) {
20147 const bool HasExcludeFromExplicitInstantiation =
20148 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
20149 // If the class has a member function declared with
20150 // `__attribute__((exclude_from_explicit_instantiation))`, the
20151 // explicit instantiation declaration should not suppress emitting
20152 // the vtable, since the corresponding explicit instantiation
20153 // definition might not emit the vtable if a triggering method is
20154 // excluded.
20155 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
20156 });
20157 if (!HasExcludeFromExplicitInstantiation)
20158 DefineVTable = false;
20159 }
20160 }
20161
20162 // The exception specifications for all virtual members may be needed even
20163 // if we are not providing an authoritative form of the vtable in this TU.
20164 // We may choose to emit it available_externally anyway.
20165 if (!DefineVTable) {
20166 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
20167 continue;
20168 }
20169
20170 // Mark all of the virtual members of this class as referenced, so
20171 // that we can build a vtable. Then, tell the AST consumer that a
20172 // vtable for this class is required.
20173 DefinedAnything = true;
20174 MarkVirtualMembersReferenced(Loc, RD: Class);
20175 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
20176 // The vtable is assumed to be emitted in an external source only for
20177 // classes attached to a named module, which is guaranteed to have an object
20178 // file. This isn't true for -fmodules-debuginfo, which still has
20179 // shouldEmitInExternalSource as true so that debug info gets supressed.
20180 if (VTablesUsed[Canonical] &&
20181 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
20182 Consumer.HandleVTable(RD: Class);
20183
20184 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
20185 // no key function or the key function is inlined. Don't warn in C++ ABIs
20186 // that lack key functions, since the user won't be able to make one.
20187 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
20188 Class->isExternallyVisible() &&
20189 !(Class->getOwningModule() &&
20190 Class->getOwningModule()->isInterfaceOrPartition()) &&
20191 ClassTSK != TSK_ImplicitInstantiation &&
20192 ClassTSK != TSK_ExplicitInstantiationDeclaration &&
20193 ClassTSK != TSK_ExplicitInstantiationDefinition) {
20194 const FunctionDecl *KeyFunctionDef = nullptr;
20195 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
20196 KeyFunctionDef->isInlined()))
20197 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
20198 }
20199 }
20200 VTableUses.clear();
20201
20202 return DefinedAnything;
20203}
20204
20205void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
20206 const CXXRecordDecl *RD) {
20207 for (const auto *I : RD->methods())
20208 if (I->isVirtual() && !I->isPureVirtual())
20209 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
20210}
20211
20212void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
20213 const CXXRecordDecl *RD,
20214 bool ConstexprOnly) {
20215 // Mark all functions which will appear in RD's vtable as used.
20216 CXXFinalOverriderMap FinalOverriders;
20217 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
20218 for (const auto &FinalOverrider : FinalOverriders) {
20219 for (const auto &OverridingMethod : FinalOverrider.second) {
20220 assert(OverridingMethod.second.size() > 0 && "no final overrider");
20221 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
20222
20223 // C++ [basic.def.odr]p2:
20224 // [...] A virtual member function is used if it is not pure. [...]
20225 if (!Overrider->isPureVirtual() &&
20226 (!ConstexprOnly || Overrider->isConstexpr()))
20227 MarkFunctionReferenced(Loc, Func: Overrider);
20228 }
20229 }
20230
20231 // Only classes that have virtual bases need a VTT.
20232 if (RD->getNumVBases() == 0)
20233 return;
20234
20235 for (const auto &I : RD->bases()) {
20236 const auto *Base = I.getType()->castAsCXXRecordDecl();
20237 if (Base->getNumVBases() == 0)
20238 continue;
20239 MarkVirtualMembersReferenced(Loc, RD: Base);
20240 }
20241}
20242
20243static
20244void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
20245 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
20246 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
20247 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
20248 Sema &S) {
20249 if (Ctor->isInvalidDecl())
20250 return;
20251
20252 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
20253
20254 // Target may not be determinable yet, for instance if this is a dependent
20255 // call in an uninstantiated template.
20256 if (Target) {
20257 const FunctionDecl *FNTarget = nullptr;
20258 (void)Target->hasBody(Definition&: FNTarget);
20259 Target = const_cast<CXXConstructorDecl*>(
20260 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
20261 }
20262
20263 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
20264 // Avoid dereferencing a null pointer here.
20265 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
20266
20267 if (!Current.insert(Ptr: Canonical).second)
20268 return;
20269
20270 // We know that beyond here, we aren't chaining into a cycle.
20271 if (!Target || !Target->isDelegatingConstructor() ||
20272 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
20273 Valid.insert_range(R&: Current);
20274 Current.clear();
20275 // We've hit a cycle.
20276 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
20277 Current.count(Ptr: TCanonical)) {
20278 // If we haven't diagnosed this cycle yet, do so now.
20279 if (!Invalid.count(Ptr: TCanonical)) {
20280 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
20281 DiagID: diag::warn_delegating_ctor_cycle)
20282 << Ctor;
20283
20284 // Don't add a note for a function delegating directly to itself.
20285 if (TCanonical != Canonical)
20286 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
20287
20288 CXXConstructorDecl *C = Target;
20289 while (C->getCanonicalDecl() != Canonical) {
20290 const FunctionDecl *FNTarget = nullptr;
20291 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
20292 assert(FNTarget && "Ctor cycle through bodiless function");
20293
20294 C = const_cast<CXXConstructorDecl*>(
20295 cast<CXXConstructorDecl>(Val: FNTarget));
20296 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
20297 }
20298 }
20299
20300 Invalid.insert_range(R&: Current);
20301 Current.clear();
20302 } else {
20303 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
20304 }
20305}
20306
20307
20308void Sema::CheckDelegatingCtorCycles() {
20309 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
20310
20311 for (DelegatingCtorDeclsType::iterator
20312 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
20313 E = DelegatingCtorDecls.end();
20314 I != E; ++I)
20315 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
20316
20317 for (CXXConstructorDecl *CI : Invalid)
20318 CI->setInvalidDecl();
20319}
20320
20321namespace {
20322 /// AST visitor that finds references to the 'this' expression.
20323class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
20324 Sema &S;
20325
20326public:
20327 explicit FindCXXThisExpr(Sema &S) : S(S) {}
20328
20329 bool VisitCXXThisExpr(CXXThisExpr *E) override {
20330 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
20331 << E->isImplicit();
20332 return false;
20333 }
20334};
20335}
20336
20337bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
20338 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
20339 if (!TSInfo)
20340 return false;
20341
20342 TypeLoc TL = TSInfo->getTypeLoc();
20343 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
20344 if (!ProtoTL)
20345 return false;
20346
20347 // C++11 [expr.prim.general]p3:
20348 // [The expression this] shall not appear before the optional
20349 // cv-qualifier-seq and it shall not appear within the declaration of a
20350 // static member function (although its type and value category are defined
20351 // within a static member function as they are within a non-static member
20352 // function). [ Note: this is because declaration matching does not occur
20353 // until the complete declarator is known. - end note ]
20354 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
20355 FindCXXThisExpr Finder(*this);
20356
20357 // If the return type came after the cv-qualifier-seq, check it now.
20358 if (Proto->hasTrailingReturn() &&
20359 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
20360 return true;
20361
20362 // Check the exception specification.
20363 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
20364 return true;
20365
20366 // Check the trailing requires clause
20367 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
20368 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
20369 return true;
20370
20371 return checkThisInStaticMemberFunctionAttributes(Method);
20372}
20373
20374bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
20375 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
20376 if (!TSInfo)
20377 return false;
20378
20379 TypeLoc TL = TSInfo->getTypeLoc();
20380 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
20381 if (!ProtoTL)
20382 return false;
20383
20384 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
20385 FindCXXThisExpr Finder(*this);
20386
20387 switch (Proto->getExceptionSpecType()) {
20388 case EST_Unparsed:
20389 case EST_Uninstantiated:
20390 case EST_Unevaluated:
20391 case EST_BasicNoexcept:
20392 case EST_NoThrow:
20393 case EST_DynamicNone:
20394 case EST_MSAny:
20395 case EST_None:
20396 break;
20397
20398 case EST_DependentNoexcept:
20399 case EST_NoexceptFalse:
20400 case EST_NoexceptTrue:
20401 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
20402 return true;
20403 [[fallthrough]];
20404
20405 case EST_Dynamic:
20406 for (const auto &E : Proto->exceptions()) {
20407 if (!Finder.TraverseType(T: E))
20408 return true;
20409 }
20410 break;
20411 }
20412
20413 return false;
20414}
20415
20416bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
20417 FindCXXThisExpr Finder(*this);
20418
20419 // Check attributes.
20420 for (const auto *A : Method->attrs()) {
20421 // FIXME: This should be emitted by tblgen.
20422 Expr *Arg = nullptr;
20423 ArrayRef<Expr *> Args;
20424 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
20425 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
20426 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
20427 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
20428 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
20429 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
20430 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
20431 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
20432 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
20433 Arg = LR->getArg();
20434 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
20435 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
20436 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
20437 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
20438 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
20439 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
20440 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
20441 Arg = AC->getSuccessValue();
20442 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
20443 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
20444 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
20445
20446 if (Arg && !Finder.TraverseStmt(S: Arg))
20447 return true;
20448
20449 for (Expr *A : Args) {
20450 if (!Finder.TraverseStmt(S: A))
20451 return true;
20452 }
20453 }
20454
20455 return false;
20456}
20457
20458void Sema::checkExceptionSpecification(
20459 bool IsTopLevel, ExceptionSpecificationType EST,
20460 ArrayRef<ParsedType> DynamicExceptions,
20461 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
20462 SmallVectorImpl<QualType> &Exceptions,
20463 FunctionProtoType::ExceptionSpecInfo &ESI) {
20464 Exceptions.clear();
20465 ESI.Type = EST;
20466 if (EST == EST_Dynamic) {
20467 Exceptions.reserve(N: DynamicExceptions.size());
20468 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
20469 // FIXME: Preserve type source info.
20470 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
20471
20472 if (IsTopLevel) {
20473 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
20474 collectUnexpandedParameterPacks(T: ET, Unexpanded);
20475 if (!Unexpanded.empty()) {
20476 DiagnoseUnexpandedParameterPacks(
20477 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
20478 Unexpanded);
20479 continue;
20480 }
20481 }
20482
20483 // Check that the type is valid for an exception spec, and
20484 // drop it if not.
20485 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
20486 Exceptions.push_back(Elt: ET);
20487 }
20488 ESI.Exceptions = Exceptions;
20489 return;
20490 }
20491
20492 if (isComputedNoexcept(ESpecType: EST)) {
20493 assert((NoexceptExpr->isTypeDependent() ||
20494 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
20495 Context.BoolTy) &&
20496 "Parser should have made sure that the expression is boolean");
20497 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
20498 ESI.Type = EST_BasicNoexcept;
20499 return;
20500 }
20501
20502 ESI.NoexceptExpr = NoexceptExpr;
20503 return;
20504 }
20505}
20506
20507void Sema::actOnDelayedExceptionSpecification(
20508 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
20509 ArrayRef<ParsedType> DynamicExceptions,
20510 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
20511 if (!D)
20512 return;
20513
20514 // Dig out the function we're referring to.
20515 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
20516 D = FTD->getTemplatedDecl();
20517
20518 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
20519 if (!FD)
20520 return;
20521
20522 // Check the exception specification.
20523 llvm::SmallVector<QualType, 4> Exceptions;
20524 FunctionProtoType::ExceptionSpecInfo ESI;
20525 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
20526 DynamicExceptionRanges, NoexceptExpr, Exceptions,
20527 ESI);
20528
20529 // Update the exception specification on the function type.
20530 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
20531
20532 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
20533 if (MD->isStatic())
20534 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
20535
20536 if (MD->isVirtual()) {
20537 // Check overrides, which we previously had to delay.
20538 for (const CXXMethodDecl *O : MD->overridden_methods())
20539 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
20540 }
20541 }
20542}
20543
20544/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
20545///
20546MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
20547 SourceLocation DeclStart, Declarator &D,
20548 Expr *BitWidth,
20549 InClassInitStyle InitStyle,
20550 AccessSpecifier AS,
20551 const ParsedAttr &MSPropertyAttr) {
20552 const IdentifierInfo *II = D.getIdentifier();
20553 if (!II) {
20554 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
20555 return nullptr;
20556 }
20557 SourceLocation Loc = D.getIdentifierLoc();
20558
20559 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
20560 QualType T = TInfo->getType();
20561 if (getLangOpts().CPlusPlus) {
20562 CheckExtraCXXDefaultArguments(D);
20563
20564 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
20565 UPPC: UPPC_DataMemberType)) {
20566 D.setInvalidType();
20567 T = Context.IntTy;
20568 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
20569 }
20570 }
20571
20572 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
20573
20574 if (D.getDeclSpec().isInlineSpecified())
20575 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
20576 << getLangOpts().CPlusPlus17;
20577 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
20578 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
20579 DiagID: diag::err_invalid_thread)
20580 << DeclSpec::getSpecifierName(S: TSCS);
20581
20582 // Check to see if this name was declared as a member previously
20583 NamedDecl *PrevDecl = nullptr;
20584 LookupResult Previous(*this, II, Loc, LookupMemberName,
20585 RedeclarationKind::ForVisibleRedeclaration);
20586 LookupName(R&: Previous, S);
20587 switch (Previous.getResultKind()) {
20588 case LookupResultKind::Found:
20589 case LookupResultKind::FoundUnresolvedValue:
20590 PrevDecl = Previous.getAsSingle<NamedDecl>();
20591 break;
20592
20593 case LookupResultKind::FoundOverloaded:
20594 PrevDecl = Previous.getRepresentativeDecl();
20595 break;
20596
20597 case LookupResultKind::NotFound:
20598 case LookupResultKind::NotFoundInCurrentInstantiation:
20599 case LookupResultKind::Ambiguous:
20600 break;
20601 }
20602
20603 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20604 // Maybe we will complain about the shadowed template parameter.
20605 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
20606 // Just pretend that we didn't see the previous declaration.
20607 PrevDecl = nullptr;
20608 }
20609
20610 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
20611 PrevDecl = nullptr;
20612
20613 SourceLocation TSSL = D.getBeginLoc();
20614 MSPropertyDecl *NewPD =
20615 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
20616 Getter: MSPropertyAttr.getPropertyDataGetter(),
20617 Setter: MSPropertyAttr.getPropertyDataSetter());
20618 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
20619 NewPD->setAccess(AS);
20620
20621 if (NewPD->isInvalidDecl())
20622 Record->setInvalidDecl();
20623
20624 if (D.getDeclSpec().isModulePrivateSpecified())
20625 NewPD->setModulePrivate();
20626
20627 if (NewPD->isInvalidDecl() && PrevDecl) {
20628 // Don't introduce NewFD into scope; there's already something
20629 // with the same name in the same scope.
20630 } else if (II) {
20631 PushOnScopeChains(D: NewPD, S);
20632 } else
20633 Record->addDecl(D: NewPD);
20634
20635 return NewPD;
20636}
20637
20638void Sema::ActOnStartFunctionDeclarationDeclarator(
20639 Declarator &Declarator, unsigned TemplateParameterDepth) {
20640 auto &Info = InventedParameterInfos.emplace_back();
20641 TemplateParameterList *ExplicitParams = nullptr;
20642 ArrayRef<TemplateParameterList *> ExplicitLists =
20643 Declarator.getTemplateParameterLists();
20644 if (!ExplicitLists.empty()) {
20645 bool IsMemberSpecialization, IsInvalid;
20646 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
20647 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
20648 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20649 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
20650 /*SuppressDiagnostic=*/true);
20651 }
20652 // C++23 [dcl.fct]p23:
20653 // An abbreviated function template can have a template-head. The invented
20654 // template-parameters are appended to the template-parameter-list after
20655 // the explicitly declared template-parameters.
20656 //
20657 // A template-head must have one or more template-parameters (read:
20658 // 'template<>' is *not* a template-head). Only append the invented
20659 // template parameters if we matched the nested-name-specifier to a non-empty
20660 // TemplateParameterList.
20661 if (ExplicitParams && !ExplicitParams->empty()) {
20662 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20663 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
20664 Info.NumExplicitTemplateParams = ExplicitParams->size();
20665 } else {
20666 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20667 Info.NumExplicitTemplateParams = 0;
20668 }
20669}
20670
20671void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
20672 auto &FSI = InventedParameterInfos.back();
20673 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20674 if (FSI.NumExplicitTemplateParams != 0) {
20675 TemplateParameterList *ExplicitParams =
20676 Declarator.getTemplateParameterLists().back();
20677 Declarator.setInventedTemplateParameterList(
20678 TemplateParameterList::Create(
20679 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
20680 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
20681 RAngleLoc: ExplicitParams->getRAngleLoc(),
20682 RequiresClause: ExplicitParams->getRequiresClause()));
20683 } else {
20684 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
20685 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
20686 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
20687 /*RequiresClause=*/nullptr));
20688 }
20689 }
20690 InventedParameterInfos.pop_back();
20691}
20692
20693bool Sema::BuildCtorClosureDefaultArgs(SourceLocation Loc,
20694 CXXConstructorDecl *Ctor, bool IsCopy) {
20695 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20696
20697 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20698 // If we build args for default constructor closures, those will have
20699 // been generated *before* building args for any copy constructor closures.
20700 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20701 return false;
20702 }
20703
20704 unsigned NumParams = Ctor->getNumParams();
20705 if (NumParams == 0)
20706 return false;
20707
20708 CXXDefaultArgExpr **Args =
20709 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20710
20711 if (IsCopy)
20712 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20713
20714 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20715 ExprResult R = BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Ctor, Param: Ctor->getParamDecl(i: I));
20716 CleanupVarDeclMarking();
20717 if (R.isInvalid())
20718 return true;
20719 Args[I] = cast<CXXDefaultArgExpr>(Val: R.get());
20720 }
20721
20722 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20723 return false;
20724}
20725