1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DynamicRecursiveASTVisitor.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Basic/AttributeCommonInfo.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/Specifiers.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/EnterExpressionEvaluationContext.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Ownership.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaCUDA.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/SemaObjC.h"
48#include "clang/Sema/SemaOpenMP.h"
49#include "clang/Sema/Template.h"
50#include "clang/Sema/TemplateDeduction.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86};
87
88/// VisitExpr - Visit all of the children of this expression.
89bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
90 bool IsInvalid = false;
91 for (const Stmt *SubStmt : Node->children())
92 if (SubStmt)
93 IsInvalid |= Visit(S: SubStmt);
94 return IsInvalid;
95}
96
97/// VisitDeclRefExpr - Visit a reference to a declaration, to
98/// determine whether this declaration can be used in the default
99/// argument expression.
100bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
101 const ValueDecl *Decl = dyn_cast<ValueDecl>(Val: DRE->getDecl());
102
103 if (!isa<VarDecl, BindingDecl>(Val: Decl))
104 return false;
105
106 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
107 // C++ [dcl.fct.default]p9:
108 // [...] parameters of a function shall not be used in default
109 // argument expressions, even if they are not evaluated. [...]
110 //
111 // C++17 [dcl.fct.default]p9 (by CWG 2082):
112 // [...] A parameter shall not appear as a potentially-evaluated
113 // expression in a default argument. [...]
114 //
115 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
116 return S.Diag(Loc: DRE->getBeginLoc(),
117 DiagID: diag::err_param_default_argument_references_param)
118 << Param->getDeclName() << DefaultArg->getSourceRange();
119 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
120 // C++ [dcl.fct.default]p7:
121 // Local variables shall not be used in default argument
122 // expressions.
123 //
124 // C++17 [dcl.fct.default]p7 (by CWG 2082):
125 // A local variable shall not appear as a potentially-evaluated
126 // expression in a default argument.
127 //
128 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
129 // Note: A local variable cannot be odr-used (6.3) in a default
130 // argument.
131 //
132 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
133 return S.Diag(Loc: DRE->getBeginLoc(),
134 DiagID: diag::err_param_default_argument_references_local)
135 << Decl << DefaultArg->getSourceRange();
136 }
137 return false;
138}
139
140/// VisitCXXThisExpr - Visit a C++ "this" expression.
141bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
142 // C++ [dcl.fct.default]p8:
143 // The keyword this shall not be used in a default argument of a
144 // member function.
145 return S.Diag(Loc: ThisE->getBeginLoc(),
146 DiagID: diag::err_param_default_argument_references_this)
147 << ThisE->getSourceRange();
148}
149
150bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
151 const PseudoObjectExpr *POE) {
152 bool Invalid = false;
153 for (const Expr *E : POE->semantics()) {
154 // Look through bindings.
155 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
156 E = OVE->getSourceExpr();
157 assert(E && "pseudo-object binding without source expression?");
158 }
159
160 Invalid |= Visit(S: E);
161 }
162 return Invalid;
163}
164
165bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
166 // [expr.prim.lambda.capture]p9
167 // a lambda-expression appearing in a default argument cannot implicitly or
168 // explicitly capture any local entity. Such a lambda-expression can still
169 // have an init-capture if any full-expression in its initializer satisfies
170 // the constraints of an expression appearing in a default argument.
171 bool Invalid = false;
172 for (const LambdaCapture &LC : Lambda->captures()) {
173 if (!Lambda->isInitCapture(Capture: &LC))
174 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
175 // Init captures are always VarDecl.
176 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
177 Invalid |= Visit(S: D->getInit());
178 }
179 return Invalid;
180}
181} // namespace
182
183void
184Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
185 const CXXMethodDecl *Method) {
186 // If we have an MSAny spec already, don't bother.
187 if (!Method || ComputedEST == EST_MSAny)
188 return;
189
190 const FunctionProtoType *Proto
191 = Method->getType()->getAs<FunctionProtoType>();
192 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
193 if (!Proto)
194 return;
195
196 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
197
198 // If we have a throw-all spec at this point, ignore the function.
199 if (ComputedEST == EST_None)
200 return;
201
202 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
203 EST = EST_BasicNoexcept;
204
205 switch (EST) {
206 case EST_Unparsed:
207 case EST_Uninstantiated:
208 case EST_Unevaluated:
209 llvm_unreachable("should not see unresolved exception specs here");
210
211 // If this function can throw any exceptions, make a note of that.
212 case EST_MSAny:
213 case EST_None:
214 // FIXME: Whichever we see last of MSAny and None determines our result.
215 // We should make a consistent, order-independent choice here.
216 ClearExceptions();
217 ComputedEST = EST;
218 return;
219 case EST_NoexceptFalse:
220 ClearExceptions();
221 ComputedEST = EST_None;
222 return;
223 // FIXME: If the call to this decl is using any of its default arguments, we
224 // need to search them for potentially-throwing calls.
225 // If this function has a basic noexcept, it doesn't affect the outcome.
226 case EST_BasicNoexcept:
227 case EST_NoexceptTrue:
228 case EST_NoThrow:
229 return;
230 // If we're still at noexcept(true) and there's a throw() callee,
231 // change to that specification.
232 case EST_DynamicNone:
233 if (ComputedEST == EST_BasicNoexcept)
234 ComputedEST = EST_DynamicNone;
235 return;
236 case EST_DependentNoexcept:
237 llvm_unreachable(
238 "should not generate implicit declarations for dependent cases");
239 case EST_Dynamic:
240 break;
241 }
242 assert(EST == EST_Dynamic && "EST case not considered earlier.");
243 assert(ComputedEST != EST_None &&
244 "Shouldn't collect exceptions when throw-all is guaranteed.");
245 ComputedEST = EST_Dynamic;
246 // Record the exceptions in this function's exception specification.
247 for (const auto &E : Proto->exceptions())
248 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
249 Exceptions.push_back(Elt: E);
250}
251
252void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
253 if (!S || ComputedEST == EST_MSAny)
254 return;
255
256 // FIXME:
257 //
258 // C++0x [except.spec]p14:
259 // [An] implicit exception-specification specifies the type-id T if and
260 // only if T is allowed by the exception-specification of a function directly
261 // invoked by f's implicit definition; f shall allow all exceptions if any
262 // function it directly invokes allows all exceptions, and f shall allow no
263 // exceptions if every function it directly invokes allows no exceptions.
264 //
265 // Note in particular that if an implicit exception-specification is generated
266 // for a function containing a throw-expression, that specification can still
267 // be noexcept(true).
268 //
269 // Note also that 'directly invoked' is not defined in the standard, and there
270 // is no indication that we should only consider potentially-evaluated calls.
271 //
272 // Ultimately we should implement the intent of the standard: the exception
273 // specification should be the set of exceptions which can be thrown by the
274 // implicit definition. For now, we assume that any non-nothrow expression can
275 // throw any exception.
276
277 if (Self->canThrow(E: S))
278 ComputedEST = EST_None;
279}
280
281ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
282 SourceLocation EqualLoc) {
283 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
284 DiagID: diag::err_typecheck_decl_incomplete_type))
285 return true;
286
287 // C++ [dcl.fct.default]p5
288 // A default argument expression is implicitly converted (clause
289 // 4) to the parameter type. The default argument expression has
290 // the same semantic constraints as the initializer expression in
291 // a declaration of a variable of the parameter type, using the
292 // copy-initialization semantics (8.5).
293 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
294 Parm: Param);
295 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
296 EqualLoc);
297 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
298 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
299 if (Result.isInvalid())
300 return true;
301 Arg = Result.getAs<Expr>();
302
303 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
304 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
305
306 return Arg;
307}
308
309void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
310 SourceLocation EqualLoc) {
311 // Add the default argument to the parameter
312 Param->setDefaultArg(Arg);
313
314 // We have already instantiated this parameter; provide each of the
315 // instantiations with the uninstantiated default argument.
316 UnparsedDefaultArgInstantiationsMap::iterator InstPos
317 = UnparsedDefaultArgInstantiations.find(Val: Param);
318 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
319 for (auto &Instantiation : InstPos->second)
320 Instantiation->setUninstantiatedDefaultArg(Arg);
321
322 // We're done tracking this parameter's instantiations.
323 UnparsedDefaultArgInstantiations.erase(I: InstPos);
324 }
325}
326
327void
328Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
329 Expr *DefaultArg) {
330 if (!param || !DefaultArg)
331 return;
332
333 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
334 UnparsedDefaultArgLocs.erase(Val: Param);
335
336 // Default arguments are only permitted in C++
337 if (!getLangOpts().CPlusPlus) {
338 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
339 << DefaultArg->getSourceRange();
340 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
341 }
342
343 // Check for unexpanded parameter packs.
344 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
345 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
346
347 // C++11 [dcl.fct.default]p3
348 // A default argument expression [...] shall not be specified for a
349 // parameter pack.
350 if (Param->isParameterPack()) {
351 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
352 << DefaultArg->getSourceRange();
353 // Recover by discarding the default argument.
354 Param->setDefaultArg(nullptr);
355 return;
356 }
357
358 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
359 if (Result.isInvalid())
360 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
361
362 DefaultArg = Result.getAs<Expr>();
363
364 // Check that the default argument is well-formed
365 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
366 if (DefaultArgChecker.Visit(S: DefaultArg))
367 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
368
369 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
370}
371
372void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
373 SourceLocation EqualLoc,
374 SourceLocation ArgLoc) {
375 if (!param)
376 return;
377
378 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
379 Param->setUnparsedDefaultArg();
380 UnparsedDefaultArgLocs[Param] = ArgLoc;
381}
382
383void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
384 Expr *DefaultArg) {
385 if (!param)
386 return;
387
388 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
389 Param->setInvalidDecl();
390 UnparsedDefaultArgLocs.erase(Val: Param);
391 ExprResult RE;
392 if (DefaultArg) {
393 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
394 T: Param->getType().getNonReferenceType());
395 } else {
396 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
397 T: Param->getType().getNonReferenceType());
398 }
399 Param->setDefaultArg(RE.get());
400}
401
402void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
403 // C++ [dcl.fct.default]p3
404 // A default argument expression shall be specified only in the
405 // parameter-declaration-clause of a function declaration or in a
406 // template-parameter (14.1). It shall not be specified for a
407 // parameter pack. If it is specified in a
408 // parameter-declaration-clause, it shall not occur within a
409 // declarator or abstract-declarator of a parameter-declaration.
410 bool MightBeFunction = D.isFunctionDeclarationContext();
411 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
412 DeclaratorChunk &chunk = D.getTypeObject(i);
413 if (chunk.Kind == DeclaratorChunk::Function) {
414 if (MightBeFunction) {
415 // This is a function declaration. It can have default arguments, but
416 // keep looking in case its return type is a function type with default
417 // arguments.
418 MightBeFunction = false;
419 continue;
420 }
421 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
422 ++argIdx) {
423 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
424 if (Param->hasUnparsedDefaultArg()) {
425 std::unique_ptr<CachedTokens> Toks =
426 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
427 SourceRange SR;
428 if (Toks->size() > 1)
429 SR = SourceRange((*Toks)[1].getLocation(),
430 Toks->back().getLocation());
431 else
432 SR = UnparsedDefaultArgLocs[Param];
433 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
434 << SR;
435 } else if (Param->getDefaultArg()) {
436 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
437 << Param->getDefaultArg()->getSourceRange();
438 Param->setDefaultArg(nullptr);
439 }
440 }
441 } else if (chunk.Kind != DeclaratorChunk::Paren) {
442 MightBeFunction = false;
443 }
444 }
445}
446
447static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
448 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
449 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
450 });
451}
452
453bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
454 Scope *S) {
455 bool Invalid = false;
456
457 // The declaration context corresponding to the scope is the semantic
458 // parent, unless this is a local function declaration, in which case
459 // it is that surrounding function.
460 DeclContext *ScopeDC = New->isLocalExternDecl()
461 ? New->getLexicalDeclContext()
462 : New->getDeclContext();
463
464 // Find the previous declaration for the purpose of default arguments.
465 FunctionDecl *PrevForDefaultArgs = Old;
466 for (/**/; PrevForDefaultArgs;
467 // Don't bother looking back past the latest decl if this is a local
468 // extern declaration; nothing else could work.
469 PrevForDefaultArgs = New->isLocalExternDecl()
470 ? nullptr
471 : PrevForDefaultArgs->getPreviousDecl()) {
472 // Ignore hidden declarations.
473 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
474 continue;
475
476 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
477 !New->isCXXClassMember()) {
478 // Ignore default arguments of old decl if they are not in
479 // the same scope and this is not an out-of-line definition of
480 // a member function.
481 continue;
482 }
483
484 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
485 // If only one of these is a local function declaration, then they are
486 // declared in different scopes, even though isDeclInScope may think
487 // they're in the same scope. (If both are local, the scope check is
488 // sufficient, and if neither is local, then they are in the same scope.)
489 continue;
490 }
491
492 // We found the right previous declaration.
493 break;
494 }
495
496 // C++ [dcl.fct.default]p4:
497 // For non-template functions, default arguments can be added in
498 // later declarations of a function in the same
499 // scope. Declarations in different scopes have completely
500 // distinct sets of default arguments. That is, declarations in
501 // inner scopes do not acquire default arguments from
502 // declarations in outer scopes, and vice versa. In a given
503 // function declaration, all parameters subsequent to a
504 // parameter with a default argument shall have default
505 // arguments supplied in this or previous declarations. A
506 // default argument shall not be redefined by a later
507 // declaration (not even to the same value).
508 //
509 // C++ [dcl.fct.default]p6:
510 // Except for member functions of class templates, the default arguments
511 // in a member function definition that appears outside of the class
512 // definition are added to the set of default arguments provided by the
513 // member function declaration in the class definition.
514 for (unsigned p = 0, NumParams = PrevForDefaultArgs
515 ? PrevForDefaultArgs->getNumParams()
516 : 0;
517 p < NumParams; ++p) {
518 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
519 ParmVarDecl *NewParam = New->getParamDecl(i: p);
520
521 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
522 bool NewParamHasDfl = NewParam->hasDefaultArg();
523
524 if (OldParamHasDfl && NewParamHasDfl) {
525 unsigned DiagDefaultParamID =
526 diag::err_param_default_argument_redefinition;
527
528 // MSVC accepts that default parameters be redefined for member functions
529 // of template class. The new default parameter's value is ignored.
530 Invalid = true;
531 if (getLangOpts().MicrosoftExt) {
532 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
533 if (MD && MD->getParent()->getDescribedClassTemplate()) {
534 // Merge the old default argument into the new parameter.
535 NewParam->setHasInheritedDefaultArg();
536 if (OldParam->hasUninstantiatedDefaultArg())
537 NewParam->setUninstantiatedDefaultArg(
538 OldParam->getUninstantiatedDefaultArg());
539 else
540 NewParam->setDefaultArg(OldParam->getInit());
541 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
542 Invalid = false;
543 }
544 }
545
546 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
547 // hint here. Alternatively, we could walk the type-source information
548 // for NewParam to find the last source location in the type... but it
549 // isn't worth the effort right now. This is the kind of test case that
550 // is hard to get right:
551 // int f(int);
552 // void g(int (*fp)(int) = f);
553 // void g(int (*fp)(int) = &f);
554 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
555 << NewParam->getDefaultArgRange();
556
557 // Look for the function declaration where the default argument was
558 // actually written, which may be a declaration prior to Old.
559 for (auto Older = PrevForDefaultArgs;
560 OldParam->hasInheritedDefaultArg(); /**/) {
561 Older = Older->getPreviousDecl();
562 OldParam = Older->getParamDecl(i: p);
563 }
564
565 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
566 << OldParam->getDefaultArgRange();
567 } else if (OldParamHasDfl) {
568 // Merge the old default argument into the new parameter unless the new
569 // function is a friend declaration in a template class. In the latter
570 // case the default arguments will be inherited when the friend
571 // declaration will be instantiated.
572 if (New->getFriendObjectKind() == Decl::FOK_None ||
573 !New->getLexicalDeclContext()->isDependentContext()) {
574 // It's important to use getInit() here; getDefaultArg()
575 // strips off any top-level ExprWithCleanups.
576 NewParam->setHasInheritedDefaultArg();
577 if (OldParam->hasUnparsedDefaultArg())
578 NewParam->setUnparsedDefaultArg();
579 else if (OldParam->hasUninstantiatedDefaultArg())
580 NewParam->setUninstantiatedDefaultArg(
581 OldParam->getUninstantiatedDefaultArg());
582 else
583 NewParam->setDefaultArg(OldParam->getInit());
584 }
585 } else if (NewParamHasDfl) {
586 if (New->getDescribedFunctionTemplate()) {
587 // Paragraph 4, quoted above, only applies to non-template functions.
588 Diag(Loc: NewParam->getLocation(),
589 DiagID: diag::err_param_default_argument_template_redecl)
590 << NewParam->getDefaultArgRange();
591 Diag(Loc: PrevForDefaultArgs->getLocation(),
592 DiagID: diag::note_template_prev_declaration)
593 << false;
594 } else if (New->getTemplateSpecializationKind()
595 != TSK_ImplicitInstantiation &&
596 New->getTemplateSpecializationKind() != TSK_Undeclared) {
597 // C++ [temp.expr.spec]p21:
598 // Default function arguments shall not be specified in a declaration
599 // or a definition for one of the following explicit specializations:
600 // - the explicit specialization of a function template;
601 // - the explicit specialization of a member function template;
602 // - the explicit specialization of a member function of a class
603 // template where the class template specialization to which the
604 // member function specialization belongs is implicitly
605 // instantiated.
606 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
607 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
608 << New->getDeclName()
609 << NewParam->getDefaultArgRange();
610 } else if (New->getDeclContext()->isDependentContext()) {
611 // C++ [dcl.fct.default]p6 (DR217):
612 // Default arguments for a member function of a class template shall
613 // be specified on the initial declaration of the member function
614 // within the class template.
615 //
616 // Reading the tea leaves a bit in DR217 and its reference to DR205
617 // leads me to the conclusion that one cannot add default function
618 // arguments for an out-of-line definition of a member function of a
619 // dependent type.
620 int WhichKind = 2;
621 if (CXXRecordDecl *Record
622 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
623 if (Record->getDescribedClassTemplate())
624 WhichKind = 0;
625 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
626 WhichKind = 1;
627 else
628 WhichKind = 2;
629 }
630
631 Diag(Loc: NewParam->getLocation(),
632 DiagID: diag::err_param_default_argument_member_template_redecl)
633 << WhichKind
634 << NewParam->getDefaultArgRange();
635 }
636 }
637 }
638
639 // DR1344: If a default argument is added outside a class definition and that
640 // default argument makes the function a special member function, the program
641 // is ill-formed. This can only happen for constructors.
642 if (isa<CXXConstructorDecl>(Val: New) &&
643 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
644 CXXSpecialMemberKind NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)),
645 OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old));
646 if (NewSM != OldSM) {
647 ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments());
648 assert(NewParam->hasDefaultArg());
649 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
650 << NewParam->getDefaultArgRange() << NewSM;
651 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
652 }
653 }
654
655 const FunctionDecl *Def;
656 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
657 // template has a constexpr specifier then all its declarations shall
658 // contain the constexpr specifier.
659 if (New->getConstexprKind() != Old->getConstexprKind()) {
660 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
661 << New << static_cast<int>(New->getConstexprKind())
662 << static_cast<int>(Old->getConstexprKind());
663 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
664 Invalid = true;
665 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
666 Old->isDefined(Definition&: Def) &&
667 // If a friend function is inlined but does not have 'inline'
668 // specifier, it is a definition. Do not report attribute conflict
669 // in this case, redefinition will be diagnosed later.
670 (New->isInlineSpecified() ||
671 New->getFriendObjectKind() == Decl::FOK_None)) {
672 // C++11 [dcl.fcn.spec]p4:
673 // If the definition of a function appears in a translation unit before its
674 // first declaration as inline, the program is ill-formed.
675 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
676 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
677 Invalid = true;
678 }
679
680 // C++17 [temp.deduct.guide]p3:
681 // Two deduction guide declarations in the same translation unit
682 // for the same class template shall not have equivalent
683 // parameter-declaration-clauses.
684 if (isa<CXXDeductionGuideDecl>(Val: New) &&
685 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
686 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
687 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
688 }
689
690 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
691 // argument expression, that declaration shall be a definition and shall be
692 // the only declaration of the function or function template in the
693 // translation unit.
694 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
695 functionDeclHasDefaultArgument(FD: Old)) {
696 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
697 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
698 Invalid = true;
699 }
700
701 // C++11 [temp.friend]p4 (DR329):
702 // When a function is defined in a friend function declaration in a class
703 // template, the function is instantiated when the function is odr-used.
704 // The same restrictions on multiple declarations and definitions that
705 // apply to non-template function declarations and definitions also apply
706 // to these implicit definitions.
707 const FunctionDecl *OldDefinition = nullptr;
708 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
709 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
710 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
711
712 return Invalid;
713}
714
715void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
716 Diag(Loc, DiagID: getLangOpts().CPlusPlus26
717 ? diag::warn_cxx23_placeholder_var_definition
718 : diag::ext_placeholder_var_definition);
719}
720
721NamedDecl *
722Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
723 MultiTemplateParamsArg TemplateParamLists) {
724 assert(D.isDecompositionDeclarator());
725 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
726
727 // The syntax only allows a decomposition declarator as a simple-declaration,
728 // a for-range-declaration, or a condition in Clang, but we parse it in more
729 // cases than that.
730 if (!D.mayHaveDecompositionDeclarator()) {
731 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
732 << Decomp.getSourceRange();
733 return nullptr;
734 }
735
736 if (!TemplateParamLists.empty()) {
737 // C++17 [temp]/1:
738 // A template defines a family of class, functions, or variables, or an
739 // alias for a family of types.
740 //
741 // Structured bindings are not included.
742 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
743 DiagID: diag::err_decomp_decl_template);
744 return nullptr;
745 }
746
747 unsigned DiagID;
748 if (!getLangOpts().CPlusPlus17)
749 DiagID = diag::compat_pre_cxx17_decomp_decl;
750 else if (D.getContext() == DeclaratorContext::Condition)
751 DiagID = getLangOpts().CPlusPlus26
752 ? diag::compat_cxx26_decomp_decl_cond
753 : diag::compat_pre_cxx26_decomp_decl_cond;
754 else
755 DiagID = diag::compat_cxx17_decomp_decl;
756
757 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
758
759 // The semantic context is always just the current context.
760 DeclContext *const DC = CurContext;
761
762 // C++17 [dcl.dcl]/8:
763 // The decl-specifier-seq shall contain only the type-specifier auto
764 // and cv-qualifiers.
765 // C++20 [dcl.dcl]/8:
766 // If decl-specifier-seq contains any decl-specifier other than static,
767 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
768 // C++23 [dcl.pre]/6:
769 // Each decl-specifier in the decl-specifier-seq shall be static,
770 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
771 // C++23 [dcl.pre]/7:
772 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
773 // constinit, static, thread_local, auto, or a cv-qualifier
774 auto &DS = D.getDeclSpec();
775 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
776 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
777 };
778
779 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
780 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
781 };
782
783 if (auto SCS = DS.getStorageClassSpec()) {
784 if (SCS == DeclSpec::SCS_static)
785 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
786 DS.getStorageClassSpecLoc());
787 else
788 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
789 DS.getStorageClassSpecLoc());
790 }
791 if (auto TSCS = DS.getThreadStorageClassSpec())
792 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
793 DS.getThreadStorageClassSpecLoc());
794
795 if (DS.isInlineSpecified())
796 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
797
798 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
799 ConstexprSpec != ConstexprSpecKind::Unspecified) {
800 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
801 !getLangOpts().CPlusPlus26)
802 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
803 DS.getConstexprSpecLoc());
804 }
805
806 // We can't recover from it being declared as a typedef.
807 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
808 return nullptr;
809
810 // C++2a [dcl.struct.bind]p1:
811 // A cv that includes volatile is deprecated
812 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
813 getLangOpts().CPlusPlus20)
814 Diag(Loc: DS.getVolatileSpecLoc(),
815 DiagID: diag::warn_deprecated_volatile_structured_binding);
816
817 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
818 QualType R = TInfo->getType();
819
820 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
821 UPPC: UPPC_DeclarationType))
822 D.setInvalidType();
823
824 // The syntax only allows a single ref-qualifier prior to the decomposition
825 // declarator. No other declarator chunks are permitted. Also check the type
826 // specifier here.
827 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
828 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
829 (D.getNumTypeObjects() == 1 &&
830 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
831 Diag(Loc: Decomp.getLSquareLoc(),
832 DiagID: (D.hasGroupingParens() ||
833 (D.getNumTypeObjects() &&
834 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
835 ? diag::err_decomp_decl_parens
836 : diag::err_decomp_decl_type)
837 << R;
838
839 // In most cases, there's no actual problem with an explicitly-specified
840 // type, but a function type won't work here, and ActOnVariableDeclarator
841 // shouldn't be called for such a type.
842 if (R->isFunctionType())
843 D.setInvalidType();
844 }
845
846 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
847 if (DS.isConstrainedAuto()) {
848 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
849 assert(TemplRep->Kind == TNK_Concept_template &&
850 "No other template kind should be possible for a constrained auto");
851
852 SourceRange TemplRange{TemplRep->TemplateNameLoc,
853 TemplRep->RAngleLoc.isValid()
854 ? TemplRep->RAngleLoc
855 : TemplRep->TemplateNameLoc};
856 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
857 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
858 }
859
860 // Build the BindingDecls.
861 SmallVector<BindingDecl*, 8> Bindings;
862
863 // Build the BindingDecls.
864 for (auto &B : D.getDecompositionDeclarator().bindings()) {
865 // Check for name conflicts.
866 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
867 IdentifierInfo *VarName = B.Name;
868 assert(VarName && "Cannot have an unnamed binding declaration");
869
870 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
871 RedeclarationKind::ForVisibleRedeclaration);
872 LookupName(R&: Previous, S,
873 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
874
875 // It's not permitted to shadow a template parameter name.
876 if (Previous.isSingleResult() &&
877 Previous.getFoundDecl()->isTemplateParameter()) {
878 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
879 Previous.clear();
880 }
881
882 QualType QT;
883 if (B.EllipsisLoc.isValid()) {
884 if (!cast<Decl>(Val: DC)->isTemplated())
885 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
886 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
887 /*ExpectsPackInType=*/ExpectPackInType: false);
888 }
889
890 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
891
892 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
893
894 // Find the shadowed declaration before filtering for scope.
895 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
896 ? getShadowedDeclaration(D: BD, R: Previous)
897 : nullptr;
898
899 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
900 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
901 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
902 /*AllowInlineNamespace*/false);
903
904 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
905 DC->isFunctionOrMethod() && VarName->isPlaceholder();
906 if (!Previous.empty()) {
907 if (IsPlaceholder) {
908 bool sameDC = (Previous.end() - 1)
909 ->getDeclContext()
910 ->getRedeclContext()
911 ->Equals(DC: DC->getRedeclContext());
912 if (sameDC &&
913 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
914 Previous.clear();
915 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
916 }
917 } else {
918 auto *Old = Previous.getRepresentativeDecl();
919 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
920 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
921 }
922 } else if (ShadowedDecl && !D.isRedeclaration()) {
923 CheckShadow(D: BD, ShadowedDecl, R: Previous);
924 }
925 PushOnScopeChains(D: BD, S, AddToContext: true);
926 Bindings.push_back(Elt: BD);
927 ParsingInitForAutoVars.insert(Ptr: BD);
928 }
929
930 // There are no prior lookup results for the variable itself, because it
931 // is unnamed.
932 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
933 Decomp.getLSquareLoc());
934 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
935 RedeclarationKind::ForVisibleRedeclaration);
936
937 // Build the variable that holds the non-decomposed object.
938 bool AddToScope = true;
939 NamedDecl *New =
940 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
941 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
942 if (AddToScope) {
943 S->AddDecl(D: New);
944 CurContext->addHiddenDecl(D: New);
945 }
946
947 if (OpenMP().isInOpenMPDeclareTargetContext())
948 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
949
950 return New;
951}
952
953// Check the arity of the structured bindings.
954// Create the resolved pack expr if needed.
955static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
956 QualType DecompType,
957 ArrayRef<BindingDecl *> Bindings,
958 unsigned MemberCount) {
959 auto BindingWithPackItr = llvm::find_if(
960 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
961 bool HasPack = BindingWithPackItr != Bindings.end();
962 bool IsValid;
963 if (!HasPack) {
964 IsValid = Bindings.size() == MemberCount;
965 } else {
966 // There may not be more members than non-pack bindings.
967 IsValid = MemberCount >= Bindings.size() - 1;
968 }
969
970 if (IsValid && HasPack) {
971 // Create the pack expr and assign it to the binding.
972 unsigned PackSize = MemberCount - Bindings.size() + 1;
973
974 BindingDecl *BPack = *BindingWithPackItr;
975 BPack->setDecomposedDecl(DD);
976 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
977 // Create the nested BindingDecls.
978 for (unsigned I = 0; I < PackSize; ++I) {
979 BindingDecl *NestedBD = BindingDecl::Create(
980 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
981 Id: BPack->getIdentifier(), T: QualType());
982 NestedBD->setDecomposedDecl(DD);
983 NestedBDs[I] = NestedBD;
984 }
985
986 QualType PackType = S.Context.getPackExpansionType(
987 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
988 auto *PackExpr = FunctionParmPackExpr::Create(
989 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
990 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
991 }
992
993 if (IsValid)
994 return false;
995
996 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
997 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
998 << (MemberCount < Bindings.size());
999 return true;
1000}
1001
1002static bool checkSimpleDecomposition(
1003 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1004 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1005 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1006 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1007 auto *DD = cast<DecompositionDecl>(Val: Src);
1008
1009 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1010 return true;
1011
1012 unsigned I = 0;
1013 for (auto *B : DD->flat_bindings()) {
1014 SourceLocation Loc = B->getLocation();
1015 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1016 if (E.isInvalid())
1017 return true;
1018 E = GetInit(Loc, E.get(), I++);
1019 if (E.isInvalid())
1020 return true;
1021 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1022 }
1023
1024 return false;
1025}
1026
1027static bool checkArrayLikeDecomposition(Sema &S,
1028 ArrayRef<BindingDecl *> Bindings,
1029 ValueDecl *Src, QualType DecompType,
1030 const llvm::APSInt &NumElems,
1031 QualType ElemType) {
1032 return checkSimpleDecomposition(
1033 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1034 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1035 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1036 if (E.isInvalid())
1037 return ExprError();
1038 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1039 });
1040}
1041
1042static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1043 ValueDecl *Src, QualType DecompType,
1044 const ConstantArrayType *CAT) {
1045 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1046 NumElems: llvm::APSInt(CAT->getSize()),
1047 ElemType: CAT->getElementType());
1048}
1049
1050static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1051 ValueDecl *Src, QualType DecompType,
1052 const VectorType *VT) {
1053 return checkArrayLikeDecomposition(
1054 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1055 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1056 Qs: DecompType.getQualifiers()));
1057}
1058
1059static bool checkComplexDecomposition(Sema &S,
1060 ArrayRef<BindingDecl *> Bindings,
1061 ValueDecl *Src, QualType DecompType,
1062 const ComplexType *CT) {
1063 return checkSimpleDecomposition(
1064 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1065 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1066 Qs: DecompType.getQualifiers()),
1067 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1068 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1069 });
1070}
1071
1072static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1073 TemplateArgumentListInfo &Args,
1074 const TemplateParameterList *Params) {
1075 SmallString<128> SS;
1076 llvm::raw_svector_ostream OS(SS);
1077 bool First = true;
1078 unsigned I = 0;
1079 for (auto &Arg : Args.arguments()) {
1080 if (!First)
1081 OS << ", ";
1082 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1083 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1084 Policy: PrintingPolicy, TPL: Params, Idx: I));
1085 First = false;
1086 I++;
1087 }
1088 return std::string(OS.str());
1089}
1090
1091static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1092 TemplateArgumentListInfo &Args, unsigned DiagID) {
1093 auto DiagnoseMissing = [&] {
1094 if (DiagID)
1095 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1096 Args, /*Params*/ nullptr);
1097 return QualType();
1098 };
1099
1100 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1101 NamespaceDecl *Std = S.getStdNamespace();
1102 if (!Std)
1103 return DiagnoseMissing();
1104
1105 // Look up the trait itself, within namespace std. We can diagnose various
1106 // problems with this lookup even if we've been asked to not diagnose a
1107 // missing specialization, because this can only fail if the user has been
1108 // declaring their own names in namespace std or we don't support the
1109 // standard library implementation in use.
1110 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1111 Sema::LookupOrdinaryName);
1112 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1113 return DiagnoseMissing();
1114 if (Result.isAmbiguous())
1115 return QualType();
1116
1117 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1118 if (!TraitTD) {
1119 Result.suppressDiagnostics();
1120 NamedDecl *Found = *Result.begin();
1121 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1122 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1123 return QualType();
1124 }
1125
1126 // Build the template-id.
1127 QualType TraitTy = S.CheckTemplateIdType(
1128 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1129 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1130 if (TraitTy.isNull())
1131 return QualType();
1132
1133 if (!S.isCompleteType(Loc, T: TraitTy)) {
1134 if (DiagID)
1135 S.RequireCompleteType(
1136 Loc, T: TraitTy, DiagID,
1137 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1138 Params: TraitTD->getTemplateParameters()));
1139 return QualType();
1140 }
1141 return TraitTy;
1142}
1143
1144static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1145 LookupResult &MemberLookup) {
1146 assert(RD && "specialization of class template is not a class?");
1147 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1148 return MemberLookup.isAmbiguous();
1149}
1150
1151static TemplateArgumentLoc
1152getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1153 uint64_t I) {
1154 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1155 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1156}
1157
1158static TemplateArgumentLoc
1159getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1160 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1161}
1162
1163namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1164
1165static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1166 unsigned &OutSize) {
1167 EnterExpressionEvaluationContext ContextRAII(
1168 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1169
1170 // Form template argument list for tuple_size<T>.
1171 TemplateArgumentListInfo Args(Loc, Loc);
1172 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1173
1174 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1175 if (TraitTy.isNull())
1176 return IsTupleLike::NotTupleLike;
1177
1178 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1179 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1180
1181 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1182 // it's not tuple-like.
1183 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1184 return IsTupleLike::NotTupleLike;
1185
1186 // If we get this far, we've committed to the tuple interpretation, but
1187 // we can still fail if there actually isn't a usable ::value.
1188
1189 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1190 LookupResult &R;
1191 TemplateArgumentListInfo &Args;
1192 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1193 : R(R), Args(Args) {}
1194 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1195 SourceLocation Loc) override {
1196 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1197 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1198 /*Params*/ nullptr);
1199 }
1200 } Diagnoser(R, Args);
1201
1202 ExprResult E =
1203 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1204 if (E.isInvalid())
1205 return IsTupleLike::Error;
1206
1207 llvm::APSInt Size;
1208 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1209 if (E.isInvalid())
1210 return IsTupleLike::Error;
1211
1212 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1213 // an UnsignedOrNone.
1214 if (Size < 0 || Size >= UINT_MAX) {
1215 llvm::SmallVector<char, 16> Str;
1216 Size.toString(Str);
1217 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1218 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1219 /*Params=*/nullptr)
1220 << StringRef(Str.data(), Str.size());
1221 return IsTupleLike::Error;
1222 }
1223
1224 OutSize = Size.getExtValue();
1225 return IsTupleLike::TupleLike;
1226}
1227
1228/// \return std::tuple_element<I, T>::type.
1229static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1230 unsigned I, QualType T) {
1231 // Form template argument list for tuple_element<I, T>.
1232 TemplateArgumentListInfo Args(Loc, Loc);
1233 Args.addArgument(
1234 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1235 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1236
1237 QualType TraitTy =
1238 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1239 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1240 if (TraitTy.isNull())
1241 return QualType();
1242
1243 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1244 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1245 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1246 return QualType();
1247
1248 auto *TD = R.getAsSingle<TypeDecl>();
1249 if (!TD) {
1250 R.suppressDiagnostics();
1251 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1252 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1253 /*Params*/ nullptr);
1254 if (!R.empty())
1255 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1256 return QualType();
1257 }
1258
1259 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1260 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1261}
1262
1263namespace {
1264struct InitializingBinding {
1265 Sema &S;
1266 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1267 Sema::CodeSynthesisContext Ctx;
1268 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1269 Ctx.PointOfInstantiation = BD->getLocation();
1270 Ctx.Entity = BD;
1271 S.pushCodeSynthesisContext(Ctx);
1272 }
1273 ~InitializingBinding() {
1274 S.popCodeSynthesisContext();
1275 }
1276};
1277}
1278
1279static bool checkTupleLikeDecomposition(Sema &S,
1280 ArrayRef<BindingDecl *> Bindings,
1281 VarDecl *Src, QualType DecompType,
1282 unsigned NumElems) {
1283 auto *DD = cast<DecompositionDecl>(Val: Src);
1284 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1285 return true;
1286
1287 if (Bindings.empty())
1288 return false;
1289
1290 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1291
1292 // [dcl.decomp]p3:
1293 // The unqualified-id get is looked up in the scope of E by class member
1294 // access lookup ...
1295 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1296 bool UseMemberGet = false;
1297 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1298 if (auto *RD = DecompType->getAsCXXRecordDecl())
1299 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1300 if (MemberGet.isAmbiguous())
1301 return true;
1302 // ... and if that finds at least one declaration that is a function
1303 // template whose first template parameter is a non-type parameter ...
1304 for (NamedDecl *D : MemberGet) {
1305 if (FunctionTemplateDecl *FTD =
1306 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1307 TemplateParameterList *TPL = FTD->getTemplateParameters();
1308 if (TPL->size() != 0 &&
1309 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1310 // ... the initializer is e.get<i>().
1311 UseMemberGet = true;
1312 break;
1313 }
1314 }
1315 }
1316 }
1317
1318 unsigned I = 0;
1319 for (auto *B : DD->flat_bindings()) {
1320 InitializingBinding InitContext(S, B);
1321 SourceLocation Loc = B->getLocation();
1322
1323 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1324 if (E.isInvalid())
1325 return true;
1326
1327 // e is an lvalue if the type of the entity is an lvalue reference and
1328 // an xvalue otherwise
1329 if (!Src->getType()->isLValueReferenceType())
1330 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1331 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1332 FPO: FPOptionsOverride());
1333
1334 TemplateArgumentListInfo Args(Loc, Loc);
1335 Args.addArgument(
1336 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1337
1338 if (UseMemberGet) {
1339 // if [lookup of member get] finds at least one declaration, the
1340 // initializer is e.get<i-1>().
1341 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1342 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1343 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1344 if (E.isInvalid())
1345 return true;
1346
1347 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1348 } else {
1349 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1350 // in the associated namespaces.
1351 Expr *Get = UnresolvedLookupExpr::Create(
1352 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1353 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1354 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1355 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1356
1357 Expr *Arg = E.get();
1358 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1359 }
1360 if (E.isInvalid())
1361 return true;
1362 Expr *Init = E.get();
1363
1364 // Given the type T designated by std::tuple_element<i - 1, E>::type,
1365 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1366 if (T.isNull())
1367 return true;
1368
1369 // each vi is a variable of type "reference to T" initialized with the
1370 // initializer, where the reference is an lvalue reference if the
1371 // initializer is an lvalue and an rvalue reference otherwise
1372 QualType RefType =
1373 S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc, Entity: B->getDeclName());
1374 if (RefType.isNull())
1375 return true;
1376
1377 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1378 // entity and this type was never written in source code.
1379 auto *RefVD =
1380 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1381 Id: B->getDeclName().getAsIdentifierInfo(), T: RefType,
1382 /*TInfo=*/nullptr, S: Src->getStorageClass());
1383 RefVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1384 RefVD->setTSCSpec(Src->getTSCSpec());
1385 RefVD->setImplicit();
1386 if (Src->isInlineSpecified())
1387 RefVD->setInlineSpecified();
1388 RefVD->getLexicalDeclContext()->addHiddenDecl(D: RefVD);
1389
1390 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: RefVD);
1391 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1392 InitializationSequence Seq(S, Entity, Kind, Init);
1393 E = Seq.Perform(S, Entity, Kind, Args: Init);
1394 if (E.isInvalid())
1395 return true;
1396 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1397 if (E.isInvalid())
1398 return true;
1399 RefVD->setInit(E.get());
1400 S.CheckCompleteVariableDeclaration(VD: RefVD);
1401
1402 E = S.BuildDeclarationNameExpr(SS: CXXScopeSpec(),
1403 NameInfo: DeclarationNameInfo(B->getDeclName(), Loc),
1404 D: RefVD);
1405 if (E.isInvalid())
1406 return true;
1407
1408 B->setBinding(DeclaredType: T, Binding: E.get());
1409 I++;
1410 }
1411
1412 return false;
1413}
1414
1415/// Find the base class to decompose in a built-in decomposition of a class type.
1416/// This base class search is, unfortunately, not quite like any other that we
1417/// perform anywhere else in C++.
1418static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1419 const CXXRecordDecl *RD,
1420 CXXCastPath &BasePath) {
1421 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1422 CXXBasePath &Path) {
1423 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1424 };
1425
1426 const CXXRecordDecl *ClassWithFields = nullptr;
1427 AccessSpecifier AS = AS_public;
1428 if (RD->hasDirectFields())
1429 // [dcl.decomp]p4:
1430 // Otherwise, all of E's non-static data members shall be public direct
1431 // members of E ...
1432 ClassWithFields = RD;
1433 else {
1434 // ... or of ...
1435 CXXBasePaths Paths;
1436 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1437 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1438 // If no classes have fields, just decompose RD itself. (This will work
1439 // if and only if zero bindings were provided.)
1440 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1441 }
1442
1443 CXXBasePath *BestPath = nullptr;
1444 for (auto &P : Paths) {
1445 if (!BestPath)
1446 BestPath = &P;
1447 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1448 T2: BestPath->back().Base->getType())) {
1449 // ... the same ...
1450 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1451 << false << RD << BestPath->back().Base->getType()
1452 << P.back().Base->getType();
1453 return DeclAccessPair();
1454 } else if (P.Access < BestPath->Access) {
1455 BestPath = &P;
1456 }
1457 }
1458
1459 // ... unambiguous ...
1460 QualType BaseType = BestPath->back().Base->getType();
1461 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1462 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1463 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1464 return DeclAccessPair();
1465 }
1466
1467 // ... [accessible, implied by other rules] base class of E.
1468 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1469 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1470 AS = BestPath->Access;
1471
1472 ClassWithFields = BaseType->getAsCXXRecordDecl();
1473 S.BuildBasePathArray(Paths, BasePath);
1474 }
1475
1476 // The above search did not check whether the selected class itself has base
1477 // classes with fields, so check that now.
1478 CXXBasePaths Paths;
1479 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1480 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1481 << (ClassWithFields == RD) << RD << ClassWithFields
1482 << Paths.front().back().Base->getType();
1483 return DeclAccessPair();
1484 }
1485
1486 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1487}
1488
1489static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1490 const CXXRecordDecl *OrigRD,
1491 QualType DecompType,
1492 DeclAccessPair BasePair) {
1493 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1494 if (!RD)
1495 return true;
1496
1497 for (auto *FD : RD->fields()) {
1498 if (FD->isUnnamedBitField())
1499 continue;
1500
1501 // All the non-static data members are required to be nameable, so they
1502 // must all have names.
1503 if (!FD->getDeclName()) {
1504 if (RD->isLambda()) {
1505 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1506 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1507 return true;
1508 }
1509
1510 if (FD->isAnonymousStructOrUnion()) {
1511 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1512 << DecompType << FD->getType()->isUnionType();
1513 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1514 return true;
1515 }
1516
1517 // FIXME: Are there any other ways we could have an anonymous member?
1518 }
1519 // The field must be accessible in the context of the structured binding.
1520 // We already checked that the base class is accessible.
1521 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1522 // const_cast here.
1523 S.CheckStructuredBindingMemberAccess(
1524 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1525 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1526 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1527 }
1528 return false;
1529}
1530
1531static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1532 ValueDecl *Src, QualType DecompType,
1533 const CXXRecordDecl *OrigRD) {
1534 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1535 DiagID: diag::err_incomplete_type))
1536 return true;
1537
1538 CXXCastPath BasePath;
1539 DeclAccessPair BasePair =
1540 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1541 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1542 if (!RD)
1543 return true;
1544 QualType BaseType = S.Context.getQualifiedType(
1545 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1546
1547 auto *DD = cast<DecompositionDecl>(Val: Src);
1548 unsigned NumFields = llvm::count_if(
1549 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1550 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1551 return true;
1552
1553 // all of E's non-static data members shall be [...] well-formed
1554 // when named as e.name in the context of the structured binding,
1555 // E shall not have an anonymous union member, ...
1556 auto FlatBindings = DD->flat_bindings();
1557 assert(llvm::range_size(FlatBindings) == NumFields);
1558 auto FlatBindingsItr = FlatBindings.begin();
1559
1560 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1561 BasePair))
1562 return true;
1563
1564 for (auto *FD : RD->fields()) {
1565 if (FD->isUnnamedBitField())
1566 continue;
1567
1568 // We have a real field to bind.
1569 assert(FlatBindingsItr != FlatBindings.end());
1570 BindingDecl *B = *(FlatBindingsItr++);
1571 SourceLocation Loc = B->getLocation();
1572
1573 // Initialize the binding to Src.FD.
1574 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1575 if (E.isInvalid())
1576 return true;
1577 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1578 VK: VK_LValue, BasePath: &BasePath);
1579 if (E.isInvalid())
1580 return true;
1581 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1582 SS: CXXScopeSpec(), Field: FD,
1583 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1584 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1585 if (E.isInvalid())
1586 return true;
1587
1588 // If the type of the member is T, the referenced type is cv T, where cv is
1589 // the cv-qualification of the decomposition expression.
1590 //
1591 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1592 // 'const' to the type of the field.
1593 Qualifiers Q = DecompType.getQualifiers();
1594 if (FD->isMutable())
1595 Q.removeConst();
1596 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1597 }
1598
1599 return false;
1600}
1601
1602void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1603 QualType DecompType = DD->getType();
1604
1605 // If the type of the decomposition is dependent, then so is the type of
1606 // each binding.
1607 if (DecompType->isDependentType()) {
1608 // Note that all of the types are still Null or PackExpansionType.
1609 for (auto *B : DD->bindings()) {
1610 // Do not overwrite any pack type.
1611 if (B->getType().isNull())
1612 B->setType(Context.DependentTy);
1613 }
1614 return;
1615 }
1616
1617 DecompType = DecompType.getNonReferenceType();
1618 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1619
1620 // C++1z [dcl.decomp]/2:
1621 // If E is an array type [...]
1622 // As an extension, we also support decomposition of built-in complex and
1623 // vector types.
1624 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1625 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1626 DD->setInvalidDecl();
1627 return;
1628 }
1629 if (auto *VT = DecompType->getAs<VectorType>()) {
1630 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1631 DD->setInvalidDecl();
1632 return;
1633 }
1634 if (auto *CT = DecompType->getAs<ComplexType>()) {
1635 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1636 DD->setInvalidDecl();
1637 return;
1638 }
1639
1640 // C++1z [dcl.decomp]/3:
1641 // if the expression std::tuple_size<E>::value is a well-formed integral
1642 // constant expression, [...]
1643 unsigned TupleSize;
1644 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1645 case IsTupleLike::Error:
1646 DD->setInvalidDecl();
1647 return;
1648
1649 case IsTupleLike::TupleLike:
1650 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1651 DD->setInvalidDecl();
1652 return;
1653
1654 case IsTupleLike::NotTupleLike:
1655 break;
1656 }
1657
1658 // C++1z [dcl.dcl]/8:
1659 // [E shall be of array or non-union class type]
1660 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1661 if (!RD || RD->isUnion()) {
1662 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1663 << DD << !RD << DecompType;
1664 DD->setInvalidDecl();
1665 return;
1666 }
1667
1668 // C++1z [dcl.decomp]/4:
1669 // all of E's non-static data members shall be [...] direct members of
1670 // E or of the same unambiguous public base class of E, ...
1671 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1672 DD->setInvalidDecl();
1673}
1674
1675UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1676 SourceLocation Loc) {
1677 const ASTContext &Ctx = getASTContext();
1678 assert(!T->isDependentType());
1679
1680 Qualifiers Quals;
1681 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1682 Quals.removeCVRQualifiers();
1683 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1684
1685 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1686 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1687 if (auto *VT = T->getAs<VectorType>())
1688 return VT->getNumElements();
1689 if (T->getAs<ComplexType>())
1690 return 2u;
1691
1692 unsigned TupleSize;
1693 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1694 case IsTupleLike::Error:
1695 return std::nullopt;
1696 case IsTupleLike::TupleLike:
1697 return TupleSize;
1698 case IsTupleLike::NotTupleLike:
1699 break;
1700 }
1701
1702 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1703 if (!OrigRD || OrigRD->isUnion())
1704 return std::nullopt;
1705
1706 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1707 return std::nullopt;
1708
1709 CXXCastPath BasePath;
1710 DeclAccessPair BasePair =
1711 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1712 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1713 if (!RD)
1714 return std::nullopt;
1715
1716 unsigned NumFields = llvm::count_if(
1717 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1718
1719 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1720 return std::nullopt;
1721
1722 return NumFields;
1723}
1724
1725void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1726 // Shortcut if exceptions are disabled.
1727 if (!getLangOpts().CXXExceptions)
1728 return;
1729
1730 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1731 "Should only be called if types are otherwise the same.");
1732
1733 QualType NewType = New->getType();
1734 QualType OldType = Old->getType();
1735
1736 // We're only interested in pointers and references to functions, as well
1737 // as pointers to member functions.
1738 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1739 NewType = R->getPointeeType();
1740 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1741 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1742 NewType = P->getPointeeType();
1743 OldType = OldType->castAs<PointerType>()->getPointeeType();
1744 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1745 NewType = M->getPointeeType();
1746 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1747 }
1748
1749 if (!NewType->isFunctionProtoType())
1750 return;
1751
1752 // There's lots of special cases for functions. For function pointers, system
1753 // libraries are hopefully not as broken so that we don't need these
1754 // workarounds.
1755 if (CheckEquivalentExceptionSpec(
1756 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1757 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1758 New->setInvalidDecl();
1759 }
1760}
1761
1762/// CheckCXXDefaultArguments - Verify that the default arguments for a
1763/// function declaration are well-formed according to C++
1764/// [dcl.fct.default].
1765void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1766 // This checking doesn't make sense for explicit specializations; their
1767 // default arguments are determined by the declaration we're specializing,
1768 // not by FD.
1769 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1770 return;
1771 if (auto *FTD = FD->getDescribedFunctionTemplate())
1772 if (FTD->isMemberSpecialization())
1773 return;
1774
1775 unsigned NumParams = FD->getNumParams();
1776 unsigned ParamIdx = 0;
1777
1778 // Find first parameter with a default argument
1779 for (; ParamIdx < NumParams; ++ParamIdx) {
1780 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1781 if (Param->hasDefaultArg())
1782 break;
1783 }
1784
1785 // C++20 [dcl.fct.default]p4:
1786 // In a given function declaration, each parameter subsequent to a parameter
1787 // with a default argument shall have a default argument supplied in this or
1788 // a previous declaration, unless the parameter was expanded from a
1789 // parameter pack, or shall be a function parameter pack.
1790 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1791 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1792 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1793 (CurrentInstantiationScope &&
1794 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1795 continue;
1796 if (Param->isInvalidDecl())
1797 /* We already complained about this parameter. */;
1798 else if (Param->getIdentifier())
1799 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1800 << Param->getIdentifier();
1801 else
1802 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1803 }
1804}
1805
1806/// Check that the given type is a literal type. Issue a diagnostic if not,
1807/// if Kind is Diagnose.
1808/// \return \c true if a problem has been found (and optionally diagnosed).
1809template <typename... Ts>
1810static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1811 SourceLocation Loc, QualType T, unsigned DiagID,
1812 Ts &&...DiagArgs) {
1813 if (T->isDependentType())
1814 return false;
1815
1816 switch (Kind) {
1817 case Sema::CheckConstexprKind::Diagnose:
1818 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1819 std::forward<Ts>(DiagArgs)...);
1820
1821 case Sema::CheckConstexprKind::CheckValid:
1822 return !T->isLiteralType(Ctx: SemaRef.Context);
1823 }
1824
1825 llvm_unreachable("unknown CheckConstexprKind");
1826}
1827
1828/// Determine whether a destructor cannot be constexpr due to
1829static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1830 const CXXDestructorDecl *DD,
1831 Sema::CheckConstexprKind Kind) {
1832 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1833 "this check is obsolete for C++23");
1834 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1835 const CXXRecordDecl *RD =
1836 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1837 if (!RD || RD->hasConstexprDestructor())
1838 return true;
1839
1840 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1841 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1842 << static_cast<int>(DD->getConstexprKind()) << !FD
1843 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1844 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1845 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1846 }
1847 return false;
1848 };
1849
1850 const CXXRecordDecl *RD = DD->getParent();
1851 for (const CXXBaseSpecifier &B : RD->bases())
1852 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1853 return false;
1854 for (const FieldDecl *FD : RD->fields())
1855 if (!Check(FD->getLocation(), FD->getType(), FD))
1856 return false;
1857 return true;
1858}
1859
1860/// Check whether a function's parameter types are all literal types. If so,
1861/// return true. If not, produce a suitable diagnostic and return false.
1862static bool CheckConstexprParameterTypes(Sema &SemaRef,
1863 const FunctionDecl *FD,
1864 Sema::CheckConstexprKind Kind) {
1865 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1866 "this check is obsolete for C++23");
1867 unsigned ArgIndex = 0;
1868 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1869 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1870 e = FT->param_type_end();
1871 i != e; ++i, ++ArgIndex) {
1872 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1873 assert(PD && "null in a parameter list");
1874 SourceLocation ParamLoc = PD->getLocation();
1875 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1876 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1877 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1878 DiagArgs: FD->isConsteval()))
1879 return false;
1880 }
1881 return true;
1882}
1883
1884/// Check whether a function's return type is a literal type. If so, return
1885/// true. If not, produce a suitable diagnostic and return false.
1886static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1887 Sema::CheckConstexprKind Kind) {
1888 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1889 "this check is obsolete for C++23");
1890 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1891 DiagID: diag::err_constexpr_non_literal_return,
1892 DiagArgs: FD->isConsteval()))
1893 return false;
1894 return true;
1895}
1896
1897/// Get diagnostic %select index for tag kind for
1898/// record diagnostic message.
1899/// WARNING: Indexes apply to particular diagnostics only!
1900///
1901/// \returns diagnostic %select index.
1902static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1903 switch (Tag) {
1904 case TagTypeKind::Struct:
1905 return 0;
1906 case TagTypeKind::Interface:
1907 return 1;
1908 case TagTypeKind::Class:
1909 return 2;
1910 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1911 }
1912}
1913
1914static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1915 Stmt *Body,
1916 Sema::CheckConstexprKind Kind);
1917static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1918
1919bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1920 CheckConstexprKind Kind) {
1921 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1922 if (MD && MD->isInstance()) {
1923 // C++11 [dcl.constexpr]p4:
1924 // The definition of a constexpr constructor shall satisfy the following
1925 // constraints:
1926 // - the class shall not have any virtual base classes;
1927 //
1928 // FIXME: This only applies to constructors and destructors, not arbitrary
1929 // member functions.
1930 const CXXRecordDecl *RD = MD->getParent();
1931 if (RD->getNumVBases()) {
1932 if (Kind == CheckConstexprKind::CheckValid)
1933 return false;
1934
1935 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1936 << isa<CXXConstructorDecl>(Val: NewFD)
1937 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1938 for (const auto &I : RD->vbases())
1939 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1940 << I.getSourceRange();
1941 return false;
1942 }
1943 }
1944
1945 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1946 // C++11 [dcl.constexpr]p3:
1947 // The definition of a constexpr function shall satisfy the following
1948 // constraints:
1949 // - it shall not be virtual; (removed in C++20)
1950 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
1951 if (Method && Method->isVirtual()) {
1952 if (getLangOpts().CPlusPlus20) {
1953 if (Kind == CheckConstexprKind::Diagnose)
1954 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
1955 } else {
1956 if (Kind == CheckConstexprKind::CheckValid)
1957 return false;
1958
1959 Method = Method->getCanonicalDecl();
1960 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
1961
1962 // If it's not obvious why this function is virtual, find an overridden
1963 // function which uses the 'virtual' keyword.
1964 const CXXMethodDecl *WrittenVirtual = Method;
1965 while (!WrittenVirtual->isVirtualAsWritten())
1966 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1967 if (WrittenVirtual != Method)
1968 Diag(Loc: WrittenVirtual->getLocation(),
1969 DiagID: diag::note_overridden_virtual_function);
1970 return false;
1971 }
1972 }
1973
1974 // - its return type shall be a literal type; (removed in C++23)
1975 if (!getLangOpts().CPlusPlus23 &&
1976 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
1977 return false;
1978 }
1979
1980 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
1981 // A destructor can be constexpr only if the defaulted destructor could be;
1982 // we don't need to check the members and bases if we already know they all
1983 // have constexpr destructors. (removed in C++23)
1984 if (!getLangOpts().CPlusPlus23 &&
1985 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
1986 if (Kind == CheckConstexprKind::CheckValid)
1987 return false;
1988 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
1989 return false;
1990 }
1991 }
1992
1993 // - each of its parameter types shall be a literal type; (removed in C++23)
1994 if (!getLangOpts().CPlusPlus23 &&
1995 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
1996 return false;
1997
1998 Stmt *Body = NewFD->getBody();
1999 assert(Body &&
2000 "CheckConstexprFunctionDefinition called on function with no body");
2001 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2002}
2003
2004/// Check the given declaration statement is legal within a constexpr function
2005/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2006///
2007/// \return true if the body is OK (maybe only as an extension), false if we
2008/// have diagnosed a problem.
2009static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2010 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2011 Sema::CheckConstexprKind Kind) {
2012 // C++11 [dcl.constexpr]p3 and p4:
2013 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2014 // contain only
2015 for (const auto *DclIt : DS->decls()) {
2016 switch (DclIt->getKind()) {
2017 case Decl::StaticAssert:
2018 case Decl::Using:
2019 case Decl::UsingShadow:
2020 case Decl::UsingDirective:
2021 case Decl::UnresolvedUsingTypename:
2022 case Decl::UnresolvedUsingValue:
2023 case Decl::UsingEnum:
2024 // - static_assert-declarations
2025 // - using-declarations,
2026 // - using-directives,
2027 // - using-enum-declaration
2028 continue;
2029
2030 case Decl::Typedef:
2031 case Decl::TypeAlias: {
2032 // - typedef declarations and alias-declarations that do not define
2033 // classes or enumerations,
2034 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2035 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2036 // Don't allow variably-modified types in constexpr functions.
2037 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2038 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2039 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2040 << TL.getSourceRange() << TL.getType()
2041 << isa<CXXConstructorDecl>(Val: Dcl);
2042 }
2043 return false;
2044 }
2045 continue;
2046 }
2047
2048 case Decl::Enum:
2049 case Decl::CXXRecord:
2050 // C++1y allows types to be defined, not just declared.
2051 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2052 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2053 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2054 CompatDiagId: diag_compat::constexpr_type_definition)
2055 << isa<CXXConstructorDecl>(Val: Dcl);
2056 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2057 return false;
2058 }
2059 }
2060 continue;
2061
2062 case Decl::EnumConstant:
2063 case Decl::IndirectField:
2064 case Decl::ParmVar:
2065 // These can only appear with other declarations which are banned in
2066 // C++11 and permitted in C++1y, so ignore them.
2067 continue;
2068
2069 case Decl::Var:
2070 case Decl::Decomposition: {
2071 // C++1y [dcl.constexpr]p3 allows anything except:
2072 // a definition of a variable of non-literal type or of static or
2073 // thread storage duration or [before C++2a] for which no
2074 // initialization is performed.
2075 const auto *VD = cast<VarDecl>(Val: DclIt);
2076 if (VD->isThisDeclarationADefinition()) {
2077 if (VD->isStaticLocal()) {
2078 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2079 SemaRef.DiagCompat(Loc: VD->getLocation(),
2080 CompatDiagId: diag_compat::constexpr_static_var)
2081 << isa<CXXConstructorDecl>(Val: Dcl)
2082 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2083 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2084 return false;
2085 }
2086 }
2087 if (SemaRef.LangOpts.CPlusPlus23) {
2088 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2089 DiagID: diag::warn_cxx20_compat_constexpr_var,
2090 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2091 } else if (CheckLiteralType(
2092 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2093 DiagID: diag::err_constexpr_local_var_non_literal_type,
2094 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2095 return false;
2096 }
2097 if (!VD->getType()->isDependentType() &&
2098 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2099 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2100 SemaRef.DiagCompat(Loc: VD->getLocation(),
2101 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2102 << isa<CXXConstructorDecl>(Val: Dcl);
2103 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2104 return false;
2105 }
2106 continue;
2107 }
2108 }
2109 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2110 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2111 << isa<CXXConstructorDecl>(Val: Dcl);
2112 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2113 return false;
2114 }
2115 continue;
2116 }
2117
2118 case Decl::NamespaceAlias:
2119 case Decl::Function:
2120 // These are disallowed in C++11 and permitted in C++1y. Allow them
2121 // everywhere as an extension.
2122 if (!Cxx1yLoc.isValid())
2123 Cxx1yLoc = DS->getBeginLoc();
2124 continue;
2125
2126 default:
2127 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2128 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2129 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2130 }
2131 return false;
2132 }
2133 }
2134
2135 return true;
2136}
2137
2138/// Check that the given field is initialized within a constexpr constructor.
2139///
2140/// \param Dcl The constexpr constructor being checked.
2141/// \param Field The field being checked. This may be a member of an anonymous
2142/// struct or union nested within the class being checked.
2143/// \param Inits All declarations, including anonymous struct/union members and
2144/// indirect members, for which any initialization was provided.
2145/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2146/// multiple notes for different members to the same error.
2147/// \param Kind Whether we're diagnosing a constructor as written or determining
2148/// whether the formal requirements are satisfied.
2149/// \return \c false if we're checking for validity and the constructor does
2150/// not satisfy the requirements on a constexpr constructor.
2151static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2152 const FunctionDecl *Dcl,
2153 FieldDecl *Field,
2154 llvm::SmallPtrSet<Decl *, 16> &Inits,
2155 bool &Diagnosed,
2156 Sema::CheckConstexprKind Kind) {
2157 // In C++20 onwards, there's nothing to check for validity.
2158 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2159 SemaRef.getLangOpts().CPlusPlus20)
2160 return true;
2161
2162 if (Field->isInvalidDecl())
2163 return true;
2164
2165 if (Field->isUnnamedBitField())
2166 return true;
2167
2168 // Anonymous unions with no variant members and empty anonymous structs do not
2169 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2170 // indirect fields don't need initializing.
2171 if (Field->isAnonymousStructOrUnion() &&
2172 (Field->getType()->isUnionType()
2173 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2174 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2175 return true;
2176
2177 if (!Inits.count(Ptr: Field)) {
2178 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2179 if (!Diagnosed) {
2180 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2181 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2182 Diagnosed = true;
2183 }
2184 SemaRef.Diag(Loc: Field->getLocation(),
2185 DiagID: diag::note_constexpr_ctor_missing_init);
2186 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2187 return false;
2188 }
2189 } else if (Field->isAnonymousStructOrUnion()) {
2190 const auto *RD = Field->getType()->castAsRecordDecl();
2191 for (auto *I : RD->fields())
2192 // If an anonymous union contains an anonymous struct of which any member
2193 // is initialized, all members must be initialized.
2194 if (!RD->isUnion() || Inits.count(Ptr: I))
2195 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2196 Kind))
2197 return false;
2198 }
2199 return true;
2200}
2201
2202/// Check the provided statement is allowed in a constexpr function
2203/// definition.
2204static bool
2205CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2206 SmallVectorImpl<SourceLocation> &ReturnStmts,
2207 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2208 SourceLocation &Cxx2bLoc,
2209 Sema::CheckConstexprKind Kind) {
2210 // - its function-body shall be [...] a compound-statement that contains only
2211 switch (S->getStmtClass()) {
2212 case Stmt::NullStmtClass:
2213 // - null statements,
2214 return true;
2215
2216 case Stmt::DeclStmtClass:
2217 // - static_assert-declarations
2218 // - using-declarations,
2219 // - using-directives,
2220 // - typedef declarations and alias-declarations that do not define
2221 // classes or enumerations,
2222 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2223 return false;
2224 return true;
2225
2226 case Stmt::ReturnStmtClass:
2227 // - and exactly one return statement;
2228 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2229 // C++1y allows return statements in constexpr constructors.
2230 if (!Cxx1yLoc.isValid())
2231 Cxx1yLoc = S->getBeginLoc();
2232 return true;
2233 }
2234
2235 ReturnStmts.push_back(Elt: S->getBeginLoc());
2236 return true;
2237
2238 case Stmt::AttributedStmtClass:
2239 // Attributes on a statement don't affect its formal kind and hence don't
2240 // affect its validity in a constexpr function.
2241 return CheckConstexprFunctionStmt(
2242 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2243 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2244
2245 case Stmt::CompoundStmtClass: {
2246 // C++1y allows compound-statements.
2247 if (!Cxx1yLoc.isValid())
2248 Cxx1yLoc = S->getBeginLoc();
2249
2250 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2251 for (auto *BodyIt : CompStmt->body()) {
2252 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2253 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2254 return false;
2255 }
2256 return true;
2257 }
2258
2259 case Stmt::IfStmtClass: {
2260 // C++1y allows if-statements.
2261 if (!Cxx1yLoc.isValid())
2262 Cxx1yLoc = S->getBeginLoc();
2263
2264 IfStmt *If = cast<IfStmt>(Val: S);
2265 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2266 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2267 return false;
2268 if (If->getElse() &&
2269 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2270 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2271 return false;
2272 return true;
2273 }
2274
2275 case Stmt::WhileStmtClass:
2276 case Stmt::DoStmtClass:
2277 case Stmt::ForStmtClass:
2278 case Stmt::CXXForRangeStmtClass:
2279 case Stmt::ContinueStmtClass:
2280 // C++1y allows all of these. We don't allow them as extensions in C++11,
2281 // because they don't make sense without variable mutation.
2282 if (!SemaRef.getLangOpts().CPlusPlus14)
2283 break;
2284 if (!Cxx1yLoc.isValid())
2285 Cxx1yLoc = S->getBeginLoc();
2286 for (Stmt *SubStmt : S->children()) {
2287 if (SubStmt &&
2288 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2289 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2290 return false;
2291 }
2292 return true;
2293
2294 case Stmt::SwitchStmtClass:
2295 case Stmt::CaseStmtClass:
2296 case Stmt::DefaultStmtClass:
2297 case Stmt::BreakStmtClass:
2298 // C++1y allows switch-statements, and since they don't need variable
2299 // mutation, we can reasonably allow them in C++11 as an extension.
2300 if (!Cxx1yLoc.isValid())
2301 Cxx1yLoc = S->getBeginLoc();
2302 for (Stmt *SubStmt : S->children()) {
2303 if (SubStmt &&
2304 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2305 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2306 return false;
2307 }
2308 return true;
2309
2310 case Stmt::LabelStmtClass:
2311 case Stmt::GotoStmtClass:
2312 if (Cxx2bLoc.isInvalid())
2313 Cxx2bLoc = S->getBeginLoc();
2314 for (Stmt *SubStmt : S->children()) {
2315 if (SubStmt &&
2316 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2317 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2318 return false;
2319 }
2320 return true;
2321
2322 case Stmt::GCCAsmStmtClass:
2323 case Stmt::MSAsmStmtClass:
2324 // C++2a allows inline assembly statements.
2325 case Stmt::CXXTryStmtClass:
2326 if (Cxx2aLoc.isInvalid())
2327 Cxx2aLoc = S->getBeginLoc();
2328 for (Stmt *SubStmt : S->children()) {
2329 if (SubStmt &&
2330 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2331 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2332 return false;
2333 }
2334 return true;
2335
2336 case Stmt::CXXCatchStmtClass:
2337 // Do not bother checking the language mode (already covered by the
2338 // try block check).
2339 if (!CheckConstexprFunctionStmt(
2340 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2341 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2342 return false;
2343 return true;
2344
2345 default:
2346 if (!isa<Expr>(Val: S))
2347 break;
2348
2349 // C++1y allows expression-statements.
2350 if (!Cxx1yLoc.isValid())
2351 Cxx1yLoc = S->getBeginLoc();
2352 return true;
2353 }
2354
2355 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2356 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2357 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2358 }
2359 return false;
2360}
2361
2362/// Check the body for the given constexpr function declaration only contains
2363/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2364///
2365/// \return true if the body is OK, false if we have found or diagnosed a
2366/// problem.
2367static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2368 Stmt *Body,
2369 Sema::CheckConstexprKind Kind) {
2370 SmallVector<SourceLocation, 4> ReturnStmts;
2371
2372 if (isa<CXXTryStmt>(Val: Body)) {
2373 // C++11 [dcl.constexpr]p3:
2374 // The definition of a constexpr function shall satisfy the following
2375 // constraints: [...]
2376 // - its function-body shall be = delete, = default, or a
2377 // compound-statement
2378 //
2379 // C++11 [dcl.constexpr]p4:
2380 // In the definition of a constexpr constructor, [...]
2381 // - its function-body shall not be a function-try-block;
2382 //
2383 // This restriction is lifted in C++2a, as long as inner statements also
2384 // apply the general constexpr rules.
2385 switch (Kind) {
2386 case Sema::CheckConstexprKind::CheckValid:
2387 if (!SemaRef.getLangOpts().CPlusPlus20)
2388 return false;
2389 break;
2390
2391 case Sema::CheckConstexprKind::Diagnose:
2392 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2393 CompatDiagId: diag_compat::constexpr_function_try_block)
2394 << isa<CXXConstructorDecl>(Val: Dcl);
2395 break;
2396 }
2397 }
2398
2399 // - its function-body shall be [...] a compound-statement that contains only
2400 // [... list of cases ...]
2401 //
2402 // Note that walking the children here is enough to properly check for
2403 // CompoundStmt and CXXTryStmt body.
2404 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2405 for (Stmt *SubStmt : Body->children()) {
2406 if (SubStmt &&
2407 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2408 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2409 return false;
2410 }
2411
2412 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2413 // If this is only valid as an extension, report that we don't satisfy the
2414 // constraints of the current language.
2415 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2416 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2417 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2418 return false;
2419 } else if (Cxx2bLoc.isValid()) {
2420 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2421 << isa<CXXConstructorDecl>(Val: Dcl);
2422 } else if (Cxx2aLoc.isValid()) {
2423 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2424 << isa<CXXConstructorDecl>(Val: Dcl);
2425 } else if (Cxx1yLoc.isValid()) {
2426 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2427 << isa<CXXConstructorDecl>(Val: Dcl);
2428 }
2429
2430 if (const CXXConstructorDecl *Constructor
2431 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2432 const CXXRecordDecl *RD = Constructor->getParent();
2433 // DR1359:
2434 // - every non-variant non-static data member and base class sub-object
2435 // shall be initialized;
2436 // DR1460:
2437 // - if the class is a union having variant members, exactly one of them
2438 // shall be initialized;
2439 if (RD->isUnion()) {
2440 if (Constructor->getNumCtorInitializers() == 0 &&
2441 RD->hasVariantMembers()) {
2442 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2443 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2444 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2445 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2446 return false;
2447 }
2448 }
2449 } else if (!Constructor->isDependentContext() &&
2450 !Constructor->isDelegatingConstructor()) {
2451 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2452
2453 // Skip detailed checking if we have enough initializers, and we would
2454 // allow at most one initializer per member.
2455 bool AnyAnonStructUnionMembers = false;
2456 unsigned Fields = 0;
2457 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2458 E = RD->field_end(); I != E; ++I, ++Fields) {
2459 if (I->isAnonymousStructOrUnion()) {
2460 AnyAnonStructUnionMembers = true;
2461 break;
2462 }
2463 }
2464 // DR1460:
2465 // - if the class is a union-like class, but is not a union, for each of
2466 // its anonymous union members having variant members, exactly one of
2467 // them shall be initialized;
2468 if (AnyAnonStructUnionMembers ||
2469 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2470 // Check initialization of non-static data members. Base classes are
2471 // always initialized so do not need to be checked. Dependent bases
2472 // might not have initializers in the member initializer list.
2473 llvm::SmallPtrSet<Decl *, 16> Inits;
2474 for (const auto *I: Constructor->inits()) {
2475 if (FieldDecl *FD = I->getMember())
2476 Inits.insert(Ptr: FD);
2477 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2478 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2479 }
2480
2481 bool Diagnosed = false;
2482 for (auto *I : RD->fields())
2483 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2484 Kind))
2485 return false;
2486 }
2487 }
2488 } else {
2489 if (ReturnStmts.empty()) {
2490 switch (Kind) {
2491 case Sema::CheckConstexprKind::Diagnose:
2492 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2493 return false;
2494 break;
2495
2496 case Sema::CheckConstexprKind::CheckValid:
2497 // The formal requirements don't include this rule in C++14, even
2498 // though the "must be able to produce a constant expression" rules
2499 // still imply it in some cases.
2500 if (!SemaRef.getLangOpts().CPlusPlus14)
2501 return false;
2502 break;
2503 }
2504 } else if (ReturnStmts.size() > 1) {
2505 switch (Kind) {
2506 case Sema::CheckConstexprKind::Diagnose:
2507 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2508 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2509 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2510 SemaRef.Diag(Loc: ReturnStmts[I],
2511 DiagID: diag::note_constexpr_body_previous_return);
2512 break;
2513
2514 case Sema::CheckConstexprKind::CheckValid:
2515 if (!SemaRef.getLangOpts().CPlusPlus14)
2516 return false;
2517 break;
2518 }
2519 }
2520 }
2521
2522 // C++11 [dcl.constexpr]p5:
2523 // if no function argument values exist such that the function invocation
2524 // substitution would produce a constant expression, the program is
2525 // ill-formed; no diagnostic required.
2526 // C++11 [dcl.constexpr]p3:
2527 // - every constructor call and implicit conversion used in initializing the
2528 // return value shall be one of those allowed in a constant expression.
2529 // C++11 [dcl.constexpr]p4:
2530 // - every constructor involved in initializing non-static data members and
2531 // base class sub-objects shall be a constexpr constructor.
2532 //
2533 // Note that this rule is distinct from the "requirements for a constexpr
2534 // function", so is not checked in CheckValid mode. Because the check for
2535 // constexpr potential is expensive, skip the check if the diagnostic is
2536 // disabled, the function is declared in a system header, or we're in C++23
2537 // or later mode (see https://wg21.link/P2448).
2538 bool SkipCheck =
2539 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2540 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2541 SemaRef.getDiagnostics().isIgnored(
2542 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2543 SmallVector<PartialDiagnosticAt, 8> Diags;
2544 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2545 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2546 SemaRef.Diag(Loc: Dcl->getLocation(),
2547 DiagID: diag::ext_constexpr_function_never_constant_expr)
2548 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2549 << Dcl->getNameInfo().getSourceRange();
2550 for (const auto &Diag : Diags)
2551 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2552 // Don't return false here: we allow this for compatibility in
2553 // system headers.
2554 }
2555
2556 return true;
2557}
2558
2559static bool CheckConstexprMissingReturn(Sema &SemaRef,
2560 const FunctionDecl *Dcl) {
2561 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2562 Dcl->getReturnType()->isDependentType();
2563 // Skip emitting a missing return error diagnostic for non-void functions
2564 // since C++23 no longer mandates constexpr functions to yield constant
2565 // expressions.
2566 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2567 return true;
2568
2569 // C++14 doesn't require constexpr functions to contain a 'return'
2570 // statement. We still do, unless the return type might be void, because
2571 // otherwise if there's no return statement, the function cannot
2572 // be used in a core constant expression.
2573 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2574 SemaRef.Diag(Loc: Dcl->getLocation(),
2575 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2576 : diag::err_constexpr_body_no_return)
2577 << Dcl->isConsteval();
2578 return OK;
2579}
2580
2581bool Sema::CheckImmediateEscalatingFunctionDefinition(
2582 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2583 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2584 return true;
2585 FD->setBodyContainsImmediateEscalatingExpressions(
2586 FSI->FoundImmediateEscalatingExpression);
2587 if (FSI->FoundImmediateEscalatingExpression) {
2588 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2589 if (it != UndefinedButUsed.end()) {
2590 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2591 << it->first;
2592 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2593 if (FD->isImmediateFunction() && !FD->isConsteval())
2594 DiagnoseImmediateEscalatingReason(FD);
2595 return false;
2596 }
2597 }
2598 return true;
2599}
2600
2601void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2602 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2603 "expected an immediate function");
2604 assert(FD->hasBody() && "expected the function to have a body");
2605 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2606 Sema &SemaRef;
2607
2608 const FunctionDecl *ImmediateFn;
2609 bool ImmediateFnIsConstructor;
2610 CXXConstructorDecl *CurrentConstructor = nullptr;
2611 CXXCtorInitializer *CurrentInit = nullptr;
2612
2613 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2614 : SemaRef(SemaRef), ImmediateFn(FD),
2615 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2616 ShouldVisitImplicitCode = true;
2617 ShouldVisitLambdaBody = false;
2618 }
2619
2620 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2621 SourceLocation Loc = E->getBeginLoc();
2622 SourceRange Range = E->getSourceRange();
2623 if (CurrentConstructor && CurrentInit) {
2624 Loc = CurrentConstructor->getLocation();
2625 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2626 : SourceRange();
2627 }
2628
2629 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2630
2631 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2632 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2633 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2634 << (InitializedField != nullptr)
2635 << (CurrentInit && !CurrentInit->isWritten())
2636 << InitializedField << Range;
2637 }
2638 bool TraverseCallExpr(CallExpr *E) override {
2639 if (const auto *DR =
2640 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2641 DR && DR->isImmediateEscalating()) {
2642 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2643 return false;
2644 }
2645
2646 for (Expr *A : E->arguments())
2647 if (!TraverseStmt(S: A))
2648 return false;
2649
2650 return true;
2651 }
2652
2653 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2654 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2655 ReferencedFn && E->isImmediateEscalating()) {
2656 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2657 return false;
2658 }
2659
2660 return true;
2661 }
2662
2663 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2664 CXXConstructorDecl *D = E->getConstructor();
2665 if (E->isImmediateEscalating()) {
2666 Diag(E, Fn: D, /*IsCall=*/true);
2667 return false;
2668 }
2669 return true;
2670 }
2671
2672 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2673 llvm::SaveAndRestore RAII(CurrentInit, Init);
2674 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2675 }
2676
2677 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2678 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2679 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2680 }
2681
2682 bool TraverseType(QualType T, bool TraverseQualifier) override {
2683 return true;
2684 }
2685 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2686
2687 } Visitor(*this, FD);
2688 Visitor.TraverseDecl(D: FD);
2689}
2690
2691CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2692 assert(getLangOpts().CPlusPlus && "No class names in C!");
2693
2694 if (SS && SS->isInvalid())
2695 return nullptr;
2696
2697 if (SS && SS->isNotEmpty()) {
2698 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2699 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2700 }
2701
2702 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2703}
2704
2705bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2706 const CXXScopeSpec *SS) {
2707 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2708 return CurDecl && &II == CurDecl->getIdentifier();
2709}
2710
2711bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2712 assert(getLangOpts().CPlusPlus && "No class names in C!");
2713
2714 if (!getLangOpts().SpellChecking)
2715 return false;
2716
2717 CXXRecordDecl *CurDecl;
2718 if (SS && SS->isSet() && !SS->isInvalid()) {
2719 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2720 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2721 } else
2722 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2723
2724 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2725 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2726 < II->getLength()) {
2727 II = CurDecl->getIdentifier();
2728 return true;
2729 }
2730
2731 return false;
2732}
2733
2734CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2735 SourceRange SpecifierRange,
2736 bool Virtual, AccessSpecifier Access,
2737 TypeSourceInfo *TInfo,
2738 SourceLocation EllipsisLoc) {
2739 QualType BaseType = TInfo->getType();
2740 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2741 if (BaseType->containsErrors()) {
2742 // Already emitted a diagnostic when parsing the error type.
2743 return nullptr;
2744 }
2745
2746 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2747 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2748 << TInfo->getTypeLoc().getSourceRange();
2749 EllipsisLoc = SourceLocation();
2750 }
2751
2752 auto *BaseDecl =
2753 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2754 // C++ [class.derived.general]p2:
2755 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2756 // that is not an incompletely defined class; any cv-qualifiers are
2757 // ignored.
2758 if (BaseDecl) {
2759 // C++ [class.union.general]p4:
2760 // [...] A union shall not be used as a base class.
2761 if (BaseDecl->isUnion()) {
2762 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2763 return nullptr;
2764 }
2765
2766 if (BaseType.hasQualifiers()) {
2767 std::string Quals =
2768 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2769 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2770 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2771 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2772 }
2773
2774 // For the MS ABI, propagate DLL attributes to base class templates.
2775 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2776 Context.getTargetInfo().getTriple().isPS()) {
2777 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2778 if (auto *BaseSpec =
2779 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2780 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2781 BaseLoc);
2782 }
2783 }
2784 }
2785
2786 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2787 Args: SpecifierRange)) {
2788 Class->setInvalidDecl();
2789 return nullptr;
2790 }
2791
2792 BaseDecl = BaseDecl->getDefinition();
2793 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2794
2795 // Microsoft docs say:
2796 // "If a base-class has a code_seg attribute, derived classes must have the
2797 // same attribute."
2798 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2799 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2800 if ((DerivedCSA || BaseCSA) &&
2801 (!BaseCSA || !DerivedCSA ||
2802 BaseCSA->getName() != DerivedCSA->getName())) {
2803 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2804 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2805 << BaseDecl;
2806 return nullptr;
2807 }
2808
2809 // A class which contains a flexible array member is not suitable for use as
2810 // a base class:
2811 // - If the layout determines that a base comes before another base,
2812 // the flexible array member would index into the subsequent base.
2813 // - If the layout determines that base comes before the derived class,
2814 // the flexible array member would index into the derived class.
2815 if (BaseDecl->hasFlexibleArrayMember()) {
2816 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2817 << BaseDecl->getDeclName();
2818 return nullptr;
2819 }
2820
2821 // C++ [class]p3:
2822 // If a class is marked final and it appears as a base-type-specifier in
2823 // base-clause, the program is ill-formed.
2824 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2825 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2826 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2827 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2828 << BaseDecl->getDeclName() << FA->getRange();
2829 return nullptr;
2830 }
2831
2832 // If the base class is invalid the derived class is as well.
2833 if (BaseDecl->isInvalidDecl())
2834 Class->setInvalidDecl();
2835 } else if (BaseType->isDependentType()) {
2836 // Make sure that we don't make an ill-formed AST where the type of the
2837 // Class is non-dependent and its attached base class specifier is an
2838 // dependent type, which violates invariants in many clang code paths (e.g.
2839 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2840 // explicitly mark the Class decl invalid. The diagnostic was already
2841 // emitted.
2842 if (!Class->isDependentContext())
2843 Class->setInvalidDecl();
2844 } else {
2845 // The base class is some non-dependent non-class type.
2846 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2847 return nullptr;
2848 }
2849
2850 // In HLSL, unspecified class access is public rather than private.
2851 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2852 Access == AS_none)
2853 Access = AS_public;
2854
2855 // Create the base specifier.
2856 return new (Context) CXXBaseSpecifier(
2857 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2858 Access, TInfo, EllipsisLoc);
2859}
2860
2861BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2862 const ParsedAttributesView &Attributes,
2863 bool Virtual, AccessSpecifier Access,
2864 ParsedType basetype, SourceLocation BaseLoc,
2865 SourceLocation EllipsisLoc) {
2866 if (!classdecl)
2867 return true;
2868
2869 AdjustDeclIfTemplate(Decl&: classdecl);
2870 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2871 if (!Class)
2872 return true;
2873
2874 // We haven't yet attached the base specifiers.
2875 Class->setIsParsingBaseSpecifiers();
2876
2877 // We do not support any C++11 attributes on base-specifiers yet.
2878 // Diagnose any attributes we see.
2879 for (const ParsedAttr &AL : Attributes) {
2880 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2881 continue;
2882 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2883 DiagnoseUnknownAttribute(AL);
2884 else
2885 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2886 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2887 }
2888
2889 TypeSourceInfo *TInfo = nullptr;
2890 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2891
2892 if (EllipsisLoc.isInvalid() &&
2893 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2894 UPPC: UPPC_BaseType))
2895 return true;
2896
2897 // C++ [class.union.general]p4:
2898 // [...] A union shall not have base classes.
2899 if (Class->isUnion()) {
2900 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2901 << SpecifierRange;
2902 return true;
2903 }
2904
2905 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2906 Virtual, Access, TInfo,
2907 EllipsisLoc))
2908 return BaseSpec;
2909
2910 Class->setInvalidDecl();
2911 return true;
2912}
2913
2914/// Use small set to collect indirect bases. As this is only used
2915/// locally, there's no need to abstract the small size parameter.
2916typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2917
2918/// Recursively add the bases of Type. Don't add Type itself.
2919static void
2920NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2921 const QualType &Type)
2922{
2923 // Even though the incoming type is a base, it might not be
2924 // a class -- it could be a template parm, for instance.
2925 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2926 // Iterate over its bases.
2927 for (const auto &BaseSpec : Decl->bases()) {
2928 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2929 .getUnqualifiedType();
2930 if (Set.insert(Ptr: Base).second)
2931 // If we've not already seen it, recurse.
2932 NoteIndirectBases(Context, Set, Type: Base);
2933 }
2934 }
2935}
2936
2937bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2938 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2939 if (Bases.empty())
2940 return false;
2941
2942 // Used to keep track of which base types we have already seen, so
2943 // that we can properly diagnose redundant direct base types. Note
2944 // that the key is always the unqualified canonical type of the base
2945 // class.
2946 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2947
2948 // Used to track indirect bases so we can see if a direct base is
2949 // ambiguous.
2950 IndirectBaseSet IndirectBaseTypes;
2951
2952 // Copy non-redundant base specifiers into permanent storage.
2953 unsigned NumGoodBases = 0;
2954 bool Invalid = false;
2955 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2956 QualType NewBaseType
2957 = Context.getCanonicalType(T: Bases[idx]->getType());
2958 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2959
2960 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2961 if (KnownBase) {
2962 // C++ [class.mi]p3:
2963 // A class shall not be specified as a direct base class of a
2964 // derived class more than once.
2965 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
2966 << KnownBase->getType() << Bases[idx]->getSourceRange();
2967
2968 // Delete the duplicate base class specifier; we're going to
2969 // overwrite its pointer later.
2970 Context.Deallocate(Ptr: Bases[idx]);
2971
2972 Invalid = true;
2973 } else {
2974 // Okay, add this new base class.
2975 KnownBase = Bases[idx];
2976 Bases[NumGoodBases++] = Bases[idx];
2977
2978 if (NewBaseType->isDependentType())
2979 continue;
2980 // Note this base's direct & indirect bases, if there could be ambiguity.
2981 if (Bases.size() > 1)
2982 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
2983
2984 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
2985 if (Class->isInterface() &&
2986 (!RD->isInterfaceLike() ||
2987 KnownBase->getAccessSpecifier() != AS_public)) {
2988 // The Microsoft extension __interface does not permit bases that
2989 // are not themselves public interfaces.
2990 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
2991 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
2992 << RD->getSourceRange();
2993 Invalid = true;
2994 }
2995 if (RD->hasAttr<WeakAttr>())
2996 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
2997 }
2998 }
2999 }
3000
3001 // Attach the remaining base class specifiers to the derived class.
3002 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3003
3004 // Check that the only base classes that are duplicate are virtual.
3005 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3006 // Check whether this direct base is inaccessible due to ambiguity.
3007 QualType BaseType = Bases[idx]->getType();
3008
3009 // Skip all dependent types in templates being used as base specifiers.
3010 // Checks below assume that the base specifier is a CXXRecord.
3011 if (BaseType->isDependentType())
3012 continue;
3013
3014 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3015 .getUnqualifiedType();
3016
3017 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3018 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3019 /*DetectVirtual=*/true);
3020 bool found
3021 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3022 assert(found);
3023 (void)found;
3024
3025 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3026 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3027 << BaseType << getAmbiguousPathsDisplayString(Paths)
3028 << Bases[idx]->getSourceRange();
3029 else
3030 assert(Bases[idx]->isVirtual());
3031 }
3032
3033 // Delete the base class specifier, since its data has been copied
3034 // into the CXXRecordDecl.
3035 Context.Deallocate(Ptr: Bases[idx]);
3036 }
3037
3038 return Invalid;
3039}
3040
3041void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3042 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3043 if (!ClassDecl || Bases.empty())
3044 return;
3045
3046 AdjustDeclIfTemplate(Decl&: ClassDecl);
3047 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3048}
3049
3050bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3051 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3052 if (!getLangOpts().CPlusPlus)
3053 return false;
3054
3055 if (!Base || !Derived)
3056 return false;
3057
3058 // If either the base or the derived type is invalid, don't try to
3059 // check whether one is derived from the other.
3060 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3061 return false;
3062
3063 // FIXME: In a modules build, do we need the entire path to be visible for us
3064 // to be able to use the inheritance relationship?
3065 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3066 !Derived->isBeingDefined())
3067 return false;
3068
3069 return Derived->isDerivedFrom(Base, Paths);
3070}
3071
3072bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3073 CXXRecordDecl *Base) {
3074 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3075 /*DetectVirtual=*/false);
3076 return IsDerivedFrom(Loc, Derived, Base, Paths);
3077}
3078
3079bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3080 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3081 /*DetectVirtual=*/false);
3082 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3083 Base: Base->getAsCXXRecordDecl(), Paths);
3084}
3085
3086bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3087 CXXBasePaths &Paths) {
3088 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3089 Base: Base->getAsCXXRecordDecl(), Paths);
3090}
3091
3092static void BuildBasePathArray(const CXXBasePath &Path,
3093 CXXCastPath &BasePathArray) {
3094 // We first go backward and check if we have a virtual base.
3095 // FIXME: It would be better if CXXBasePath had the base specifier for
3096 // the nearest virtual base.
3097 unsigned Start = 0;
3098 for (unsigned I = Path.size(); I != 0; --I) {
3099 if (Path[I - 1].Base->isVirtual()) {
3100 Start = I - 1;
3101 break;
3102 }
3103 }
3104
3105 // Now add all bases.
3106 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3107 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3108}
3109
3110
3111void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3112 CXXCastPath &BasePathArray) {
3113 assert(BasePathArray.empty() && "Base path array must be empty!");
3114 assert(Paths.isRecordingPaths() && "Must record paths!");
3115 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3116}
3117
3118bool
3119Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3120 unsigned InaccessibleBaseID,
3121 unsigned AmbiguousBaseConvID,
3122 SourceLocation Loc, SourceRange Range,
3123 DeclarationName Name,
3124 CXXCastPath *BasePath,
3125 bool IgnoreAccess) {
3126 // First, determine whether the path from Derived to Base is
3127 // ambiguous. This is slightly more expensive than checking whether
3128 // the Derived to Base conversion exists, because here we need to
3129 // explore multiple paths to determine if there is an ambiguity.
3130 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3131 /*DetectVirtual=*/false);
3132 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3133 if (!DerivationOkay)
3134 return true;
3135
3136 const CXXBasePath *Path = nullptr;
3137 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3138 Path = &Paths.front();
3139
3140 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3141 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3142 // user to access such bases.
3143 if (!Path && getLangOpts().MSVCCompat) {
3144 for (const CXXBasePath &PossiblePath : Paths) {
3145 if (PossiblePath.size() == 1) {
3146 Path = &PossiblePath;
3147 if (AmbiguousBaseConvID)
3148 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3149 << Base << Derived << Range;
3150 break;
3151 }
3152 }
3153 }
3154
3155 if (Path) {
3156 if (!IgnoreAccess) {
3157 // Check that the base class can be accessed.
3158 switch (
3159 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3160 case AR_inaccessible:
3161 return true;
3162 case AR_accessible:
3163 case AR_dependent:
3164 case AR_delayed:
3165 break;
3166 }
3167 }
3168
3169 // Build a base path if necessary.
3170 if (BasePath)
3171 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3172 return false;
3173 }
3174
3175 if (AmbiguousBaseConvID) {
3176 // We know that the derived-to-base conversion is ambiguous, and
3177 // we're going to produce a diagnostic. Perform the derived-to-base
3178 // search just one more time to compute all of the possible paths so
3179 // that we can print them out. This is more expensive than any of
3180 // the previous derived-to-base checks we've done, but at this point
3181 // performance isn't as much of an issue.
3182 Paths.clear();
3183 Paths.setRecordingPaths(true);
3184 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3185 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3186 (void)StillOkay;
3187
3188 // Build up a textual representation of the ambiguous paths, e.g.,
3189 // D -> B -> A, that will be used to illustrate the ambiguous
3190 // conversions in the diagnostic. We only print one of the paths
3191 // to each base class subobject.
3192 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3193
3194 Diag(Loc, DiagID: AmbiguousBaseConvID)
3195 << Derived << Base << PathDisplayStr << Range << Name;
3196 }
3197 return true;
3198}
3199
3200bool
3201Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3202 SourceLocation Loc, SourceRange Range,
3203 CXXCastPath *BasePath,
3204 bool IgnoreAccess) {
3205 return CheckDerivedToBaseConversion(
3206 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3207 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3208 BasePath, IgnoreAccess);
3209}
3210
3211std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3212 std::string PathDisplayStr;
3213 std::set<unsigned> DisplayedPaths;
3214 for (const CXXBasePath &Path : Paths) {
3215 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3216 // We haven't displayed a path to this particular base
3217 // class subobject yet.
3218 PathDisplayStr += "\n ";
3219 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3220 .getAsString();
3221 for (const CXXBasePathElement &Element : Path)
3222 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3223 }
3224 }
3225
3226 return PathDisplayStr;
3227}
3228
3229//===----------------------------------------------------------------------===//
3230// C++ class member Handling
3231//===----------------------------------------------------------------------===//
3232
3233bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3234 SourceLocation ColonLoc,
3235 const ParsedAttributesView &Attrs) {
3236 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3237 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3238 ASLoc, ColonLoc);
3239 CurContext->addHiddenDecl(D: ASDecl);
3240 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3241}
3242
3243void Sema::CheckOverrideControl(NamedDecl *D) {
3244 if (D->isInvalidDecl())
3245 return;
3246
3247 // We only care about "override" and "final" declarations.
3248 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3249 return;
3250
3251 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3252
3253 // We can't check dependent instance methods.
3254 if (MD && MD->isInstance() &&
3255 (MD->getParent()->hasAnyDependentBases() ||
3256 MD->getType()->isDependentType()))
3257 return;
3258
3259 if (MD && !MD->isVirtual()) {
3260 // If we have a non-virtual method, check if it hides a virtual method.
3261 // (In that case, it's most likely the method has the wrong type.)
3262 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3263 FindHiddenVirtualMethods(MD, OverloadedMethods);
3264
3265 if (!OverloadedMethods.empty()) {
3266 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3267 Diag(Loc: OA->getLocation(),
3268 DiagID: diag::override_keyword_hides_virtual_member_function)
3269 << "override" << (OverloadedMethods.size() > 1);
3270 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3271 Diag(Loc: FA->getLocation(),
3272 DiagID: diag::override_keyword_hides_virtual_member_function)
3273 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3274 << (OverloadedMethods.size() > 1);
3275 }
3276 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3277 MD->setInvalidDecl();
3278 return;
3279 }
3280 // Fall through into the general case diagnostic.
3281 // FIXME: We might want to attempt typo correction here.
3282 }
3283
3284 if (!MD || !MD->isVirtual()) {
3285 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3286 Diag(Loc: OA->getLocation(),
3287 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3288 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3289 D->dropAttr<OverrideAttr>();
3290 }
3291 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3292 Diag(Loc: FA->getLocation(),
3293 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3294 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3295 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3296 D->dropAttr<FinalAttr>();
3297 }
3298 return;
3299 }
3300
3301 // C++11 [class.virtual]p5:
3302 // If a function is marked with the virt-specifier override and
3303 // does not override a member function of a base class, the program is
3304 // ill-formed.
3305 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3306 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3307 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3308 << MD->getDeclName();
3309}
3310
3311void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3312 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3313 return;
3314 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3315 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3316 return;
3317
3318 SourceLocation Loc = MD->getLocation();
3319 SourceLocation SpellingLoc = Loc;
3320 if (getSourceManager().isMacroArgExpansion(Loc))
3321 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3322 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3323 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3324 return;
3325
3326 if (MD->size_overridden_methods() > 0) {
3327 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3328 unsigned DiagID =
3329 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3330 ? DiagInconsistent
3331 : DiagSuggest;
3332 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3333 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3334 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3335 };
3336 if (isa<CXXDestructorDecl>(Val: MD))
3337 EmitDiag(
3338 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3339 diag::warn_suggest_destructor_marked_not_override_overriding);
3340 else
3341 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3342 diag::warn_suggest_function_marked_not_override_overriding);
3343 }
3344}
3345
3346bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3347 const CXXMethodDecl *Old) {
3348 FinalAttr *FA = Old->getAttr<FinalAttr>();
3349 if (!FA)
3350 return false;
3351
3352 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3353 << New->getDeclName()
3354 << FA->isSpelledAsSealed();
3355 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3356 return true;
3357}
3358
3359static bool InitializationHasSideEffects(const FieldDecl &FD) {
3360 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3361 // FIXME: Destruction of ObjC lifetime types has side-effects.
3362 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3363 return !RD->isCompleteDefinition() ||
3364 !RD->hasTrivialDefaultConstructor() ||
3365 !RD->hasTrivialDestructor();
3366 return false;
3367}
3368
3369void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3370 DeclarationName FieldName,
3371 const CXXRecordDecl *RD,
3372 bool DeclIsField) {
3373 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3374 return;
3375
3376 // To record a shadowed field in a base
3377 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3378 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3379 CXXBasePath &Path) {
3380 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3381 // Record an ambiguous path directly
3382 if (Bases.find(x: Base) != Bases.end())
3383 return true;
3384 for (const auto Field : Base->lookup(Name: FieldName)) {
3385 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3386 Field->getAccess() != AS_private) {
3387 assert(Field->getAccess() != AS_none);
3388 assert(Bases.find(Base) == Bases.end());
3389 Bases[Base] = Field;
3390 return true;
3391 }
3392 }
3393 return false;
3394 };
3395
3396 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3397 /*DetectVirtual=*/true);
3398 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3399 return;
3400
3401 for (const auto &P : Paths) {
3402 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3403 auto It = Bases.find(x: Base);
3404 // Skip duplicated bases
3405 if (It == Bases.end())
3406 continue;
3407 auto BaseField = It->second;
3408 assert(BaseField->getAccess() != AS_private);
3409 if (AS_none !=
3410 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3411 Diag(Loc, DiagID: diag::warn_shadow_field)
3412 << FieldName << RD << Base << DeclIsField;
3413 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3414 Bases.erase(position: It);
3415 }
3416 }
3417}
3418
3419template <typename AttrType>
3420inline static bool HasAttribute(const QualType &T) {
3421 if (const TagDecl *TD = T->getAsTagDecl())
3422 return TD->hasAttr<AttrType>();
3423 if (const TypedefType *TDT = T->getAs<TypedefType>())
3424 return TDT->getDecl()->hasAttr<AttrType>();
3425 return false;
3426}
3427
3428static bool IsUnusedPrivateField(const FieldDecl *FD) {
3429 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3430 QualType FieldType = FD->getType();
3431 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3432 return true;
3433
3434 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3435 !FD->getParent()->isDependentContext() &&
3436 !HasAttribute<UnusedAttr>(T: FieldType) &&
3437 !InitializationHasSideEffects(FD: *FD);
3438 }
3439 return false;
3440}
3441
3442NamedDecl *
3443Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3444 MultiTemplateParamsArg TemplateParameterLists,
3445 Expr *BitWidth, const VirtSpecifiers &VS,
3446 InClassInitStyle InitStyle) {
3447 const DeclSpec &DS = D.getDeclSpec();
3448 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3449 DeclarationName Name = NameInfo.getName();
3450 SourceLocation Loc = NameInfo.getLoc();
3451
3452 // For anonymous bitfields, the location should point to the type.
3453 if (Loc.isInvalid())
3454 Loc = D.getBeginLoc();
3455
3456 assert(isa<CXXRecordDecl>(CurContext));
3457 assert(!DS.isFriendSpecified());
3458
3459 bool isFunc = D.isDeclarationOfFunction();
3460 const ParsedAttr *MSPropertyAttr =
3461 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3462
3463 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3464 // The Microsoft extension __interface only permits public member functions
3465 // and prohibits constructors, destructors, operators, non-public member
3466 // functions, static methods and data members.
3467 unsigned InvalidDecl;
3468 bool ShowDeclName = true;
3469 if (!isFunc &&
3470 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3471 InvalidDecl = 0;
3472 else if (!isFunc)
3473 InvalidDecl = 1;
3474 else if (AS != AS_public)
3475 InvalidDecl = 2;
3476 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3477 InvalidDecl = 3;
3478 else switch (Name.getNameKind()) {
3479 case DeclarationName::CXXConstructorName:
3480 InvalidDecl = 4;
3481 ShowDeclName = false;
3482 break;
3483
3484 case DeclarationName::CXXDestructorName:
3485 InvalidDecl = 5;
3486 ShowDeclName = false;
3487 break;
3488
3489 case DeclarationName::CXXOperatorName:
3490 case DeclarationName::CXXConversionFunctionName:
3491 InvalidDecl = 6;
3492 break;
3493
3494 default:
3495 InvalidDecl = 0;
3496 break;
3497 }
3498
3499 if (InvalidDecl) {
3500 if (ShowDeclName)
3501 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3502 << (InvalidDecl-1) << Name;
3503 else
3504 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3505 << (InvalidDecl-1) << "";
3506 return nullptr;
3507 }
3508 }
3509
3510 // C++ 9.2p6: A member shall not be declared to have automatic storage
3511 // duration (auto, register) or with the extern storage-class-specifier.
3512 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3513 // data members and cannot be applied to names declared const or static,
3514 // and cannot be applied to reference members.
3515 switch (DS.getStorageClassSpec()) {
3516 case DeclSpec::SCS_unspecified:
3517 case DeclSpec::SCS_typedef:
3518 case DeclSpec::SCS_static:
3519 break;
3520 case DeclSpec::SCS_mutable:
3521 if (isFunc) {
3522 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3523
3524 // FIXME: It would be nicer if the keyword was ignored only for this
3525 // declarator. Otherwise we could get follow-up errors.
3526 D.getMutableDeclSpec().ClearStorageClassSpecs();
3527 }
3528 break;
3529 default:
3530 Diag(Loc: DS.getStorageClassSpecLoc(),
3531 DiagID: diag::err_storageclass_invalid_for_member);
3532 D.getMutableDeclSpec().ClearStorageClassSpecs();
3533 break;
3534 }
3535
3536 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3537 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3538 !isFunc && TemplateParameterLists.empty();
3539
3540 if (DS.hasConstexprSpecifier() && isInstField) {
3541 SemaDiagnosticBuilder B =
3542 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3543 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3544 if (InitStyle == ICIS_NoInit) {
3545 B << 0 << 0;
3546 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3547 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3548 else {
3549 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3550 D.getMutableDeclSpec().ClearConstexprSpec();
3551 const char *PrevSpec;
3552 unsigned DiagID;
3553 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3554 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3555 (void)Failed;
3556 assert(!Failed && "Making a constexpr member const shouldn't fail");
3557 }
3558 } else {
3559 B << 1;
3560 const char *PrevSpec;
3561 unsigned DiagID;
3562 if (D.getMutableDeclSpec().SetStorageClassSpec(
3563 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3564 Policy: Context.getPrintingPolicy())) {
3565 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3566 "This is the only DeclSpec that should fail to be applied");
3567 B << 1;
3568 } else {
3569 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3570 isInstField = false;
3571 }
3572 }
3573 }
3574
3575 NamedDecl *Member;
3576 if (isInstField) {
3577 CXXScopeSpec &SS = D.getCXXScopeSpec();
3578
3579 // Data members must have identifiers for names.
3580 if (!Name.isIdentifier()) {
3581 Diag(Loc, DiagID: diag::err_bad_variable_name)
3582 << Name;
3583 return nullptr;
3584 }
3585
3586 IdentifierInfo *II = Name.getAsIdentifierInfo();
3587 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3588 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3589 << II
3590 << SourceRange(D.getName().TemplateId->LAngleLoc,
3591 D.getName().TemplateId->RAngleLoc)
3592 << D.getName().TemplateId->LAngleLoc;
3593 D.SetIdentifier(Id: II, IdLoc: Loc);
3594 }
3595
3596 if (SS.isSet() && !SS.isInvalid()) {
3597 // The user provided a superfluous scope specifier inside a class
3598 // definition:
3599 //
3600 // class X {
3601 // int X::member;
3602 // };
3603 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3604 TemplateIdAnnotation *TemplateId =
3605 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3606 ? D.getName().TemplateId
3607 : nullptr;
3608 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3609 TemplateId,
3610 /*IsMemberSpecialization=*/false);
3611 } else {
3612 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3613 << Name << SS.getRange();
3614 }
3615 SS.clear();
3616 }
3617
3618 if (MSPropertyAttr) {
3619 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3620 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3621 if (!Member)
3622 return nullptr;
3623 isInstField = false;
3624 } else {
3625 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3626 BitfieldWidth: BitWidth, InitStyle, AS);
3627 if (!Member)
3628 return nullptr;
3629 }
3630
3631 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3632 } else {
3633 Member = HandleDeclarator(S, D, TemplateParameterLists);
3634 if (!Member)
3635 return nullptr;
3636
3637 // Non-instance-fields can't have a bitfield.
3638 if (BitWidth) {
3639 if (Member->isInvalidDecl()) {
3640 // don't emit another diagnostic.
3641 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3642 // C++ 9.6p3: A bit-field shall not be a static member.
3643 // "static member 'A' cannot be a bit-field"
3644 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3645 << Name << BitWidth->getSourceRange();
3646 } else if (isa<TypedefDecl>(Val: Member)) {
3647 // "typedef member 'x' cannot be a bit-field"
3648 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3649 << Name << BitWidth->getSourceRange();
3650 } else {
3651 // A function typedef ("typedef int f(); f a;").
3652 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3653 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3654 << Name << cast<ValueDecl>(Val: Member)->getType()
3655 << BitWidth->getSourceRange();
3656 }
3657
3658 BitWidth = nullptr;
3659 Member->setInvalidDecl();
3660 }
3661
3662 NamedDecl *NonTemplateMember = Member;
3663 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3664 NonTemplateMember = FunTmpl->getTemplatedDecl();
3665 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3666 NonTemplateMember = VarTmpl->getTemplatedDecl();
3667
3668 Member->setAccess(AS);
3669
3670 // If we have declared a member function template or static data member
3671 // template, set the access of the templated declaration as well.
3672 if (NonTemplateMember != Member)
3673 NonTemplateMember->setAccess(AS);
3674
3675 // C++ [temp.deduct.guide]p3:
3676 // A deduction guide [...] for a member class template [shall be
3677 // declared] with the same access [as the template].
3678 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3679 auto *TD = DG->getDeducedTemplate();
3680 // Access specifiers are only meaningful if both the template and the
3681 // deduction guide are from the same scope.
3682 if (AS != TD->getAccess() &&
3683 TD->getDeclContext()->getRedeclContext()->Equals(
3684 DC: DG->getDeclContext()->getRedeclContext())) {
3685 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3686 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3687 << TD->getAccess();
3688 const AccessSpecDecl *LastAccessSpec = nullptr;
3689 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3690 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3691 LastAccessSpec = AccessSpec;
3692 }
3693 assert(LastAccessSpec && "differing access with no access specifier");
3694 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3695 << AS;
3696 }
3697 }
3698 }
3699
3700 if (VS.isOverrideSpecified())
3701 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3702 if (VS.isFinalSpecified())
3703 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3704 S: VS.isFinalSpelledSealed()
3705 ? FinalAttr::Keyword_sealed
3706 : FinalAttr::Keyword_final));
3707
3708 if (VS.getLastLocation().isValid()) {
3709 // Update the end location of a method that has a virt-specifiers.
3710 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3711 MD->setRangeEnd(VS.getLastLocation());
3712 }
3713
3714 CheckOverrideControl(D: Member);
3715
3716 assert((Name || isInstField) && "No identifier for non-field ?");
3717
3718 if (isInstField) {
3719 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3720 FieldCollector->Add(D: FD);
3721
3722 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3723 IsUnusedPrivateField(FD)) {
3724 // Remember all explicit private FieldDecls that have a name, no side
3725 // effects and are not part of a dependent type declaration.
3726 UnusedPrivateFields.insert(X: FD);
3727 }
3728 }
3729
3730 return Member;
3731}
3732
3733namespace {
3734 class UninitializedFieldVisitor
3735 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3736 Sema &S;
3737 // List of Decls to generate a warning on. Also remove Decls that become
3738 // initialized.
3739 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3740 // List of base classes of the record. Classes are removed after their
3741 // initializers.
3742 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3743 // Vector of decls to be removed from the Decl set prior to visiting the
3744 // nodes. These Decls may have been initialized in the prior initializer.
3745 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3746 // If non-null, add a note to the warning pointing back to the constructor.
3747 const CXXConstructorDecl *Constructor;
3748 // Variables to hold state when processing an initializer list. When
3749 // InitList is true, special case initialization of FieldDecls matching
3750 // InitListFieldDecl.
3751 bool InitList;
3752 FieldDecl *InitListFieldDecl;
3753 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3754
3755 public:
3756 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3757 UninitializedFieldVisitor(Sema &S,
3758 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3759 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3760 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3761 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3762
3763 // Returns true if the use of ME is not an uninitialized use.
3764 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3765 bool CheckReferenceOnly) {
3766 llvm::SmallVector<FieldDecl*, 4> Fields;
3767 bool ReferenceField = false;
3768 while (ME) {
3769 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3770 if (!FD)
3771 return false;
3772 Fields.push_back(Elt: FD);
3773 if (FD->getType()->isReferenceType())
3774 ReferenceField = true;
3775 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3776 }
3777
3778 // Binding a reference to an uninitialized field is not an
3779 // uninitialized use.
3780 if (CheckReferenceOnly && !ReferenceField)
3781 return true;
3782
3783 // Discard the first field since it is the field decl that is being
3784 // initialized.
3785 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3786 auto UsedIter = UsedFields.begin();
3787 const auto UsedEnd = UsedFields.end();
3788
3789 for (const unsigned Orig : InitFieldIndex) {
3790 if (UsedIter == UsedEnd)
3791 break;
3792 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3793 if (UsedIndex < Orig)
3794 return true;
3795 if (UsedIndex > Orig)
3796 break;
3797 ++UsedIter;
3798 }
3799
3800 return false;
3801 }
3802
3803 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3804 bool AddressOf) {
3805 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3806 return;
3807
3808 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3809 // or union.
3810 MemberExpr *FieldME = ME;
3811
3812 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3813
3814 Expr *Base = ME;
3815 while (MemberExpr *SubME =
3816 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3817
3818 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3819 return;
3820
3821 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3822 if (!FD->isAnonymousStructOrUnion())
3823 FieldME = SubME;
3824
3825 if (!FieldME->getType().isPODType(Context: S.Context))
3826 AllPODFields = false;
3827
3828 Base = SubME->getBase();
3829 }
3830
3831 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3832 Visit(S: Base);
3833 return;
3834 }
3835
3836 if (AddressOf && AllPODFields)
3837 return;
3838
3839 ValueDecl* FoundVD = FieldME->getMemberDecl();
3840
3841 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3842 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3843 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3844 }
3845
3846 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3847 QualType T = BaseCast->getType();
3848 if (T->isPointerType() &&
3849 BaseClasses.count(Ptr: T->getPointeeType())) {
3850 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3851 << T->getPointeeType() << FoundVD;
3852 }
3853 }
3854 }
3855
3856 if (!Decls.count(Ptr: FoundVD))
3857 return;
3858
3859 const bool IsReference = FoundVD->getType()->isReferenceType();
3860
3861 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3862 // Special checking for initializer lists.
3863 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3864 return;
3865 }
3866 } else {
3867 // Prevent double warnings on use of unbounded references.
3868 if (CheckReferenceOnly && !IsReference)
3869 return;
3870 }
3871
3872 unsigned diag = IsReference
3873 ? diag::warn_reference_field_is_uninit
3874 : diag::warn_field_is_uninit;
3875 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3876 if (Constructor)
3877 S.Diag(Loc: Constructor->getLocation(),
3878 DiagID: diag::note_uninit_in_this_constructor)
3879 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3880
3881 }
3882
3883 void HandleValue(Expr *E, bool AddressOf) {
3884 E = E->IgnoreParens();
3885
3886 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3887 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3888 AddressOf /*AddressOf*/);
3889 return;
3890 }
3891
3892 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3893 Visit(S: CO->getCond());
3894 HandleValue(E: CO->getTrueExpr(), AddressOf);
3895 HandleValue(E: CO->getFalseExpr(), AddressOf);
3896 return;
3897 }
3898
3899 if (BinaryConditionalOperator *BCO =
3900 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3901 Visit(S: BCO->getCond());
3902 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3903 return;
3904 }
3905
3906 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3907 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3908 return;
3909 }
3910
3911 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3912 switch (BO->getOpcode()) {
3913 default:
3914 break;
3915 case(BO_PtrMemD):
3916 case(BO_PtrMemI):
3917 HandleValue(E: BO->getLHS(), AddressOf);
3918 Visit(S: BO->getRHS());
3919 return;
3920 case(BO_Comma):
3921 Visit(S: BO->getLHS());
3922 HandleValue(E: BO->getRHS(), AddressOf);
3923 return;
3924 }
3925 }
3926
3927 Visit(S: E);
3928 }
3929
3930 void CheckInitListExpr(InitListExpr *ILE) {
3931 InitFieldIndex.push_back(Elt: 0);
3932 for (auto *Child : ILE->children()) {
3933 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3934 CheckInitListExpr(ILE: SubList);
3935 } else {
3936 Visit(S: Child);
3937 }
3938 ++InitFieldIndex.back();
3939 }
3940 InitFieldIndex.pop_back();
3941 }
3942
3943 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3944 FieldDecl *Field, const Type *BaseClass) {
3945 // Remove Decls that may have been initialized in the previous
3946 // initializer.
3947 for (ValueDecl* VD : DeclsToRemove)
3948 Decls.erase(Ptr: VD);
3949 DeclsToRemove.clear();
3950
3951 Constructor = FieldConstructor;
3952 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3953
3954 if (ILE && Field) {
3955 InitList = true;
3956 InitListFieldDecl = Field;
3957 InitFieldIndex.clear();
3958 CheckInitListExpr(ILE);
3959 } else {
3960 InitList = false;
3961 Visit(S: E);
3962 }
3963
3964 if (Field)
3965 Decls.erase(Ptr: Field);
3966 if (BaseClass)
3967 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
3968 }
3969
3970 void VisitMemberExpr(MemberExpr *ME) {
3971 // All uses of unbounded reference fields will warn.
3972 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
3973 }
3974
3975 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
3976 if (E->getCastKind() == CK_LValueToRValue) {
3977 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
3978 return;
3979 }
3980
3981 Inherited::VisitImplicitCastExpr(S: E);
3982 }
3983
3984 void VisitCXXConstructExpr(CXXConstructExpr *E) {
3985 if (E->getConstructor()->isCopyConstructor()) {
3986 Expr *ArgExpr = E->getArg(Arg: 0);
3987 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
3988 if (ILE->getNumInits() == 1)
3989 ArgExpr = ILE->getInit(Init: 0);
3990 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
3991 if (ICE->getCastKind() == CK_NoOp)
3992 ArgExpr = ICE->getSubExpr();
3993 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
3994 return;
3995 }
3996 Inherited::VisitCXXConstructExpr(S: E);
3997 }
3998
3999 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4000 Expr *Callee = E->getCallee();
4001 if (isa<MemberExpr>(Val: Callee)) {
4002 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4003 for (auto *Arg : E->arguments())
4004 Visit(S: Arg);
4005 return;
4006 }
4007
4008 Inherited::VisitCXXMemberCallExpr(S: E);
4009 }
4010
4011 void VisitCallExpr(CallExpr *E) {
4012 // Treat std::move as a use.
4013 if (E->isCallToStdMove()) {
4014 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4015 return;
4016 }
4017
4018 Inherited::VisitCallExpr(CE: E);
4019 }
4020
4021 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4022 Expr *Callee = E->getCallee();
4023
4024 if (isa<UnresolvedLookupExpr>(Val: Callee))
4025 return Inherited::VisitCXXOperatorCallExpr(S: E);
4026
4027 Visit(S: Callee);
4028 for (auto *Arg : E->arguments())
4029 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4030 }
4031
4032 void VisitBinaryOperator(BinaryOperator *E) {
4033 // If a field assignment is detected, remove the field from the
4034 // uninitiailized field set.
4035 if (E->getOpcode() == BO_Assign)
4036 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4037 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4038 if (!FD->getType()->isReferenceType())
4039 DeclsToRemove.push_back(Elt: FD);
4040
4041 if (E->isCompoundAssignmentOp()) {
4042 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4043 Visit(S: E->getRHS());
4044 return;
4045 }
4046
4047 Inherited::VisitBinaryOperator(S: E);
4048 }
4049
4050 void VisitUnaryOperator(UnaryOperator *E) {
4051 if (E->isIncrementDecrementOp()) {
4052 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4053 return;
4054 }
4055 if (E->getOpcode() == UO_AddrOf) {
4056 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4057 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4058 return;
4059 }
4060 }
4061
4062 Inherited::VisitUnaryOperator(S: E);
4063 }
4064 };
4065
4066 // Diagnose value-uses of fields to initialize themselves, e.g.
4067 // foo(foo)
4068 // where foo is not also a parameter to the constructor.
4069 // Also diagnose across field uninitialized use such as
4070 // x(y), y(x)
4071 // TODO: implement -Wuninitialized and fold this into that framework.
4072 static void DiagnoseUninitializedFields(
4073 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4074
4075 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4076 Loc: Constructor->getLocation())) {
4077 return;
4078 }
4079
4080 if (Constructor->isInvalidDecl())
4081 return;
4082
4083 const CXXRecordDecl *RD = Constructor->getParent();
4084
4085 if (RD->isDependentContext())
4086 return;
4087
4088 // Holds fields that are uninitialized.
4089 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4090
4091 // At the beginning, all fields are uninitialized.
4092 for (auto *I : RD->decls()) {
4093 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4094 UninitializedFields.insert(Ptr: FD);
4095 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4096 UninitializedFields.insert(Ptr: IFD->getAnonField());
4097 }
4098 }
4099
4100 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4101 for (const auto &I : RD->bases())
4102 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4103
4104 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4105 return;
4106
4107 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4108 UninitializedFields,
4109 UninitializedBaseClasses);
4110
4111 for (const auto *FieldInit : Constructor->inits()) {
4112 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4113 break;
4114
4115 Expr *InitExpr = FieldInit->getInit();
4116 if (!InitExpr)
4117 continue;
4118
4119 if (CXXDefaultInitExpr *Default =
4120 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4121 InitExpr = Default->getExpr();
4122 if (!InitExpr)
4123 continue;
4124 // In class initializers will point to the constructor.
4125 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4126 Field: FieldInit->getAnyMember(),
4127 BaseClass: FieldInit->getBaseClass());
4128 } else {
4129 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4130 Field: FieldInit->getAnyMember(),
4131 BaseClass: FieldInit->getBaseClass());
4132 }
4133 }
4134 }
4135} // namespace
4136
4137void Sema::ActOnStartCXXInClassMemberInitializer() {
4138 // Create a synthetic function scope to represent the call to the constructor
4139 // that notionally surrounds a use of this initializer.
4140 PushFunctionScope();
4141}
4142
4143void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4144 if (!D.isFunctionDeclarator())
4145 return;
4146 auto &FTI = D.getFunctionTypeInfo();
4147 if (!FTI.Params)
4148 return;
4149 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4150 FTI.NumParams)) {
4151 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4152 if (ParamDecl->getDeclName())
4153 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4154 }
4155}
4156
4157ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4158 return ActOnRequiresClause(ConstraintExpr);
4159}
4160
4161ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4162 if (ConstraintExpr.isInvalid())
4163 return ExprError();
4164
4165 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4166 UPPC: UPPC_RequiresClause))
4167 return ExprError();
4168
4169 return ConstraintExpr;
4170}
4171
4172ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4173 Expr *InitExpr,
4174 SourceLocation InitLoc) {
4175 InitializedEntity Entity =
4176 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4177 InitializationKind Kind =
4178 FD->getInClassInitStyle() == ICIS_ListInit
4179 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4180 LBraceLoc: InitExpr->getBeginLoc(),
4181 RBraceLoc: InitExpr->getEndLoc())
4182 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4183 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4184 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4185}
4186
4187void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4188 SourceLocation InitLoc,
4189 ExprResult InitExpr) {
4190 // Pop the notional constructor scope we created earlier.
4191 PopFunctionScopeInfo(WP: nullptr, D);
4192
4193 // Microsoft C++'s property declaration cannot have a default member
4194 // initializer.
4195 if (isa<MSPropertyDecl>(Val: D)) {
4196 D->setInvalidDecl();
4197 return;
4198 }
4199
4200 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4201 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4202 "must set init style when field is created");
4203
4204 if (!InitExpr.isUsable() ||
4205 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4206 FD->setInvalidDecl();
4207 ExprResult RecoveryInit =
4208 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4209 if (RecoveryInit.isUsable())
4210 FD->setInClassInitializer(RecoveryInit.get());
4211 return;
4212 }
4213
4214 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4215 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4216 // C++11 [class.base.init]p7:
4217 // The initialization of each base and member constitutes a
4218 // full-expression.
4219 if (!InitExpr.isInvalid())
4220 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4221 if (InitExpr.isInvalid()) {
4222 FD->setInvalidDecl();
4223 return;
4224 }
4225 }
4226
4227 FD->setInClassInitializer(InitExpr.get());
4228}
4229
4230/// Find the direct and/or virtual base specifiers that
4231/// correspond to the given base type, for use in base initialization
4232/// within a constructor.
4233static bool FindBaseInitializer(Sema &SemaRef,
4234 CXXRecordDecl *ClassDecl,
4235 QualType BaseType,
4236 const CXXBaseSpecifier *&DirectBaseSpec,
4237 const CXXBaseSpecifier *&VirtualBaseSpec) {
4238 // First, check for a direct base class.
4239 DirectBaseSpec = nullptr;
4240 for (const auto &Base : ClassDecl->bases()) {
4241 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4242 // We found a direct base of this type. That's what we're
4243 // initializing.
4244 DirectBaseSpec = &Base;
4245 break;
4246 }
4247 }
4248
4249 // Check for a virtual base class.
4250 // FIXME: We might be able to short-circuit this if we know in advance that
4251 // there are no virtual bases.
4252 VirtualBaseSpec = nullptr;
4253 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4254 // We haven't found a base yet; search the class hierarchy for a
4255 // virtual base class.
4256 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4257 /*DetectVirtual=*/false);
4258 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4259 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4260 Base: BaseType, Paths)) {
4261 for (const CXXBasePath &Path : Paths) {
4262 if (Path.back().Base->isVirtual()) {
4263 VirtualBaseSpec = Path.back().Base;
4264 break;
4265 }
4266 }
4267 }
4268 }
4269
4270 return DirectBaseSpec || VirtualBaseSpec;
4271}
4272
4273MemInitResult
4274Sema::ActOnMemInitializer(Decl *ConstructorD,
4275 Scope *S,
4276 CXXScopeSpec &SS,
4277 IdentifierInfo *MemberOrBase,
4278 ParsedType TemplateTypeTy,
4279 const DeclSpec &DS,
4280 SourceLocation IdLoc,
4281 Expr *InitList,
4282 SourceLocation EllipsisLoc) {
4283 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4284 DS, IdLoc, Init: InitList,
4285 EllipsisLoc);
4286}
4287
4288MemInitResult
4289Sema::ActOnMemInitializer(Decl *ConstructorD,
4290 Scope *S,
4291 CXXScopeSpec &SS,
4292 IdentifierInfo *MemberOrBase,
4293 ParsedType TemplateTypeTy,
4294 const DeclSpec &DS,
4295 SourceLocation IdLoc,
4296 SourceLocation LParenLoc,
4297 ArrayRef<Expr *> Args,
4298 SourceLocation RParenLoc,
4299 SourceLocation EllipsisLoc) {
4300 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4301 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4302 DS, IdLoc, Init: List, EllipsisLoc);
4303}
4304
4305namespace {
4306
4307// Callback to only accept typo corrections that can be a valid C++ member
4308// initializer: either a non-static field member or a base class.
4309class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4310public:
4311 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4312 : ClassDecl(ClassDecl) {}
4313
4314 bool ValidateCandidate(const TypoCorrection &candidate) override {
4315 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4316 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4317 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4318 return isa<TypeDecl>(Val: ND);
4319 }
4320 return false;
4321 }
4322
4323 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4324 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4325 }
4326
4327private:
4328 CXXRecordDecl *ClassDecl;
4329};
4330
4331}
4332
4333bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4334 RecordDecl *ClassDecl,
4335 const IdentifierInfo *Name) {
4336 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4337 DeclContextLookupResult::iterator Found =
4338 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4339 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4340 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4341 });
4342 // We did not find a placeholder variable
4343 if (Found == Result.end())
4344 return false;
4345 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4346 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4347 const NamedDecl *ND = *It;
4348 if (ND->getDeclContext() != ND->getDeclContext())
4349 break;
4350 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4351 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4352 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4353 }
4354 return true;
4355}
4356
4357ValueDecl *
4358Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4359 const IdentifierInfo *MemberOrBase) {
4360 ValueDecl *ND = nullptr;
4361 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4362 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4363 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4364 if (ND) {
4365 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4366 return nullptr;
4367 break;
4368 }
4369 if (!IsPlaceholder)
4370 return cast<ValueDecl>(Val: D);
4371 ND = cast<ValueDecl>(Val: D);
4372 }
4373 }
4374 return ND;
4375}
4376
4377ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4378 CXXScopeSpec &SS,
4379 ParsedType TemplateTypeTy,
4380 IdentifierInfo *MemberOrBase) {
4381 if (SS.getScopeRep() || TemplateTypeTy)
4382 return nullptr;
4383 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4384}
4385
4386MemInitResult
4387Sema::BuildMemInitializer(Decl *ConstructorD,
4388 Scope *S,
4389 CXXScopeSpec &SS,
4390 IdentifierInfo *MemberOrBase,
4391 ParsedType TemplateTypeTy,
4392 const DeclSpec &DS,
4393 SourceLocation IdLoc,
4394 Expr *Init,
4395 SourceLocation EllipsisLoc) {
4396 if (!ConstructorD || !Init)
4397 return true;
4398
4399 AdjustDeclIfTemplate(Decl&: ConstructorD);
4400
4401 CXXConstructorDecl *Constructor
4402 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4403 if (!Constructor) {
4404 // The user wrote a constructor initializer on a function that is
4405 // not a C++ constructor. Ignore the error for now, because we may
4406 // have more member initializers coming; we'll diagnose it just
4407 // once in ActOnMemInitializers.
4408 return true;
4409 }
4410
4411 CXXRecordDecl *ClassDecl = Constructor->getParent();
4412
4413 // C++ [class.base.init]p2:
4414 // Names in a mem-initializer-id are looked up in the scope of the
4415 // constructor's class and, if not found in that scope, are looked
4416 // up in the scope containing the constructor's definition.
4417 // [Note: if the constructor's class contains a member with the
4418 // same name as a direct or virtual base class of the class, a
4419 // mem-initializer-id naming the member or base class and composed
4420 // of a single identifier refers to the class member. A
4421 // mem-initializer-id for the hidden base class may be specified
4422 // using a qualified name. ]
4423
4424 // Look for a member, first.
4425 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4426 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4427 if (EllipsisLoc.isValid())
4428 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4429 << MemberOrBase
4430 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4431
4432 return BuildMemberInitializer(Member, Init, IdLoc);
4433 }
4434 // It didn't name a member, so see if it names a class.
4435 QualType BaseType;
4436 TypeSourceInfo *TInfo = nullptr;
4437
4438 if (TemplateTypeTy) {
4439 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4440 if (BaseType.isNull())
4441 return true;
4442 } else if (DS.getTypeSpecType() == TST_decltype) {
4443 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4444 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4445 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4446 return true;
4447 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4448 BaseType =
4449 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4450 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4451 } else {
4452 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4453 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4454
4455 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4456 if (!TyD) {
4457 if (R.isAmbiguous()) return true;
4458
4459 // We don't want access-control diagnostics here.
4460 R.suppressDiagnostics();
4461
4462 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4463 bool NotUnknownSpecialization = false;
4464 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4465 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4466 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4467
4468 if (!NotUnknownSpecialization) {
4469 // When the scope specifier can refer to a member of an unknown
4470 // specialization, we take it as a type name.
4471 BaseType = CheckTypenameType(
4472 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4473 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4474 if (BaseType.isNull())
4475 return true;
4476
4477 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4478 DependentNameTypeLoc TL =
4479 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4480 if (!TL.isNull()) {
4481 TL.setNameLoc(IdLoc);
4482 TL.setElaboratedKeywordLoc(SourceLocation());
4483 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4484 }
4485
4486 R.clear();
4487 R.setLookupName(MemberOrBase);
4488 }
4489 }
4490
4491 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4492 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4493 auto *TempSpec = cast<TemplateSpecializationType>(
4494 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4495 TemplateName TN = TempSpec->getTemplateName();
4496 for (auto const &Base : ClassDecl->bases()) {
4497 auto BaseTemplate =
4498 Base.getType()->getAs<TemplateSpecializationType>();
4499 if (BaseTemplate &&
4500 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4501 /*IgnoreDeduced=*/true)) {
4502 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4503 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4504 BaseType = Base.getType();
4505 break;
4506 }
4507 }
4508 }
4509 }
4510
4511 // If no results were found, try to correct typos.
4512 TypoCorrection Corr;
4513 MemInitializerValidatorCCC CCC(ClassDecl);
4514 if (R.empty() && BaseType.isNull() &&
4515 (Corr =
4516 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4517 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4518 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4519 // We have found a non-static data member with a similar
4520 // name to what was typed; complain and initialize that
4521 // member.
4522 diagnoseTypo(Correction: Corr,
4523 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4524 << MemberOrBase << true);
4525 return BuildMemberInitializer(Member, Init, IdLoc);
4526 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4527 const CXXBaseSpecifier *DirectBaseSpec;
4528 const CXXBaseSpecifier *VirtualBaseSpec;
4529 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4530 BaseType: Context.getTypeDeclType(Decl: Type),
4531 DirectBaseSpec, VirtualBaseSpec)) {
4532 // We have found a direct or virtual base class with a
4533 // similar name to what was typed; complain and initialize
4534 // that base class.
4535 diagnoseTypo(Correction: Corr,
4536 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4537 << MemberOrBase << false,
4538 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4539
4540 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4541 : VirtualBaseSpec;
4542 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4543 << BaseSpec->getType() << BaseSpec->getSourceRange();
4544
4545 TyD = Type;
4546 }
4547 }
4548 }
4549
4550 if (!TyD && BaseType.isNull()) {
4551 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4552 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4553 return true;
4554 }
4555 }
4556
4557 if (BaseType.isNull()) {
4558 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4559
4560 TypeLocBuilder TLB;
4561 // FIXME: This is missing building the UsingType for TyD, if any.
4562 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4563 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4564 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4565 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4566 TL.setElaboratedKeywordLoc(SourceLocation());
4567 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4568 TL.setNameLoc(IdLoc);
4569 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4570 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4571 Qualifier: SS.getScopeRep(), Decl: TN);
4572 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4573 /*ElaboratedKeywordLoc=*/SourceLocation(),
4574 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4575 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4576 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4577 Qualifier: SS.getScopeRep(), D: UD);
4578 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4579 /*ElaboratedKeywordLoc=*/SourceLocation(),
4580 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4581 } else {
4582 // FIXME: What else can appear here?
4583 assert(SS.isEmpty());
4584 BaseType = Context.getTypeDeclType(Decl: TyD);
4585 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4586 }
4587 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4588 }
4589 }
4590
4591 if (!TInfo)
4592 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4593
4594 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4595}
4596
4597MemInitResult
4598Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4599 SourceLocation IdLoc) {
4600 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4601 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4602 assert((DirectMember || IndirectMember) &&
4603 "Member must be a FieldDecl or IndirectFieldDecl");
4604
4605 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4606 return true;
4607
4608 if (Member->isInvalidDecl())
4609 return true;
4610
4611 MultiExprArg Args;
4612 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4613 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4614 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4615 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4616 } else {
4617 // Template instantiation doesn't reconstruct ParenListExprs for us.
4618 Args = Init;
4619 }
4620
4621 SourceRange InitRange = Init->getSourceRange();
4622
4623 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4624 // Can't check initialization for a member of dependent type or when
4625 // any of the arguments are type-dependent expressions.
4626 DiscardCleanupsInEvaluationContext();
4627 } else {
4628 bool InitList = false;
4629 if (isa<InitListExpr>(Val: Init)) {
4630 InitList = true;
4631 Args = Init;
4632 }
4633
4634 // Initialize the member.
4635 InitializedEntity MemberEntity =
4636 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4637 : InitializedEntity::InitializeMember(Member: IndirectMember,
4638 Parent: nullptr);
4639 InitializationKind Kind =
4640 InitList ? InitializationKind::CreateDirectList(
4641 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4642 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4643 RParenLoc: InitRange.getEnd());
4644
4645 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4646 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4647 ResultType: nullptr);
4648 if (!MemberInit.isInvalid()) {
4649 // C++11 [class.base.init]p7:
4650 // The initialization of each base and member constitutes a
4651 // full-expression.
4652 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4653 /*DiscardedValue*/ false);
4654 }
4655
4656 if (MemberInit.isInvalid()) {
4657 // Args were sensible expressions but we couldn't initialize the member
4658 // from them. Preserve them in a RecoveryExpr instead.
4659 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4660 T: Member->getType())
4661 .get();
4662 if (!Init)
4663 return true;
4664 } else {
4665 Init = MemberInit.get();
4666 }
4667 }
4668
4669 if (DirectMember) {
4670 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4671 InitRange.getBegin(), Init,
4672 InitRange.getEnd());
4673 } else {
4674 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4675 InitRange.getBegin(), Init,
4676 InitRange.getEnd());
4677 }
4678}
4679
4680MemInitResult
4681Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4682 CXXRecordDecl *ClassDecl) {
4683 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4684 if (!LangOpts.CPlusPlus11)
4685 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4686 << TInfo->getTypeLoc().getSourceRange();
4687 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4688
4689 bool InitList = true;
4690 MultiExprArg Args = Init;
4691 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4692 InitList = false;
4693 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4694 }
4695
4696 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4697
4698 SourceRange InitRange = Init->getSourceRange();
4699 // Initialize the object.
4700 InitializedEntity DelegationEntity =
4701 InitializedEntity::InitializeDelegation(Type: ClassType);
4702 InitializationKind Kind =
4703 InitList ? InitializationKind::CreateDirectList(
4704 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4705 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4706 RParenLoc: InitRange.getEnd());
4707 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4708 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4709 Args, ResultType: nullptr);
4710 if (!DelegationInit.isInvalid()) {
4711 assert((DelegationInit.get()->containsErrors() ||
4712 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4713 "Delegating constructor with no target?");
4714
4715 // C++11 [class.base.init]p7:
4716 // The initialization of each base and member constitutes a
4717 // full-expression.
4718 DelegationInit = ActOnFinishFullExpr(
4719 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4720 }
4721
4722 if (DelegationInit.isInvalid()) {
4723 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4724 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4725 if (DelegationInit.isInvalid())
4726 return true;
4727 } else {
4728 // If we are in a dependent context, template instantiation will
4729 // perform this type-checking again. Just save the arguments that we
4730 // received in a ParenListExpr.
4731 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4732 // of the information that we have about the base
4733 // initializer. However, deconstructing the ASTs is a dicey process,
4734 // and this approach is far more likely to get the corner cases right.
4735 if (CurContext->isDependentContext())
4736 DelegationInit = Init;
4737 }
4738
4739 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4740 DelegationInit.getAs<Expr>(),
4741 InitRange.getEnd());
4742}
4743
4744MemInitResult
4745Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4746 Expr *Init, CXXRecordDecl *ClassDecl,
4747 SourceLocation EllipsisLoc) {
4748 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4749
4750 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4751 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4752 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4753
4754 // C++ [class.base.init]p2:
4755 // [...] Unless the mem-initializer-id names a nonstatic data
4756 // member of the constructor's class or a direct or virtual base
4757 // of that class, the mem-initializer is ill-formed. A
4758 // mem-initializer-list can initialize a base class using any
4759 // name that denotes that base class type.
4760
4761 // We can store the initializers in "as-written" form and delay analysis until
4762 // instantiation if the constructor is dependent. But not for dependent
4763 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4764 bool Dependent = CurContext->isDependentContext() &&
4765 (BaseType->isDependentType() || Init->isTypeDependent());
4766
4767 SourceRange InitRange = Init->getSourceRange();
4768 if (EllipsisLoc.isValid()) {
4769 // This is a pack expansion.
4770 if (!BaseType->containsUnexpandedParameterPack()) {
4771 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4772 << SourceRange(BaseLoc, InitRange.getEnd());
4773
4774 EllipsisLoc = SourceLocation();
4775 }
4776 } else {
4777 // Check for any unexpanded parameter packs.
4778 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4779 return true;
4780
4781 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4782 return true;
4783 }
4784
4785 // Check for direct and virtual base classes.
4786 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4787 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4788 if (!Dependent) {
4789 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4790 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4791
4792 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4793 VirtualBaseSpec);
4794
4795 // C++ [base.class.init]p2:
4796 // Unless the mem-initializer-id names a nonstatic data member of the
4797 // constructor's class or a direct or virtual base of that class, the
4798 // mem-initializer is ill-formed.
4799 if (!DirectBaseSpec && !VirtualBaseSpec) {
4800 // If the class has any dependent bases, then it's possible that
4801 // one of those types will resolve to the same type as
4802 // BaseType. Therefore, just treat this as a dependent base
4803 // class initialization. FIXME: Should we try to check the
4804 // initialization anyway? It seems odd.
4805 if (ClassDecl->hasAnyDependentBases())
4806 Dependent = true;
4807 else
4808 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4809 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4810 << BaseTInfo->getTypeLoc().getSourceRange();
4811 }
4812 }
4813
4814 if (Dependent) {
4815 DiscardCleanupsInEvaluationContext();
4816
4817 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4818 /*IsVirtual=*/false,
4819 InitRange.getBegin(), Init,
4820 InitRange.getEnd(), EllipsisLoc);
4821 }
4822
4823 // C++ [base.class.init]p2:
4824 // If a mem-initializer-id is ambiguous because it designates both
4825 // a direct non-virtual base class and an inherited virtual base
4826 // class, the mem-initializer is ill-formed.
4827 if (DirectBaseSpec && VirtualBaseSpec)
4828 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4829 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4830
4831 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4832 if (!BaseSpec)
4833 BaseSpec = VirtualBaseSpec;
4834
4835 // Initialize the base.
4836 bool InitList = true;
4837 MultiExprArg Args = Init;
4838 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4839 InitList = false;
4840 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4841 }
4842
4843 InitializedEntity BaseEntity =
4844 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4845 InitializationKind Kind =
4846 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4847 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4848 RParenLoc: InitRange.getEnd());
4849 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4850 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4851 if (!BaseInit.isInvalid()) {
4852 // C++11 [class.base.init]p7:
4853 // The initialization of each base and member constitutes a
4854 // full-expression.
4855 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4856 /*DiscardedValue*/ false);
4857 }
4858
4859 if (BaseInit.isInvalid()) {
4860 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4861 SubExprs: Args, T: BaseType);
4862 if (BaseInit.isInvalid())
4863 return true;
4864 } else {
4865 // If we are in a dependent context, template instantiation will
4866 // perform this type-checking again. Just save the arguments that we
4867 // received in a ParenListExpr.
4868 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4869 // of the information that we have about the base
4870 // initializer. However, deconstructing the ASTs is a dicey process,
4871 // and this approach is far more likely to get the corner cases right.
4872 if (CurContext->isDependentContext())
4873 BaseInit = Init;
4874 }
4875
4876 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4877 BaseSpec->isVirtual(),
4878 InitRange.getBegin(),
4879 BaseInit.getAs<Expr>(),
4880 InitRange.getEnd(), EllipsisLoc);
4881}
4882
4883// Create a static_cast\<T&&>(expr).
4884static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4885 QualType TargetType =
4886 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4887 Loc: SourceLocation(), Entity: DeclarationName());
4888 SourceLocation ExprLoc = E->getBeginLoc();
4889 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4890 T: TargetType, Loc: ExprLoc);
4891
4892 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4893 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4894 Parens: E->getSourceRange()).get();
4895}
4896
4897/// ImplicitInitializerKind - How an implicit base or member initializer should
4898/// initialize its base or member.
4899enum ImplicitInitializerKind {
4900 IIK_Default,
4901 IIK_Copy,
4902 IIK_Move,
4903 IIK_Inherit
4904};
4905
4906static bool
4907BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4908 ImplicitInitializerKind ImplicitInitKind,
4909 CXXBaseSpecifier *BaseSpec,
4910 bool IsInheritedVirtualBase,
4911 CXXCtorInitializer *&CXXBaseInit) {
4912 InitializedEntity InitEntity
4913 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4914 IsInheritedVirtualBase);
4915
4916 ExprResult BaseInit;
4917
4918 switch (ImplicitInitKind) {
4919 case IIK_Inherit:
4920 case IIK_Default: {
4921 InitializationKind InitKind
4922 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4923 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4924 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4925 break;
4926 }
4927
4928 case IIK_Move:
4929 case IIK_Copy: {
4930 bool Moving = ImplicitInitKind == IIK_Move;
4931 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
4932 QualType ParamType = Param->getType().getNonReferenceType();
4933
4934 Expr *CopyCtorArg =
4935 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
4936 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
4937 NameLoc: Constructor->getLocation(), T: ParamType,
4938 VK: VK_LValue, FoundD: nullptr);
4939
4940 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4941
4942 // Cast to the base class to avoid ambiguities.
4943 QualType ArgTy =
4944 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4945 Qs: ParamType.getQualifiers());
4946
4947 if (Moving) {
4948 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4949 }
4950
4951 CXXCastPath BasePath;
4952 BasePath.push_back(Elt: BaseSpec);
4953 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4954 CK: CK_UncheckedDerivedToBase,
4955 VK: Moving ? VK_XValue : VK_LValue,
4956 BasePath: &BasePath).get();
4957
4958 InitializationKind InitKind
4959 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4960 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4961 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4962 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
4963 break;
4964 }
4965 }
4966
4967 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
4968 if (BaseInit.isInvalid())
4969 return true;
4970
4971 CXXBaseInit =
4972 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
4973 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
4974 Loc: SourceLocation()),
4975 BaseSpec->isVirtual(),
4976 SourceLocation(),
4977 BaseInit.getAs<Expr>(),
4978 SourceLocation(),
4979 SourceLocation());
4980
4981 return false;
4982}
4983
4984static bool RefersToRValueRef(Expr *MemRef) {
4985 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
4986 return Referenced->getType()->isRValueReferenceType();
4987}
4988
4989static bool
4990BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4991 ImplicitInitializerKind ImplicitInitKind,
4992 FieldDecl *Field, IndirectFieldDecl *Indirect,
4993 CXXCtorInitializer *&CXXMemberInit) {
4994 if (Field->isInvalidDecl())
4995 return true;
4996
4997 SourceLocation Loc = Constructor->getLocation();
4998
4999 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5000 bool Moving = ImplicitInitKind == IIK_Move;
5001 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5002 QualType ParamType = Param->getType().getNonReferenceType();
5003
5004 // Suppress copying zero-width bitfields.
5005 if (Field->isZeroLengthBitField())
5006 return false;
5007
5008 Expr *MemberExprBase =
5009 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5010 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5011 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5012
5013 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5014
5015 if (Moving) {
5016 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5017 }
5018
5019 // Build a reference to this field within the parameter.
5020 CXXScopeSpec SS;
5021 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5022 Sema::LookupMemberName);
5023 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5024 : cast<ValueDecl>(Val: Field), AS: AS_public);
5025 MemberLookup.resolveKind();
5026 ExprResult CtorArg
5027 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5028 BaseType: ParamType, OpLoc: Loc,
5029 /*IsArrow=*/false,
5030 SS,
5031 /*TemplateKWLoc=*/SourceLocation(),
5032 /*FirstQualifierInScope=*/nullptr,
5033 R&: MemberLookup,
5034 /*TemplateArgs=*/nullptr,
5035 /*S*/nullptr);
5036 if (CtorArg.isInvalid())
5037 return true;
5038
5039 // C++11 [class.copy]p15:
5040 // - if a member m has rvalue reference type T&&, it is direct-initialized
5041 // with static_cast<T&&>(x.m);
5042 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5043 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5044 }
5045
5046 InitializedEntity Entity =
5047 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5048 /*Implicit*/ true)
5049 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5050 /*Implicit*/ true);
5051
5052 // Direct-initialize to use the copy constructor.
5053 InitializationKind InitKind =
5054 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5055
5056 Expr *CtorArgE = CtorArg.getAs<Expr>();
5057 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5058 ExprResult MemberInit =
5059 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5060 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5061 if (MemberInit.isInvalid())
5062 return true;
5063
5064 if (Indirect)
5065 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5066 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5067 else
5068 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5069 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5070 return false;
5071 }
5072
5073 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5074 "Unhandled implicit init kind!");
5075
5076 QualType FieldBaseElementType =
5077 SemaRef.Context.getBaseElementType(QT: Field->getType());
5078
5079 if (FieldBaseElementType->isRecordType()) {
5080 InitializedEntity InitEntity =
5081 Indirect ? InitializedEntity::InitializeMember(Member: Indirect, Parent: nullptr,
5082 /*Implicit*/ true)
5083 : InitializedEntity::InitializeMember(Member: Field, Parent: nullptr,
5084 /*Implicit*/ true);
5085 InitializationKind InitKind =
5086 InitializationKind::CreateDefault(InitLoc: Loc);
5087
5088 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5089 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5090
5091 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5092 if (MemberInit.isInvalid())
5093 return true;
5094
5095 if (Indirect)
5096 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5097 Indirect, Loc,
5098 Loc,
5099 MemberInit.get(),
5100 Loc);
5101 else
5102 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5103 Field, Loc, Loc,
5104 MemberInit.get(),
5105 Loc);
5106 return false;
5107 }
5108
5109 if (!Field->getParent()->isUnion()) {
5110 if (FieldBaseElementType->isReferenceType()) {
5111 SemaRef.Diag(Loc: Constructor->getLocation(),
5112 DiagID: diag::err_uninitialized_member_in_ctor)
5113 << (int)Constructor->isImplicit()
5114 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5115 << Field->getDeclName();
5116 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5117 return true;
5118 }
5119
5120 if (FieldBaseElementType.isConstQualified()) {
5121 SemaRef.Diag(Loc: Constructor->getLocation(),
5122 DiagID: diag::err_uninitialized_member_in_ctor)
5123 << (int)Constructor->isImplicit()
5124 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5125 << Field->getDeclName();
5126 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5127 return true;
5128 }
5129 }
5130
5131 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5132 // ARC and Weak:
5133 // Default-initialize Objective-C pointers to NULL.
5134 CXXMemberInit
5135 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5136 Loc, Loc,
5137 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5138 Loc);
5139 return false;
5140 }
5141
5142 // Nothing to initialize.
5143 CXXMemberInit = nullptr;
5144 return false;
5145}
5146
5147namespace {
5148struct BaseAndFieldInfo {
5149 Sema &S;
5150 CXXConstructorDecl *Ctor;
5151 bool AnyErrorsInInits;
5152 ImplicitInitializerKind IIK;
5153 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5154 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5155 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5156
5157 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5158 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5159 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5160 if (Ctor->getInheritedConstructor())
5161 IIK = IIK_Inherit;
5162 else if (Generated && Ctor->isCopyConstructor())
5163 IIK = IIK_Copy;
5164 else if (Generated && Ctor->isMoveConstructor())
5165 IIK = IIK_Move;
5166 else
5167 IIK = IIK_Default;
5168 }
5169
5170 bool isImplicitCopyOrMove() const {
5171 switch (IIK) {
5172 case IIK_Copy:
5173 case IIK_Move:
5174 return true;
5175
5176 case IIK_Default:
5177 case IIK_Inherit:
5178 return false;
5179 }
5180
5181 llvm_unreachable("Invalid ImplicitInitializerKind!");
5182 }
5183
5184 bool addFieldInitializer(CXXCtorInitializer *Init) {
5185 AllToInit.push_back(Elt: Init);
5186
5187 // Check whether this initializer makes the field "used".
5188 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5189 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5190
5191 return false;
5192 }
5193
5194 bool isInactiveUnionMember(FieldDecl *Field) {
5195 RecordDecl *Record = Field->getParent();
5196 if (!Record->isUnion())
5197 return false;
5198
5199 if (FieldDecl *Active =
5200 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5201 return Active != Field->getCanonicalDecl();
5202
5203 // In an implicit copy or move constructor, ignore any in-class initializer.
5204 if (isImplicitCopyOrMove())
5205 return true;
5206
5207 // If there's no explicit initialization, the field is active only if it
5208 // has an in-class initializer...
5209 if (Field->hasInClassInitializer())
5210 return false;
5211 // ... or it's an anonymous struct or union whose class has an in-class
5212 // initializer.
5213 if (!Field->isAnonymousStructOrUnion())
5214 return true;
5215 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5216 return !FieldRD->hasInClassInitializer();
5217 }
5218
5219 /// Determine whether the given field is, or is within, a union member
5220 /// that is inactive (because there was an initializer given for a different
5221 /// member of the union, or because the union was not initialized at all).
5222 bool isWithinInactiveUnionMember(FieldDecl *Field,
5223 IndirectFieldDecl *Indirect) {
5224 if (!Indirect)
5225 return isInactiveUnionMember(Field);
5226
5227 for (auto *C : Indirect->chain()) {
5228 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5229 if (Field && isInactiveUnionMember(Field))
5230 return true;
5231 }
5232 return false;
5233 }
5234};
5235}
5236
5237/// Determine whether the given type is an incomplete or zero-lenfgth
5238/// array type.
5239static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5240 if (T->isIncompleteArrayType())
5241 return true;
5242
5243 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5244 if (ArrayT->isZeroSize())
5245 return true;
5246
5247 T = ArrayT->getElementType();
5248 }
5249
5250 return false;
5251}
5252
5253static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5254 FieldDecl *Field,
5255 IndirectFieldDecl *Indirect = nullptr) {
5256 if (Field->isInvalidDecl())
5257 return false;
5258
5259 // Overwhelmingly common case: we have a direct initializer for this field.
5260 if (CXXCtorInitializer *Init =
5261 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5262 return Info.addFieldInitializer(Init);
5263
5264 // C++11 [class.base.init]p8:
5265 // if the entity is a non-static data member that has a
5266 // brace-or-equal-initializer and either
5267 // -- the constructor's class is a union and no other variant member of that
5268 // union is designated by a mem-initializer-id or
5269 // -- the constructor's class is not a union, and, if the entity is a member
5270 // of an anonymous union, no other member of that union is designated by
5271 // a mem-initializer-id,
5272 // the entity is initialized as specified in [dcl.init].
5273 //
5274 // We also apply the same rules to handle anonymous structs within anonymous
5275 // unions.
5276 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5277 return false;
5278
5279 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5280 ExprResult DIE =
5281 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5282 if (DIE.isInvalid())
5283 return true;
5284
5285 auto Entity = InitializedEntity::InitializeMember(Member: Field, Parent: nullptr, Implicit: true);
5286 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5287
5288 CXXCtorInitializer *Init;
5289 if (Indirect)
5290 Init = new (SemaRef.Context)
5291 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5292 SourceLocation(), DIE.get(), SourceLocation());
5293 else
5294 Init = new (SemaRef.Context)
5295 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5296 SourceLocation(), DIE.get(), SourceLocation());
5297 return Info.addFieldInitializer(Init);
5298 }
5299
5300 // Don't initialize incomplete or zero-length arrays.
5301 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5302 return false;
5303
5304 // Don't try to build an implicit initializer if there were semantic
5305 // errors in any of the initializers (and therefore we might be
5306 // missing some that the user actually wrote).
5307 if (Info.AnyErrorsInInits)
5308 return false;
5309
5310 CXXCtorInitializer *Init = nullptr;
5311 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5312 Indirect, CXXMemberInit&: Init))
5313 return true;
5314
5315 if (!Init)
5316 return false;
5317
5318 return Info.addFieldInitializer(Init);
5319}
5320
5321bool
5322Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5323 CXXCtorInitializer *Initializer) {
5324 assert(Initializer->isDelegatingInitializer());
5325 Constructor->setNumCtorInitializers(1);
5326 CXXCtorInitializer **initializer =
5327 new (Context) CXXCtorInitializer*[1];
5328 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5329 Constructor->setCtorInitializers(initializer);
5330
5331 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5332 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5333 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5334 }
5335
5336 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5337
5338 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5339
5340 return false;
5341}
5342
5343static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5344 CXXRecordDecl *Class) {
5345 if (Class->isInvalidDecl())
5346 return nullptr;
5347 if (Class->hasIrrelevantDestructor())
5348 return nullptr;
5349
5350 // Dtor might still be missing, e.g because it's invalid.
5351 return S.LookupDestructor(Class);
5352}
5353
5354static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5355 FieldDecl *Field) {
5356 if (Field->isInvalidDecl())
5357 return;
5358
5359 // Don't destroy incomplete or zero-length arrays.
5360 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5361 return;
5362
5363 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5364
5365 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5366 if (!FieldClassDecl)
5367 return;
5368
5369 // The destructor for an implicit anonymous union member is never invoked.
5370 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5371 return;
5372
5373 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5374 if (!Dtor)
5375 return;
5376
5377 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5378 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5379 << Field->getDeclName() << FieldType);
5380
5381 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5382 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5383}
5384
5385static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5386 CXXRecordDecl *ClassDecl) {
5387 if (ClassDecl->isDependentContext())
5388 return;
5389
5390 // We only potentially invoke the destructors of potentially constructed
5391 // subobjects.
5392 bool VisitVirtualBases = !ClassDecl->isAbstract();
5393
5394 // If the destructor exists and has already been marked used in the MS ABI,
5395 // then virtual base destructors have already been checked and marked used.
5396 // Skip checking them again to avoid duplicate diagnostics.
5397 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5398 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5399 if (Dtor && Dtor->isUsed())
5400 VisitVirtualBases = false;
5401 }
5402
5403 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5404
5405 // Bases.
5406 for (const auto &Base : ClassDecl->bases()) {
5407 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5408 if (!BaseClassDecl)
5409 continue;
5410
5411 // Remember direct virtual bases.
5412 if (Base.isVirtual()) {
5413 if (!VisitVirtualBases)
5414 continue;
5415 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5416 }
5417
5418 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5419 if (!Dtor)
5420 continue;
5421
5422 // FIXME: caret should be on the start of the class name
5423 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5424 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5425 << Base.getType() << Base.getSourceRange(),
5426 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5427
5428 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5429 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5430 }
5431
5432 if (VisitVirtualBases)
5433 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5434 DirectVirtualBases: &DirectVirtualBases);
5435}
5436
5437bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5438 ArrayRef<CXXCtorInitializer *> Initializers) {
5439 if (Constructor->isDependentContext()) {
5440 // Just store the initializers as written, they will be checked during
5441 // instantiation.
5442 if (!Initializers.empty()) {
5443 Constructor->setNumCtorInitializers(Initializers.size());
5444 CXXCtorInitializer **baseOrMemberInitializers =
5445 new (Context) CXXCtorInitializer*[Initializers.size()];
5446 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5447 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5448 Constructor->setCtorInitializers(baseOrMemberInitializers);
5449 }
5450
5451 // Let template instantiation know whether we had errors.
5452 if (AnyErrors)
5453 Constructor->setInvalidDecl();
5454
5455 return false;
5456 }
5457
5458 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5459
5460 // We need to build the initializer AST according to order of construction
5461 // and not what user specified in the Initializers list.
5462 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5463 if (!ClassDecl)
5464 return true;
5465
5466 bool HadError = false;
5467
5468 for (CXXCtorInitializer *Member : Initializers) {
5469 if (Member->isBaseInitializer())
5470 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5471 Member;
5472 else {
5473 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5474
5475 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5476 for (auto *C : F->chain()) {
5477 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5478 if (FD && FD->getParent()->isUnion())
5479 Info.ActiveUnionMember.insert(KV: std::make_pair(
5480 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5481 }
5482 } else if (FieldDecl *FD = Member->getMember()) {
5483 if (FD->getParent()->isUnion())
5484 Info.ActiveUnionMember.insert(KV: std::make_pair(
5485 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5486 }
5487 }
5488 }
5489
5490 // Keep track of the direct virtual bases.
5491 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5492 for (auto &I : ClassDecl->bases()) {
5493 if (I.isVirtual())
5494 DirectVBases.insert(Ptr: &I);
5495 }
5496
5497 // Push virtual bases before others.
5498 for (auto &VBase : ClassDecl->vbases()) {
5499 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5500 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5501 // [class.base.init]p7, per DR257:
5502 // A mem-initializer where the mem-initializer-id names a virtual base
5503 // class is ignored during execution of a constructor of any class that
5504 // is not the most derived class.
5505 if (ClassDecl->isAbstract()) {
5506 // FIXME: Provide a fixit to remove the base specifier. This requires
5507 // tracking the location of the associated comma for a base specifier.
5508 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5509 << VBase.getType() << ClassDecl;
5510 DiagnoseAbstractType(RD: ClassDecl);
5511 }
5512
5513 Info.AllToInit.push_back(Elt: Value);
5514 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5515 // [class.base.init]p8, per DR257:
5516 // If a given [...] base class is not named by a mem-initializer-id
5517 // [...] and the entity is not a virtual base class of an abstract
5518 // class, then [...] the entity is default-initialized.
5519 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5520 CXXCtorInitializer *CXXBaseInit;
5521 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5522 BaseSpec: &VBase, IsInheritedVirtualBase,
5523 CXXBaseInit)) {
5524 HadError = true;
5525 continue;
5526 }
5527
5528 Info.AllToInit.push_back(Elt: CXXBaseInit);
5529 }
5530 }
5531
5532 // Non-virtual bases.
5533 for (auto &Base : ClassDecl->bases()) {
5534 // Virtuals are in the virtual base list and already constructed.
5535 if (Base.isVirtual())
5536 continue;
5537
5538 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5539 Val: Base.getType()->getAsCanonical<RecordType>())) {
5540 Info.AllToInit.push_back(Elt: Value);
5541 } else if (!AnyErrors) {
5542 CXXCtorInitializer *CXXBaseInit;
5543 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5544 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5545 CXXBaseInit)) {
5546 HadError = true;
5547 continue;
5548 }
5549
5550 Info.AllToInit.push_back(Elt: CXXBaseInit);
5551 }
5552 }
5553
5554 // Fields.
5555 for (auto *Mem : ClassDecl->decls()) {
5556 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5557 // C++ [class.bit]p2:
5558 // A declaration for a bit-field that omits the identifier declares an
5559 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5560 // initialized.
5561 if (F->isUnnamedBitField())
5562 continue;
5563
5564 // If we're not generating the implicit copy/move constructor, then we'll
5565 // handle anonymous struct/union fields based on their individual
5566 // indirect fields.
5567 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5568 continue;
5569
5570 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5571 HadError = true;
5572 continue;
5573 }
5574
5575 // Beyond this point, we only consider default initialization.
5576 if (Info.isImplicitCopyOrMove())
5577 continue;
5578
5579 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5580 if (F->getType()->isIncompleteArrayType()) {
5581 assert(ClassDecl->hasFlexibleArrayMember() &&
5582 "Incomplete array type is not valid");
5583 continue;
5584 }
5585
5586 // Initialize each field of an anonymous struct individually.
5587 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5588 HadError = true;
5589
5590 continue;
5591 }
5592 }
5593
5594 unsigned NumInitializers = Info.AllToInit.size();
5595 if (NumInitializers > 0) {
5596 Constructor->setNumCtorInitializers(NumInitializers);
5597 CXXCtorInitializer **baseOrMemberInitializers =
5598 new (Context) CXXCtorInitializer*[NumInitializers];
5599 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5600 n: NumInitializers * sizeof(CXXCtorInitializer*));
5601 Constructor->setCtorInitializers(baseOrMemberInitializers);
5602
5603 SourceLocation Location = Constructor->getLocation();
5604
5605 // Constructors implicitly reference the base and member
5606 // destructors.
5607
5608 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5609 FieldDecl *Field = Initializer->getAnyMember();
5610 if (!Field)
5611 continue;
5612
5613 // C++ [class.base.init]p12:
5614 // In a non-delegating constructor, the destructor for each
5615 // potentially constructed subobject of class type is potentially
5616 // invoked.
5617 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5618 }
5619
5620 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5621 }
5622
5623 return HadError;
5624}
5625
5626static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5627 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5628 const RecordDecl *RD = RT->getDecl();
5629 if (RD->isAnonymousStructOrUnion()) {
5630 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5631 PopulateKeysForFields(Field, IdealInits);
5632 return;
5633 }
5634 }
5635 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5636}
5637
5638static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5639 return Context.getCanonicalType(T: BaseType).getTypePtr();
5640}
5641
5642static const void *GetKeyForMember(ASTContext &Context,
5643 CXXCtorInitializer *Member) {
5644 if (!Member->isAnyMemberInitializer())
5645 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5646
5647 return Member->getAnyMember()->getCanonicalDecl();
5648}
5649
5650static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5651 const CXXCtorInitializer *Previous,
5652 const CXXCtorInitializer *Current) {
5653 if (Previous->isAnyMemberInitializer())
5654 Diag << 0 << Previous->getAnyMember();
5655 else
5656 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5657
5658 if (Current->isAnyMemberInitializer())
5659 Diag << 0 << Current->getAnyMember();
5660 else
5661 Diag << 1 << Current->getTypeSourceInfo()->getType();
5662}
5663
5664static void DiagnoseBaseOrMemInitializerOrder(
5665 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5666 ArrayRef<CXXCtorInitializer *> Inits) {
5667 if (Constructor->getDeclContext()->isDependentContext())
5668 return;
5669
5670 // Don't check initializers order unless the warning is enabled at the
5671 // location of at least one initializer.
5672 bool ShouldCheckOrder = false;
5673 for (const CXXCtorInitializer *Init : Inits) {
5674 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5675 Loc: Init->getSourceLocation())) {
5676 ShouldCheckOrder = true;
5677 break;
5678 }
5679 }
5680 if (!ShouldCheckOrder)
5681 return;
5682
5683 // Build the list of bases and members in the order that they'll
5684 // actually be initialized. The explicit initializers should be in
5685 // this same order but may be missing things.
5686 SmallVector<const void*, 32> IdealInitKeys;
5687
5688 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5689
5690 // 1. Virtual bases.
5691 for (const auto &VBase : ClassDecl->vbases())
5692 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5693
5694 // 2. Non-virtual bases.
5695 for (const auto &Base : ClassDecl->bases()) {
5696 if (Base.isVirtual())
5697 continue;
5698 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5699 }
5700
5701 // 3. Direct fields.
5702 for (auto *Field : ClassDecl->fields()) {
5703 if (Field->isUnnamedBitField())
5704 continue;
5705
5706 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5707 }
5708
5709 unsigned NumIdealInits = IdealInitKeys.size();
5710 unsigned IdealIndex = 0;
5711
5712 // Track initializers that are in an incorrect order for either a warning or
5713 // note if multiple ones occur.
5714 SmallVector<unsigned> WarnIndexes;
5715 // Correlates the index of an initializer in the init-list to the index of
5716 // the field/base in the class.
5717 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5718
5719 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5720 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5721
5722 // Scan forward to try to find this initializer in the idealized
5723 // initializers list.
5724 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5725 if (InitKey == IdealInitKeys[IdealIndex])
5726 break;
5727
5728 // If we didn't find this initializer, it must be because we
5729 // scanned past it on a previous iteration. That can only
5730 // happen if we're out of order; emit a warning.
5731 if (IdealIndex == NumIdealInits && InitIndex) {
5732 WarnIndexes.push_back(Elt: InitIndex);
5733
5734 // Move back to the initializer's location in the ideal list.
5735 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5736 if (InitKey == IdealInitKeys[IdealIndex])
5737 break;
5738
5739 assert(IdealIndex < NumIdealInits &&
5740 "initializer not found in initializer list");
5741 }
5742 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5743 }
5744
5745 if (WarnIndexes.empty())
5746 return;
5747
5748 // Sort based on the ideal order, first in the pair.
5749 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5750
5751 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5752 // emit the diagnostic before we can try adding notes.
5753 {
5754 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5755 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5756 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5757 : diag::warn_some_initializers_out_of_order);
5758
5759 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5760 if (CorrelatedInitOrder[I].second == I)
5761 continue;
5762 // Ideally we would be using InsertFromRange here, but clang doesn't
5763 // appear to handle InsertFromRange correctly when the source range is
5764 // modified by another fix-it.
5765 D << FixItHint::CreateReplacement(
5766 RemoveRange: Inits[I]->getSourceRange(),
5767 Code: Lexer::getSourceText(
5768 Range: CharSourceRange::getTokenRange(
5769 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5770 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5771 }
5772
5773 // If there is only 1 item out of order, the warning expects the name and
5774 // type of each being added to it.
5775 if (WarnIndexes.size() == 1) {
5776 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5777 Current: Inits[WarnIndexes.front()]);
5778 return;
5779 }
5780 }
5781 // More than 1 item to warn, create notes letting the user know which ones
5782 // are bad.
5783 for (unsigned WarnIndex : WarnIndexes) {
5784 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5785 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5786 DiagID: diag::note_initializer_out_of_order);
5787 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5788 D << PrevInit->getSourceRange();
5789 }
5790}
5791
5792namespace {
5793bool CheckRedundantInit(Sema &S,
5794 CXXCtorInitializer *Init,
5795 CXXCtorInitializer *&PrevInit) {
5796 if (!PrevInit) {
5797 PrevInit = Init;
5798 return false;
5799 }
5800
5801 if (FieldDecl *Field = Init->getAnyMember())
5802 S.Diag(Loc: Init->getSourceLocation(),
5803 DiagID: diag::err_multiple_mem_initialization)
5804 << Field->getDeclName()
5805 << Init->getSourceRange();
5806 else {
5807 const Type *BaseClass = Init->getBaseClass();
5808 assert(BaseClass && "neither field nor base");
5809 S.Diag(Loc: Init->getSourceLocation(),
5810 DiagID: diag::err_multiple_base_initialization)
5811 << QualType(BaseClass, 0)
5812 << Init->getSourceRange();
5813 }
5814 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5815 << 0 << PrevInit->getSourceRange();
5816
5817 return true;
5818}
5819
5820typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5821typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5822
5823bool CheckRedundantUnionInit(Sema &S,
5824 CXXCtorInitializer *Init,
5825 RedundantUnionMap &Unions) {
5826 FieldDecl *Field = Init->getAnyMember();
5827 RecordDecl *Parent = Field->getParent();
5828 NamedDecl *Child = Field;
5829
5830 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5831 if (Parent->isUnion()) {
5832 UnionEntry &En = Unions[Parent];
5833 if (En.first && En.first != Child) {
5834 S.Diag(Loc: Init->getSourceLocation(),
5835 DiagID: diag::err_multiple_mem_union_initialization)
5836 << Field->getDeclName()
5837 << Init->getSourceRange();
5838 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5839 << 0 << En.second->getSourceRange();
5840 return true;
5841 }
5842 if (!En.first) {
5843 En.first = Child;
5844 En.second = Init;
5845 }
5846 if (!Parent->isAnonymousStructOrUnion())
5847 return false;
5848 }
5849
5850 Child = Parent;
5851 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5852 }
5853
5854 return false;
5855}
5856} // namespace
5857
5858void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5859 SourceLocation ColonLoc,
5860 ArrayRef<CXXCtorInitializer*> MemInits,
5861 bool AnyErrors) {
5862 if (!ConstructorDecl)
5863 return;
5864
5865 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5866
5867 CXXConstructorDecl *Constructor
5868 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5869
5870 if (!Constructor) {
5871 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5872 return;
5873 }
5874
5875 // Mapping for the duplicate initializers check.
5876 // For member initializers, this is keyed with a FieldDecl*.
5877 // For base initializers, this is keyed with a Type*.
5878 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5879
5880 // Mapping for the inconsistent anonymous-union initializers check.
5881 RedundantUnionMap MemberUnions;
5882
5883 bool HadError = false;
5884 for (unsigned i = 0; i < MemInits.size(); i++) {
5885 CXXCtorInitializer *Init = MemInits[i];
5886
5887 // Set the source order index.
5888 Init->setSourceOrder(i);
5889
5890 if (Init->isAnyMemberInitializer()) {
5891 const void *Key = GetKeyForMember(Context, Member: Init);
5892 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5893 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5894 HadError = true;
5895 } else if (Init->isBaseInitializer()) {
5896 const void *Key = GetKeyForMember(Context, Member: Init);
5897 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5898 HadError = true;
5899 } else {
5900 assert(Init->isDelegatingInitializer());
5901 // This must be the only initializer
5902 if (MemInits.size() != 1) {
5903 Diag(Loc: Init->getSourceLocation(),
5904 DiagID: diag::err_delegating_initializer_alone)
5905 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5906 // We will treat this as being the only initializer.
5907 }
5908 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5909 // Return immediately as the initializer is set.
5910 return;
5911 }
5912 }
5913
5914 if (HadError)
5915 return;
5916
5917 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5918
5919 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5920
5921 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5922}
5923
5924void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5925 CXXRecordDecl *ClassDecl) {
5926 // Ignore dependent contexts. Also ignore unions, since their members never
5927 // have destructors implicitly called.
5928 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5929 return;
5930
5931 // FIXME: all the access-control diagnostics are positioned on the
5932 // field/base declaration. That's probably good; that said, the
5933 // user might reasonably want to know why the destructor is being
5934 // emitted, and we currently don't say.
5935
5936 // Non-static data members.
5937 for (auto *Field : ClassDecl->fields()) {
5938 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5939 }
5940
5941 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
5942}
5943
5944void Sema::MarkVirtualBaseDestructorsReferenced(
5945 SourceLocation Location, CXXRecordDecl *ClassDecl,
5946 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5947 // Virtual bases.
5948 for (const auto &VBase : ClassDecl->vbases()) {
5949 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5950 if (!BaseClassDecl)
5951 continue;
5952
5953 // Ignore already visited direct virtual bases.
5954 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
5955 continue;
5956
5957 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
5958 if (!Dtor)
5959 continue;
5960
5961 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
5962 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
5963 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
5964 << CT << VBase.getType(),
5965 objectType: CT) == AR_accessible) {
5966 CheckDerivedToBaseConversion(
5967 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
5968 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
5969 }
5970
5971 MarkFunctionReferenced(Loc: Location, Func: Dtor);
5972 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5973 }
5974}
5975
5976void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
5977 if (!CDtorDecl)
5978 return;
5979
5980 if (CXXConstructorDecl *Constructor
5981 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
5982 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
5983 !ClassDecl || ClassDecl->isInvalidDecl()) {
5984 return;
5985 }
5986 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
5987 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5988 }
5989}
5990
5991bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
5992 if (!getLangOpts().CPlusPlus)
5993 return false;
5994
5995 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
5996 if (!RD)
5997 return false;
5998
5999 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6000 // class template specialization here, but doing so breaks a lot of code.
6001
6002 // We can't answer whether something is abstract until it has a
6003 // definition. If it's currently being defined, we'll walk back
6004 // over all the declarations when we have a full definition.
6005 const CXXRecordDecl *Def = RD->getDefinition();
6006 if (!Def || Def->isBeingDefined())
6007 return false;
6008
6009 return RD->isAbstract();
6010}
6011
6012bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6013 TypeDiagnoser &Diagnoser) {
6014 if (!isAbstractType(Loc, T))
6015 return false;
6016
6017 T = Context.getBaseElementType(QT: T);
6018 Diagnoser.diagnose(S&: *this, Loc, T);
6019 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6020 return true;
6021}
6022
6023void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6024 // Check if we've already emitted the list of pure virtual functions
6025 // for this class.
6026 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6027 return;
6028
6029 // If the diagnostic is suppressed, don't emit the notes. We're only
6030 // going to emit them once, so try to attach them to a diagnostic we're
6031 // actually going to show.
6032 if (Diags.isLastDiagnosticIgnored())
6033 return;
6034
6035 CXXFinalOverriderMap FinalOverriders;
6036 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6037
6038 // Keep a set of seen pure methods so we won't diagnose the same method
6039 // more than once.
6040 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6041
6042 for (const auto &M : FinalOverriders) {
6043 for (const auto &SO : M.second) {
6044 // C++ [class.abstract]p4:
6045 // A class is abstract if it contains or inherits at least one
6046 // pure virtual function for which the final overrider is pure
6047 // virtual.
6048
6049 if (SO.second.size() != 1)
6050 continue;
6051 const CXXMethodDecl *Method = SO.second.front().Method;
6052
6053 if (!Method->isPureVirtual())
6054 continue;
6055
6056 if (!SeenPureMethods.insert(Ptr: Method).second)
6057 continue;
6058
6059 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6060 << Method->getDeclName() << RD->getDeclName();
6061 }
6062 }
6063
6064 if (!PureVirtualClassDiagSet)
6065 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6066 PureVirtualClassDiagSet->insert(Ptr: RD);
6067}
6068
6069namespace {
6070struct AbstractUsageInfo {
6071 Sema &S;
6072 CXXRecordDecl *Record;
6073 CanQualType AbstractType;
6074 bool Invalid;
6075
6076 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6077 : S(S), Record(Record),
6078 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6079
6080 void DiagnoseAbstractType() {
6081 if (Invalid) return;
6082 S.DiagnoseAbstractType(RD: Record);
6083 Invalid = true;
6084 }
6085
6086 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6087};
6088
6089struct CheckAbstractUsage {
6090 AbstractUsageInfo &Info;
6091 const NamedDecl *Ctx;
6092
6093 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6094 : Info(Info), Ctx(Ctx) {}
6095
6096 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6097 switch (TL.getTypeLocClass()) {
6098#define ABSTRACT_TYPELOC(CLASS, PARENT)
6099#define TYPELOC(CLASS, PARENT) \
6100 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6101#include "clang/AST/TypeLocNodes.def"
6102 }
6103 }
6104
6105 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6106 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6107 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6108 if (!TL.getParam(i: I))
6109 continue;
6110
6111 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6112 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6113 }
6114 }
6115
6116 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6117 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6118 }
6119
6120 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6121 // Visit the type parameters from a permissive context.
6122 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6123 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6124 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6125 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6126 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6127 // TODO: other template argument types?
6128 }
6129 }
6130
6131 // Visit pointee types from a permissive context.
6132#define CheckPolymorphic(Type) \
6133 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6134 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6135 }
6136 CheckPolymorphic(PointerTypeLoc)
6137 CheckPolymorphic(ReferenceTypeLoc)
6138 CheckPolymorphic(MemberPointerTypeLoc)
6139 CheckPolymorphic(BlockPointerTypeLoc)
6140 CheckPolymorphic(AtomicTypeLoc)
6141
6142 /// Handle all the types we haven't given a more specific
6143 /// implementation for above.
6144 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6145 // Every other kind of type that we haven't called out already
6146 // that has an inner type is either (1) sugar or (2) contains that
6147 // inner type in some way as a subobject.
6148 if (TypeLoc Next = TL.getNextTypeLoc())
6149 return Visit(TL: Next, Sel);
6150
6151 // If there's no inner type and we're in a permissive context,
6152 // don't diagnose.
6153 if (Sel == Sema::AbstractNone) return;
6154
6155 // Check whether the type matches the abstract type.
6156 QualType T = TL.getType();
6157 if (T->isArrayType()) {
6158 Sel = Sema::AbstractArrayType;
6159 T = Info.S.Context.getBaseElementType(QT: T);
6160 }
6161 CanQualType CT = T->getCanonicalTypeUnqualified();
6162 if (CT != Info.AbstractType) return;
6163
6164 // It matched; do some magic.
6165 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6166 if (Sel == Sema::AbstractArrayType) {
6167 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6168 << T << TL.getSourceRange();
6169 } else {
6170 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6171 << Sel << T << TL.getSourceRange();
6172 }
6173 Info.DiagnoseAbstractType();
6174 }
6175};
6176
6177void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6178 Sema::AbstractDiagSelID Sel) {
6179 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6180}
6181
6182}
6183
6184/// Check for invalid uses of an abstract type in a function declaration.
6185static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6186 FunctionDecl *FD) {
6187 // Only definitions are required to refer to complete and
6188 // non-abstract types.
6189 if (!FD->doesThisDeclarationHaveABody())
6190 return;
6191
6192 // For safety's sake, just ignore it if we don't have type source
6193 // information. This should never happen for non-implicit methods,
6194 // but...
6195 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6196 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6197}
6198
6199/// Check for invalid uses of an abstract type in a variable0 declaration.
6200static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6201 VarDecl *VD) {
6202 // No need to do the check on definitions, which require that
6203 // the type is complete.
6204 if (VD->isThisDeclarationADefinition())
6205 return;
6206
6207 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6208 Sel: Sema::AbstractVariableType);
6209}
6210
6211/// Check for invalid uses of an abstract type within a class definition.
6212static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6213 CXXRecordDecl *RD) {
6214 for (auto *D : RD->decls()) {
6215 if (D->isImplicit()) continue;
6216
6217 // Step through friends to the befriended declaration.
6218 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6219 D = FD->getFriendDecl();
6220 if (!D) continue;
6221 }
6222
6223 // Functions and function templates.
6224 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6225 CheckAbstractClassUsage(Info, FD);
6226 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6227 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6228
6229 // Fields and static variables.
6230 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6231 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6232 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6233 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6234 CheckAbstractClassUsage(Info, VD);
6235 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6236 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6237
6238 // Nested classes and class templates.
6239 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6240 CheckAbstractClassUsage(Info, RD);
6241 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6242 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6243 }
6244 }
6245}
6246
6247static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6248 Attr *ClassAttr = getDLLAttr(D: Class);
6249 if (!ClassAttr)
6250 return;
6251
6252 assert(ClassAttr->getKind() == attr::DLLExport);
6253
6254 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6255
6256 if (TSK == TSK_ExplicitInstantiationDeclaration)
6257 // Don't go any further if this is just an explicit instantiation
6258 // declaration.
6259 return;
6260
6261 // Add a context note to explain how we got to any diagnostics produced below.
6262 struct MarkingClassDllexported {
6263 Sema &S;
6264 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6265 SourceLocation AttrLoc)
6266 : S(S) {
6267 Sema::CodeSynthesisContext Ctx;
6268 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6269 Ctx.PointOfInstantiation = AttrLoc;
6270 Ctx.Entity = Class;
6271 S.pushCodeSynthesisContext(Ctx);
6272 }
6273 ~MarkingClassDllexported() {
6274 S.popCodeSynthesisContext();
6275 }
6276 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6277
6278 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6279 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6280
6281 for (Decl *Member : Class->decls()) {
6282 // Skip members that were not marked exported.
6283 if (!Member->hasAttr<DLLExportAttr>())
6284 continue;
6285
6286 // Defined static variables that are members of an exported base
6287 // class must be marked export too.
6288 auto *VD = dyn_cast<VarDecl>(Val: Member);
6289 if (VD && VD->getStorageClass() == SC_Static &&
6290 TSK == TSK_ImplicitInstantiation)
6291 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6292
6293 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6294 if (!MD)
6295 continue;
6296
6297 if (MD->isUserProvided()) {
6298 // Instantiate non-default class member functions ...
6299
6300 // .. except for certain kinds of template specializations.
6301 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6302 continue;
6303
6304 // If this is an MS ABI dllexport default constructor, instantiate any
6305 // default arguments.
6306 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6307 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6308 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6309 S.InstantiateDefaultCtorDefaultArgs(Ctor: CD);
6310 }
6311 }
6312
6313 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6314
6315 // The function will be passed to the consumer when its definition is
6316 // encountered.
6317 } else if (MD->isExplicitlyDefaulted()) {
6318 // Synthesize and instantiate explicitly defaulted methods.
6319 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6320
6321 if (TSK != TSK_ExplicitInstantiationDefinition) {
6322 // Except for explicit instantiation defs, we will not see the
6323 // definition again later, so pass it to the consumer now.
6324 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6325 }
6326 } else if (!MD->isTrivial() ||
6327 MD->isCopyAssignmentOperator() ||
6328 MD->isMoveAssignmentOperator()) {
6329 // Synthesize and instantiate non-trivial implicit methods, and the copy
6330 // and move assignment operators. The latter are exported even if they
6331 // are trivial, because the address of an operator can be taken and
6332 // should compare equal across libraries.
6333 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6334
6335 // There is no later point when we will see the definition of this
6336 // function, so pass it to the consumer now.
6337 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6338 }
6339 }
6340}
6341
6342static void checkForMultipleExportedDefaultConstructors(Sema &S,
6343 CXXRecordDecl *Class) {
6344 // Only the MS ABI has default constructor closures, so we don't need to do
6345 // this semantic checking anywhere else.
6346 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6347 return;
6348
6349 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6350 for (Decl *Member : Class->decls()) {
6351 // Look for exported default constructors.
6352 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6353 if (!CD || !CD->isDefaultConstructor())
6354 continue;
6355 auto *Attr = CD->getAttr<DLLExportAttr>();
6356 if (!Attr)
6357 continue;
6358
6359 // If the class is non-dependent, mark the default arguments as ODR-used so
6360 // that we can properly codegen the constructor closure.
6361 if (!Class->isDependentContext()) {
6362 for (ParmVarDecl *PD : CD->parameters()) {
6363 (void)S.CheckCXXDefaultArgExpr(CallLoc: Attr->getLocation(), FD: CD, Param: PD);
6364 S.DiscardCleanupsInEvaluationContext();
6365 }
6366 }
6367
6368 if (LastExportedDefaultCtor) {
6369 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6370 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6371 << Class;
6372 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6373 << CD->getDeclName();
6374 return;
6375 }
6376 LastExportedDefaultCtor = CD;
6377 }
6378}
6379
6380static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6381 CXXRecordDecl *Class) {
6382 bool ErrorReported = false;
6383 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6384 ClassTemplateDecl *TD) {
6385 if (ErrorReported)
6386 return;
6387 S.Diag(Loc: TD->getLocation(),
6388 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6389 << /*surface*/ 0 << TD;
6390 ErrorReported = true;
6391 };
6392
6393 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6394 if (!TD) {
6395 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6396 if (!SD) {
6397 S.Diag(Loc: Class->getLocation(),
6398 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6399 << /*surface*/ 0 << Class;
6400 S.Diag(Loc: Class->getLocation(),
6401 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6402 << Class;
6403 return;
6404 }
6405 TD = SD->getSpecializedTemplate();
6406 }
6407
6408 TemplateParameterList *Params = TD->getTemplateParameters();
6409 unsigned N = Params->size();
6410
6411 if (N != 2) {
6412 reportIllegalClassTemplate(S, TD);
6413 S.Diag(Loc: TD->getLocation(),
6414 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6415 << TD << 2;
6416 }
6417 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6418 reportIllegalClassTemplate(S, TD);
6419 S.Diag(Loc: TD->getLocation(),
6420 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6421 << TD << /*1st*/ 0 << /*type*/ 0;
6422 }
6423 if (N > 1) {
6424 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6425 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6426 reportIllegalClassTemplate(S, TD);
6427 S.Diag(Loc: TD->getLocation(),
6428 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6429 << TD << /*2nd*/ 1 << /*integer*/ 1;
6430 }
6431 }
6432}
6433
6434static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6435 CXXRecordDecl *Class) {
6436 bool ErrorReported = false;
6437 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6438 ClassTemplateDecl *TD) {
6439 if (ErrorReported)
6440 return;
6441 S.Diag(Loc: TD->getLocation(),
6442 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6443 << /*texture*/ 1 << TD;
6444 ErrorReported = true;
6445 };
6446
6447 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6448 if (!TD) {
6449 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6450 if (!SD) {
6451 S.Diag(Loc: Class->getLocation(),
6452 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6453 << /*texture*/ 1 << Class;
6454 S.Diag(Loc: Class->getLocation(),
6455 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6456 << Class;
6457 return;
6458 }
6459 TD = SD->getSpecializedTemplate();
6460 }
6461
6462 TemplateParameterList *Params = TD->getTemplateParameters();
6463 unsigned N = Params->size();
6464
6465 if (N != 3) {
6466 reportIllegalClassTemplate(S, TD);
6467 S.Diag(Loc: TD->getLocation(),
6468 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6469 << TD << 3;
6470 }
6471 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6472 reportIllegalClassTemplate(S, TD);
6473 S.Diag(Loc: TD->getLocation(),
6474 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6475 << TD << /*1st*/ 0 << /*type*/ 0;
6476 }
6477 if (N > 1) {
6478 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6479 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6480 reportIllegalClassTemplate(S, TD);
6481 S.Diag(Loc: TD->getLocation(),
6482 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6483 << TD << /*2nd*/ 1 << /*integer*/ 1;
6484 }
6485 }
6486 if (N > 2) {
6487 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6488 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6489 reportIllegalClassTemplate(S, TD);
6490 S.Diag(Loc: TD->getLocation(),
6491 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6492 << TD << /*3rd*/ 2 << /*integer*/ 1;
6493 }
6494 }
6495}
6496
6497void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6498 // Mark any compiler-generated routines with the implicit code_seg attribute.
6499 for (auto *Method : Class->methods()) {
6500 if (Method->isUserProvided())
6501 continue;
6502 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6503 Method->addAttr(A);
6504 }
6505}
6506
6507void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6508 Attr *ClassAttr = getDLLAttr(D: Class);
6509
6510 // MSVC inherits DLL attributes to partial class template specializations.
6511 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6512 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6513 if (Attr *TemplateAttr =
6514 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6515 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6516 A->setInherited(true);
6517 ClassAttr = A;
6518 }
6519 }
6520 }
6521
6522 if (!ClassAttr)
6523 return;
6524
6525 // MSVC allows imported or exported template classes that have UniqueExternal
6526 // linkage. This occurs when the template class has been instantiated with
6527 // a template parameter which itself has internal linkage.
6528 // We drop the attribute to avoid exporting or importing any members.
6529 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6530 Context.getTargetInfo().getTriple().isPS()) &&
6531 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6532 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6533 return;
6534 }
6535
6536 if (!Class->isExternallyVisible()) {
6537 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6538 << Class << ClassAttr;
6539 return;
6540 }
6541
6542 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6543 !ClassAttr->isInherited()) {
6544 // Diagnose dll attributes on members of class with dll attribute.
6545 for (Decl *Member : Class->decls()) {
6546 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6547 continue;
6548 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6549 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6550 continue;
6551
6552 Diag(Loc: MemberAttr->getLocation(),
6553 DiagID: diag::err_attribute_dll_member_of_dll_class)
6554 << MemberAttr << ClassAttr;
6555 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6556 Member->setInvalidDecl();
6557 }
6558 }
6559
6560 if (Class->getDescribedClassTemplate())
6561 // Don't inherit dll attribute until the template is instantiated.
6562 return;
6563
6564 // The class is either imported or exported.
6565 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6566
6567 // Check if this was a dllimport attribute propagated from a derived class to
6568 // a base class template specialization. We don't apply these attributes to
6569 // static data members.
6570 const bool PropagatedImport =
6571 !ClassExported &&
6572 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6573
6574 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6575
6576 // Ignore explicit dllexport on explicit class template instantiation
6577 // declarations, except in MinGW mode.
6578 if (ClassExported && !ClassAttr->isInherited() &&
6579 TSK == TSK_ExplicitInstantiationDeclaration &&
6580 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6581 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6582 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6583 Class->dropAttr<DLLExportAttr>();
6584 }
6585 return;
6586 }
6587
6588 // Force declaration of implicit members so they can inherit the attribute.
6589 ForceDeclarationOfImplicitMembers(Class);
6590
6591 // Inherited constructors are created lazily; force their creation now so the
6592 // loop below can propagate the DLL attribute to them.
6593 if (ClassExported) {
6594 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6595 for (Decl *D : Class->decls())
6596 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6597 Shadows.push_back(Elt: S);
6598 for (ConstructorUsingShadowDecl *S : Shadows) {
6599 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6600 if (!BC || BC->isDeleted())
6601 continue;
6602 // Skip constructors whose requires clause is not satisfied.
6603 // Normally overload resolution filters these, but we are bypassing
6604 // it to eagerly create inherited constructors for dllexport.
6605 if (BC->getTrailingRequiresClause()) {
6606 ConstraintSatisfaction Satisfaction;
6607 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6608 !Satisfaction.IsSatisfied)
6609 continue;
6610 }
6611 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6612 }
6613 }
6614
6615 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6616 // seem to be true in practice?
6617
6618 for (Decl *Member : Class->decls()) {
6619 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6620 continue;
6621
6622 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6623 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6624
6625 // Only methods and static fields inherit the attributes.
6626 if (!VD && !MD)
6627 continue;
6628
6629 if (MD) {
6630 // Don't process deleted methods.
6631 if (MD->isDeleted())
6632 continue;
6633
6634 if (ClassExported) {
6635 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6636 if (CD && CD->getInheritedConstructor()) {
6637 // Inherited constructors already had their base constructor's
6638 // constraints checked before creation via
6639 // findInheritingConstructor, so only ABI-compatibility checks
6640 // are needed here.
6641 //
6642 // Don't export inherited constructors whose parameters prevent
6643 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6644 // CodeGen) returns false, Clang inlines the constructor body
6645 // instead of emitting a forwarding thunk, producing code that
6646 // is not ABI-compatible with MSVC. Suppress the export and warn
6647 // so the user gets a linker error rather than a silent runtime
6648 // mismatch.
6649 if (CD->isVariadic()) {
6650 Diag(Loc: CD->getLocation(),
6651 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6652 << /*variadic=*/0;
6653 continue;
6654 }
6655 if (Context.getTargetInfo()
6656 .getCXXABI()
6657 .areArgsDestroyedLeftToRightInCallee()) {
6658 bool HasCalleeCleanupParam = false;
6659 for (const ParmVarDecl *P : CD->parameters())
6660 if (P->needsDestruction(Ctx: Context)) {
6661 HasCalleeCleanupParam = true;
6662 break;
6663 }
6664 if (HasCalleeCleanupParam) {
6665 Diag(Loc: CD->getLocation(),
6666 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6667 << /*callee-cleanup=*/1;
6668 continue;
6669 }
6670 }
6671 } else if (MD->getTrailingRequiresClause()) {
6672 // Don't export methods whose requires clause is not satisfied.
6673 // For class template specializations, member constraints may
6674 // depend on template arguments and an unsatisfied constraint
6675 // means the member should not be available in this
6676 // specialization.
6677 ConstraintSatisfaction Satisfaction;
6678 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6679 !Satisfaction.IsSatisfied)
6680 continue;
6681 }
6682 }
6683
6684 if (MD->isInlined()) {
6685 // MinGW does not import or export inline methods. But do it for
6686 // template instantiations and inherited constructors (which are
6687 // marked inline but must be exported to match MSVC behavior).
6688 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6689 TSK != TSK_ExplicitInstantiationDeclaration &&
6690 TSK != TSK_ExplicitInstantiationDefinition) {
6691 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6692 !CD || !CD->getInheritedConstructor())
6693 continue;
6694 }
6695
6696 // MSVC versions before 2015 don't export the move assignment operators
6697 // and move constructor, so don't attempt to import/export them if
6698 // we have a definition.
6699 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6700 if ((MD->isMoveAssignmentOperator() ||
6701 (Ctor && Ctor->isMoveConstructor())) &&
6702 getLangOpts().isCompatibleWithMSVC() &&
6703 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6704 continue;
6705
6706 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6707 // operator is exported anyway.
6708 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6709 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6710 continue;
6711 }
6712 }
6713
6714 // Don't apply dllimport attributes to static data members of class template
6715 // instantiations when the attribute is propagated from a derived class.
6716 if (VD && PropagatedImport)
6717 continue;
6718
6719 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6720 continue;
6721
6722 if (!getDLLAttr(D: Member)) {
6723 InheritableAttr *NewAttr = nullptr;
6724
6725 // Do not export/import inline function when -fno-dllexport-inlines is
6726 // passed. But add attribute for later local static var check.
6727 // Inherited constructors are marked inline but must still be exported
6728 // to match MSVC behavior, so exclude them from this override.
6729 bool IsInheritedCtor = false;
6730 if (auto *CD = dyn_cast_or_null<CXXConstructorDecl>(Val: MD))
6731 IsInheritedCtor = (bool)CD->getInheritedConstructor();
6732 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6733 !IsInheritedCtor && TSK != TSK_ExplicitInstantiationDeclaration &&
6734 TSK != TSK_ExplicitInstantiationDefinition) {
6735 if (ClassExported) {
6736 NewAttr = ::new (getASTContext())
6737 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6738 } else {
6739 NewAttr = ::new (getASTContext())
6740 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6741 }
6742 } else {
6743 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6744 }
6745
6746 NewAttr->setInherited(true);
6747 Member->addAttr(A: NewAttr);
6748
6749 if (MD) {
6750 // Propagate DLLAttr to friend re-declarations of MD that have already
6751 // been constructed.
6752 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6753 FD = FD->getPreviousDecl()) {
6754 if (FD->getFriendObjectKind() == Decl::FOK_None)
6755 continue;
6756 assert(!getDLLAttr(FD) &&
6757 "friend re-decl should not already have a DLLAttr");
6758 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6759 NewAttr->setInherited(true);
6760 FD->addAttr(A: NewAttr);
6761 }
6762 }
6763 }
6764 }
6765
6766 if (ClassExported)
6767 DelayedDllExportClasses.push_back(Elt: Class);
6768}
6769
6770void Sema::propagateDLLAttrToBaseClassTemplate(
6771 CXXRecordDecl *Class, Attr *ClassAttr,
6772 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6773 if (getDLLAttr(
6774 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6775 // If the base class template has a DLL attribute, don't try to change it.
6776 return;
6777 }
6778
6779 auto TSK = BaseTemplateSpec->getSpecializationKind();
6780 if (!getDLLAttr(D: BaseTemplateSpec) &&
6781 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6782 TSK == TSK_ImplicitInstantiation)) {
6783 // The template hasn't been instantiated yet (or it has, but only as an
6784 // explicit instantiation declaration or implicit instantiation, which means
6785 // we haven't codegenned any members yet), so propagate the attribute.
6786 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6787 NewAttr->setInherited(true);
6788 BaseTemplateSpec->addAttr(A: NewAttr);
6789
6790 // If this was an import, mark that we propagated it from a derived class to
6791 // a base class template specialization.
6792 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6793 ImportAttr->setPropagatedToBaseTemplate();
6794
6795 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6796 // needs to be run again to work see the new attribute. Otherwise this will
6797 // get run whenever the template is instantiated.
6798 if (TSK != TSK_Undeclared)
6799 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6800
6801 return;
6802 }
6803
6804 if (getDLLAttr(D: BaseTemplateSpec)) {
6805 // The template has already been specialized or instantiated with an
6806 // attribute, explicitly or through propagation. We should not try to change
6807 // it.
6808 return;
6809 }
6810
6811 // The template was previously instantiated or explicitly specialized without
6812 // a dll attribute, It's too late for us to add an attribute, so warn that
6813 // this is unsupported.
6814 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6815 << BaseTemplateSpec->isExplicitSpecialization();
6816 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6817 if (BaseTemplateSpec->isExplicitSpecialization()) {
6818 Diag(Loc: BaseTemplateSpec->getLocation(),
6819 DiagID: diag::note_template_class_explicit_specialization_was_here)
6820 << BaseTemplateSpec;
6821 } else {
6822 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6823 DiagID: diag::note_template_class_instantiation_was_here)
6824 << BaseTemplateSpec;
6825 }
6826}
6827
6828Sema::DefaultedFunctionKind
6829Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6830 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6831 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6832 if (Ctor->isDefaultConstructor())
6833 return CXXSpecialMemberKind::DefaultConstructor;
6834
6835 if (Ctor->isCopyConstructor())
6836 return CXXSpecialMemberKind::CopyConstructor;
6837
6838 if (Ctor->isMoveConstructor())
6839 return CXXSpecialMemberKind::MoveConstructor;
6840 }
6841
6842 if (MD->isCopyAssignmentOperator())
6843 return CXXSpecialMemberKind::CopyAssignment;
6844
6845 if (MD->isMoveAssignmentOperator())
6846 return CXXSpecialMemberKind::MoveAssignment;
6847
6848 if (isa<CXXDestructorDecl>(Val: FD))
6849 return CXXSpecialMemberKind::Destructor;
6850 }
6851
6852 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6853 case OO_EqualEqual:
6854 return DefaultedComparisonKind::Equal;
6855
6856 case OO_ExclaimEqual:
6857 return DefaultedComparisonKind::NotEqual;
6858
6859 case OO_Spaceship:
6860 // No point allowing this if <=> doesn't exist in the current language mode.
6861 if (!getLangOpts().CPlusPlus20)
6862 break;
6863 return DefaultedComparisonKind::ThreeWay;
6864
6865 case OO_Less:
6866 case OO_LessEqual:
6867 case OO_Greater:
6868 case OO_GreaterEqual:
6869 // No point allowing this if <=> doesn't exist in the current language mode.
6870 if (!getLangOpts().CPlusPlus20)
6871 break;
6872 return DefaultedComparisonKind::Relational;
6873
6874 default:
6875 break;
6876 }
6877
6878 // Not defaultable.
6879 return DefaultedFunctionKind();
6880}
6881
6882static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6883 SourceLocation DefaultLoc) {
6884 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6885 if (DFK.isComparison())
6886 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6887
6888 switch (DFK.asSpecialMember()) {
6889 case CXXSpecialMemberKind::DefaultConstructor:
6890 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6891 Constructor: cast<CXXConstructorDecl>(Val: FD));
6892 break;
6893 case CXXSpecialMemberKind::CopyConstructor:
6894 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6895 break;
6896 case CXXSpecialMemberKind::CopyAssignment:
6897 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6898 break;
6899 case CXXSpecialMemberKind::Destructor:
6900 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6901 break;
6902 case CXXSpecialMemberKind::MoveConstructor:
6903 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6904 break;
6905 case CXXSpecialMemberKind::MoveAssignment:
6906 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6907 break;
6908 case CXXSpecialMemberKind::Invalid:
6909 llvm_unreachable("Invalid special member.");
6910 }
6911}
6912
6913/// Determine whether a type is permitted to be passed or returned in
6914/// registers, per C++ [class.temporary]p3.
6915static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6916 TargetInfo::CallingConvKind CCK) {
6917 if (D->isDependentType() || D->isInvalidDecl())
6918 return false;
6919
6920 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6921 // The PS4 platform ABI follows the behavior of Clang 3.2.
6922 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6923 return !D->hasNonTrivialDestructorForCall() &&
6924 !D->hasNonTrivialCopyConstructorForCall();
6925
6926 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6927 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6928 bool DtorIsTrivialForCall = false;
6929
6930 // If a class has at least one eligible, trivial copy constructor, it
6931 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6932 //
6933 // Note: This permits classes with non-trivial copy or move ctors to be
6934 // passed in registers, so long as they *also* have a trivial copy ctor,
6935 // which is non-conforming.
6936 if (D->needsImplicitCopyConstructor()) {
6937 if (!D->defaultedCopyConstructorIsDeleted()) {
6938 if (D->hasTrivialCopyConstructor())
6939 CopyCtorIsTrivial = true;
6940 if (D->hasTrivialCopyConstructorForCall())
6941 CopyCtorIsTrivialForCall = true;
6942 }
6943 } else {
6944 for (const CXXConstructorDecl *CD : D->ctors()) {
6945 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6946 !CD->isIneligibleOrNotSelected()) {
6947 if (CD->isTrivial())
6948 CopyCtorIsTrivial = true;
6949 if (CD->isTrivialForCall())
6950 CopyCtorIsTrivialForCall = true;
6951 }
6952 }
6953 }
6954
6955 if (D->needsImplicitDestructor()) {
6956 if (!D->defaultedDestructorIsDeleted() &&
6957 D->hasTrivialDestructorForCall())
6958 DtorIsTrivialForCall = true;
6959 } else if (const auto *DD = D->getDestructor()) {
6960 if (!DD->isDeleted() && DD->isTrivialForCall())
6961 DtorIsTrivialForCall = true;
6962 }
6963
6964 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6965 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6966 return true;
6967
6968 // If a class has a destructor, we'd really like to pass it indirectly
6969 // because it allows us to elide copies. Unfortunately, MSVC makes that
6970 // impossible for small types, which it will pass in a single register or
6971 // stack slot. Most objects with dtors are large-ish, so handle that early.
6972 // We can't call out all large objects as being indirect because there are
6973 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
6974 // how we pass large POD types.
6975
6976 // Note: This permits small classes with nontrivial destructors to be
6977 // passed in registers, which is non-conforming.
6978 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
6979 uint64_t TypeSize = isAArch64 ? 128 : 64;
6980
6981 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
6982 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
6983 return true;
6984 return false;
6985 }
6986
6987 // Per C++ [class.temporary]p3, the relevant condition is:
6988 // each copy constructor, move constructor, and destructor of X is
6989 // either trivial or deleted, and X has at least one non-deleted copy
6990 // or move constructor
6991 bool HasNonDeletedCopyOrMove = false;
6992
6993 if (D->needsImplicitCopyConstructor() &&
6994 !D->defaultedCopyConstructorIsDeleted()) {
6995 if (!D->hasTrivialCopyConstructorForCall())
6996 return false;
6997 HasNonDeletedCopyOrMove = true;
6998 }
6999
7000 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7001 !D->defaultedMoveConstructorIsDeleted()) {
7002 if (!D->hasTrivialMoveConstructorForCall())
7003 return false;
7004 HasNonDeletedCopyOrMove = true;
7005 }
7006
7007 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7008 !D->hasTrivialDestructorForCall())
7009 return false;
7010
7011 for (const CXXMethodDecl *MD : D->methods()) {
7012 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7013 continue;
7014
7015 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7016 if (CD && CD->isCopyOrMoveConstructor())
7017 HasNonDeletedCopyOrMove = true;
7018 else if (!isa<CXXDestructorDecl>(Val: MD))
7019 continue;
7020
7021 if (!MD->isTrivialForCall())
7022 return false;
7023 }
7024
7025 return HasNonDeletedCopyOrMove;
7026}
7027
7028/// Report an error regarding overriding, along with any relevant
7029/// overridden methods.
7030///
7031/// \param DiagID the primary error to report.
7032/// \param MD the overriding method.
7033static bool
7034ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7035 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7036 bool IssuedDiagnostic = false;
7037 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7038 if (Report(O)) {
7039 if (!IssuedDiagnostic) {
7040 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7041 IssuedDiagnostic = true;
7042 }
7043 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7044 }
7045 }
7046 return IssuedDiagnostic;
7047}
7048
7049void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7050 if (!Record)
7051 return;
7052
7053 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7054 AbstractUsageInfo Info(*this, Record);
7055 CheckAbstractClassUsage(Info, RD: Record);
7056 }
7057
7058 // If this is not an aggregate type and has no user-declared constructor,
7059 // complain about any non-static data members of reference or const scalar
7060 // type, since they will never get initializers.
7061 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7062 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7063 !Record->isLambda()) {
7064 bool Complained = false;
7065 for (const auto *F : Record->fields()) {
7066 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7067 continue;
7068
7069 if (F->getType()->isReferenceType() ||
7070 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7071 if (!Complained) {
7072 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7073 << Record->getTagKind() << Record;
7074 Complained = true;
7075 }
7076
7077 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7078 << F->getType()->isReferenceType()
7079 << F->getDeclName();
7080 }
7081 }
7082 }
7083
7084 if (Record->getIdentifier()) {
7085 // C++ [class.mem]p13:
7086 // If T is the name of a class, then each of the following shall have a
7087 // name different from T:
7088 // - every member of every anonymous union that is a member of class T.
7089 //
7090 // C++ [class.mem]p14:
7091 // In addition, if class T has a user-declared constructor (12.1), every
7092 // non-static data member of class T shall have a name different from T.
7093 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7094 const NamedDecl *D = Element->getUnderlyingDecl();
7095 // Invalid IndirectFieldDecls have already been diagnosed with
7096 // err_anonymous_record_member_redecl in
7097 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7098 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7099 Record->hasUserDeclaredConstructor()) ||
7100 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7101 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7102 << D->getDeclName();
7103 break;
7104 }
7105 }
7106 }
7107
7108 // Warn if the class has virtual methods but non-virtual public destructor.
7109 if (Record->isPolymorphic() && !Record->isDependentType()) {
7110 CXXDestructorDecl *dtor = Record->getDestructor();
7111 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7112 !Record->hasAttr<FinalAttr>())
7113 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7114 DiagID: diag::warn_non_virtual_dtor)
7115 << Context.getCanonicalTagType(TD: Record);
7116 }
7117
7118 if (Record->isAbstract()) {
7119 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7120 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7121 << FA->isSpelledAsSealed();
7122 DiagnoseAbstractType(RD: Record);
7123 }
7124 }
7125
7126 // Warn if the class has a final destructor but is not itself marked final.
7127 if (!Record->hasAttr<FinalAttr>()) {
7128 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7129 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7130 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7131 << FA->isSpelledAsSealed()
7132 << FixItHint::CreateInsertion(
7133 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7134 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7135 Diag(Loc: Record->getLocation(),
7136 DiagID: diag::note_final_dtor_non_final_class_silence)
7137 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7138 }
7139 }
7140 }
7141
7142 // See if trivial_abi has to be dropped.
7143 if (Record->hasAttr<TrivialABIAttr>())
7144 checkIllFormedTrivialABIStruct(RD&: *Record);
7145
7146 // Set HasTrivialSpecialMemberForCall if the record has attribute
7147 // "trivial_abi".
7148 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7149
7150 if (HasTrivialABI)
7151 Record->setHasTrivialSpecialMemberForCall();
7152
7153 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7154 // We check these last because they can depend on the properties of the
7155 // primary comparison functions (==, <=>).
7156 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7157
7158 // Perform checks that can't be done until we know all the properties of a
7159 // member function (whether it's defaulted, deleted, virtual, overriding,
7160 // ...).
7161 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7162 // A static function cannot override anything.
7163 if (MD->getStorageClass() == SC_Static) {
7164 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7165 Report: [](const CXXMethodDecl *) { return true; }))
7166 return;
7167 }
7168
7169 // A deleted function cannot override a non-deleted function and vice
7170 // versa.
7171 if (ReportOverrides(S&: *this,
7172 DiagID: MD->isDeleted() ? diag::err_deleted_override
7173 : diag::err_non_deleted_override,
7174 MD, Report: [&](const CXXMethodDecl *V) {
7175 return MD->isDeleted() != V->isDeleted();
7176 })) {
7177 if (MD->isDefaulted() && MD->isDeleted())
7178 // Explain why this defaulted function was deleted.
7179 DiagnoseDeletedDefaultedFunction(FD: MD);
7180 return;
7181 }
7182
7183 // A consteval function cannot override a non-consteval function and vice
7184 // versa.
7185 if (ReportOverrides(S&: *this,
7186 DiagID: MD->isConsteval() ? diag::err_consteval_override
7187 : diag::err_non_consteval_override,
7188 MD, Report: [&](const CXXMethodDecl *V) {
7189 return MD->isConsteval() != V->isConsteval();
7190 })) {
7191 if (MD->isDefaulted() && MD->isDeleted())
7192 // Explain why this defaulted function was deleted.
7193 DiagnoseDeletedDefaultedFunction(FD: MD);
7194 return;
7195 }
7196 };
7197
7198 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7199 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7200 return false;
7201
7202 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7203 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7204 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7205 DefaultedSecondaryComparisons.push_back(Elt: FD);
7206 return true;
7207 }
7208
7209 CheckExplicitlyDefaultedFunction(S, MD: FD);
7210 return false;
7211 };
7212
7213 if (!Record->isInvalidDecl() &&
7214 Record->hasAttr<VTablePointerAuthenticationAttr>())
7215 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7216
7217 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7218 // Check whether the explicitly-defaulted members are valid.
7219 bool Incomplete = CheckForDefaultedFunction(M);
7220
7221 // Skip the rest of the checks for a member of a dependent class.
7222 if (Record->isDependentType())
7223 return;
7224
7225 // For an explicitly defaulted or deleted special member, we defer
7226 // determining triviality until the class is complete. That time is now!
7227 CXXSpecialMemberKind CSM = getSpecialMember(MD: M);
7228 if (!M->isImplicit() && !M->isUserProvided()) {
7229 if (CSM != CXXSpecialMemberKind::Invalid) {
7230 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7231 // Inform the class that we've finished declaring this member.
7232 Record->finishedDefaultedOrDeletedMember(MD: M);
7233 M->setTrivialForCall(
7234 HasTrivialABI ||
7235 SpecialMemberIsTrivial(MD: M, CSM,
7236 TAH: TrivialABIHandling::ConsiderTrivialABI));
7237 Record->setTrivialForCallFlags(M);
7238 }
7239 }
7240
7241 // Set triviality for the purpose of calls if this is a user-provided
7242 // copy/move constructor or destructor.
7243 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7244 CSM == CXXSpecialMemberKind::MoveConstructor ||
7245 CSM == CXXSpecialMemberKind::Destructor) &&
7246 M->isUserProvided()) {
7247 M->setTrivialForCall(HasTrivialABI);
7248 Record->setTrivialForCallFlags(M);
7249 }
7250
7251 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7252 M->hasAttr<DLLExportAttr>()) {
7253 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7254 M->isTrivial() &&
7255 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7256 CSM == CXXSpecialMemberKind::CopyConstructor ||
7257 CSM == CXXSpecialMemberKind::Destructor))
7258 M->dropAttr<DLLExportAttr>();
7259
7260 if (M->hasAttr<DLLExportAttr>()) {
7261 // Define after any fields with in-class initializers have been parsed.
7262 DelayedDllExportMemberFunctions.push_back(Elt: M);
7263 }
7264 }
7265
7266 bool EffectivelyConstexprDestructor = true;
7267 // Avoid triggering vtable instantiation due to a dtor that is not
7268 // "effectively constexpr" for better compatibility.
7269 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7270 if (isa<CXXDestructorDecl>(Val: M)) {
7271 llvm::SmallDenseSet<QualType> Visited;
7272 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7273 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7274 return false;
7275 const CXXRecordDecl *RD =
7276 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7277 if (!RD || !RD->isCompleteDefinition())
7278 return true;
7279
7280 if (!RD->hasConstexprDestructor())
7281 return false;
7282
7283 for (const CXXBaseSpecifier &B : RD->bases())
7284 if (!Check(B.getType(), Check))
7285 return false;
7286 for (const FieldDecl *FD : RD->fields())
7287 if (!Check(FD->getType(), Check))
7288 return false;
7289 return true;
7290 };
7291 EffectivelyConstexprDestructor =
7292 Check(Context.getCanonicalTagType(TD: Record), Check);
7293 }
7294
7295 // Define defaulted constexpr virtual functions that override a base class
7296 // function right away.
7297 // FIXME: We can defer doing this until the vtable is marked as used.
7298 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7299 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7300 EffectivelyConstexprDestructor)
7301 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7302
7303 if (!Incomplete)
7304 CheckCompletedMemberFunction(M);
7305 };
7306
7307 // Check the destructor before any other member function. We need to
7308 // determine whether it's trivial in order to determine whether the claas
7309 // type is a literal type, which is a prerequisite for determining whether
7310 // other special member functions are valid and whether they're implicitly
7311 // 'constexpr'.
7312 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7313 CompleteMemberFunction(Dtor);
7314
7315 bool HasMethodWithOverrideControl = false,
7316 HasOverridingMethodWithoutOverrideControl = false;
7317 for (auto *D : Record->decls()) {
7318 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7319 // FIXME: We could do this check for dependent types with non-dependent
7320 // bases.
7321 if (!Record->isDependentType()) {
7322 // See if a method overloads virtual methods in a base
7323 // class without overriding any.
7324 if (!M->isStatic())
7325 DiagnoseHiddenVirtualMethods(MD: M);
7326
7327 if (M->hasAttr<OverrideAttr>()) {
7328 HasMethodWithOverrideControl = true;
7329 } else if (M->size_overridden_methods() > 0) {
7330 HasOverridingMethodWithoutOverrideControl = true;
7331 } else {
7332 // Warn on newly-declared virtual methods in `final` classes
7333 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7334 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7335 << M;
7336 }
7337 }
7338 }
7339
7340 if (!isa<CXXDestructorDecl>(Val: M))
7341 CompleteMemberFunction(M);
7342 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7343 CheckForDefaultedFunction(
7344 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7345 }
7346 }
7347
7348 if (HasOverridingMethodWithoutOverrideControl) {
7349 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7350 for (auto *M : Record->methods())
7351 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7352 }
7353
7354 // Check the defaulted secondary comparisons after any other member functions.
7355 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7356 CheckExplicitlyDefaultedFunction(S, MD: FD);
7357
7358 // If this is a member function, we deferred checking it until now.
7359 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7360 CheckCompletedMemberFunction(MD);
7361 }
7362
7363 // {ms,gcc}_struct is a request to change ABI rules to either follow
7364 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7365 // present, we do not layout classes following foreign ABI rules, but
7366 // instead enter a special "compatibility mode", which only changes
7367 // alignments of fundamental types and layout of bit fields.
7368 // Check whether this class uses any C++ features that are implemented
7369 // completely differently in the requested ABI, and if so, emit a
7370 // diagnostic. That diagnostic defaults to an error, but we allow
7371 // projects to map it down to a warning (or ignore it). It's a fairly
7372 // common practice among users of the ms_struct pragma to
7373 // mass-annotate headers, sweeping up a bunch of types that the
7374 // project doesn't really rely on MSVC-compatible layout for. We must
7375 // therefore support "ms_struct except for C++ stuff" as a secondary
7376 // ABI.
7377 // Don't emit this diagnostic if the feature was enabled as a
7378 // language option (as opposed to via a pragma or attribute), as
7379 // the option -mms-bitfields otherwise essentially makes it impossible
7380 // to build C++ code, unless this diagnostic is turned off.
7381 if (Context.getLangOpts().getLayoutCompatibility() ==
7382 LangOptions::LayoutCompatibilityKind::Default &&
7383 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7384 (Record->isPolymorphic() || Record->getNumBases())) {
7385 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7386 }
7387
7388 checkClassLevelDLLAttribute(Class: Record);
7389 checkClassLevelCodeSegAttribute(Class: Record);
7390
7391 bool ClangABICompat4 =
7392 Context.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver4;
7393 TargetInfo::CallingConvKind CCK =
7394 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7395 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7396
7397 // Do not change ArgPassingRestrictions if it has already been set to
7398 // RecordArgPassingKind::CanNeverPassInRegs.
7399 if (Record->getArgPassingRestrictions() !=
7400 RecordArgPassingKind::CanNeverPassInRegs)
7401 Record->setArgPassingRestrictions(
7402 CanPass ? RecordArgPassingKind::CanPassInRegs
7403 : RecordArgPassingKind::CannotPassInRegs);
7404
7405 // If canPassInRegisters returns true despite the record having a non-trivial
7406 // destructor, the record is destructed in the callee. This happens only when
7407 // the record or one of its subobjects has a field annotated with trivial_abi
7408 // or a field qualified with ObjC __strong/__weak.
7409 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7410 Record->setParamDestroyedInCallee(true);
7411 else if (Record->hasNonTrivialDestructor())
7412 Record->setParamDestroyedInCallee(CanPass);
7413
7414 if (getLangOpts().ForceEmitVTables) {
7415 // If we want to emit all the vtables, we need to mark it as used. This
7416 // is especially required for cases like vtable assumption loads.
7417 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7418 }
7419
7420 if (getLangOpts().CUDA) {
7421 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7422 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7423 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7424 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7425 }
7426
7427 llvm::SmallDenseMap<OverloadedOperatorKind,
7428 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7429 TypeAwareDecls{{OO_New, {}},
7430 {OO_Array_New, {}},
7431 {OO_Delete, {}},
7432 {OO_Array_New, {}}};
7433 for (auto *D : Record->decls()) {
7434 const FunctionDecl *FnDecl = D->getAsFunction();
7435 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7436 continue;
7437 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7438 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7439 }
7440 auto CheckMismatchedTypeAwareAllocators =
7441 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7442 OverloadedOperatorKind DeleteKind) {
7443 auto &NewDecls = TypeAwareDecls[NewKind];
7444 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7445 if (NewDecls.empty() == DeleteDecls.empty())
7446 return;
7447 DeclarationName FoundOperator =
7448 Context.DeclarationNames.getCXXOperatorName(
7449 Op: NewDecls.empty() ? DeleteKind : NewKind);
7450 DeclarationName MissingOperator =
7451 Context.DeclarationNames.getCXXOperatorName(
7452 Op: NewDecls.empty() ? NewKind : DeleteKind);
7453 Diag(Loc: Record->getLocation(),
7454 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7455 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7456 << MissingOperator;
7457 for (auto MD : NewDecls)
7458 Diag(Loc: MD->getLocation(),
7459 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7460 << MD;
7461 for (auto MD : DeleteDecls)
7462 Diag(Loc: MD->getLocation(),
7463 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7464 << MD;
7465 };
7466 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7467 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7468}
7469
7470/// Look up the special member function that would be called by a special
7471/// member function for a subobject of class type.
7472///
7473/// \param Class The class type of the subobject.
7474/// \param CSM The kind of special member function.
7475/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7476/// \param ConstRHS True if this is a copy operation with a const object
7477/// on its RHS, that is, if the argument to the outer special member
7478/// function is 'const' and this is not a field marked 'mutable'.
7479static Sema::SpecialMemberOverloadResult
7480lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7481 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7482 bool ConstRHS) {
7483 unsigned LHSQuals = 0;
7484 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7485 CSM == CXXSpecialMemberKind::MoveAssignment)
7486 LHSQuals = FieldQuals;
7487
7488 unsigned RHSQuals = FieldQuals;
7489 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7490 CSM == CXXSpecialMemberKind::Destructor)
7491 RHSQuals = 0;
7492 else if (ConstRHS)
7493 RHSQuals |= Qualifiers::Const;
7494
7495 return S.LookupSpecialMember(D: Class, SM: CSM,
7496 ConstArg: RHSQuals & Qualifiers::Const,
7497 VolatileArg: RHSQuals & Qualifiers::Volatile,
7498 RValueThis: false,
7499 ConstThis: LHSQuals & Qualifiers::Const,
7500 VolatileThis: LHSQuals & Qualifiers::Volatile);
7501}
7502
7503class Sema::InheritedConstructorInfo {
7504 Sema &S;
7505 SourceLocation UseLoc;
7506
7507 /// A mapping from the base classes through which the constructor was
7508 /// inherited to the using shadow declaration in that base class (or a null
7509 /// pointer if the constructor was declared in that base class).
7510 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7511 InheritedFromBases;
7512
7513public:
7514 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7515 ConstructorUsingShadowDecl *Shadow)
7516 : S(S), UseLoc(UseLoc) {
7517 bool DiagnosedMultipleConstructedBases = false;
7518 CXXRecordDecl *ConstructedBase = nullptr;
7519 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7520
7521 // Find the set of such base class subobjects and check that there's a
7522 // unique constructed subobject.
7523 for (auto *D : Shadow->redecls()) {
7524 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7525 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7526 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7527
7528 InheritedFromBases.insert(
7529 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7530 y: DShadow->getNominatedBaseClassShadowDecl()));
7531 if (DShadow->constructsVirtualBase())
7532 InheritedFromBases.insert(
7533 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7534 y: DShadow->getConstructedBaseClassShadowDecl()));
7535 else
7536 assert(DNominatedBase == DConstructedBase);
7537
7538 // [class.inhctor.init]p2:
7539 // If the constructor was inherited from multiple base class subobjects
7540 // of type B, the program is ill-formed.
7541 if (!ConstructedBase) {
7542 ConstructedBase = DConstructedBase;
7543 ConstructedBaseIntroducer = D->getIntroducer();
7544 } else if (ConstructedBase != DConstructedBase &&
7545 !Shadow->isInvalidDecl()) {
7546 if (!DiagnosedMultipleConstructedBases) {
7547 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7548 << Shadow->getTargetDecl();
7549 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7550 DiagID: diag::note_ambiguous_inherited_constructor_using)
7551 << ConstructedBase;
7552 DiagnosedMultipleConstructedBases = true;
7553 }
7554 S.Diag(Loc: D->getIntroducer()->getLocation(),
7555 DiagID: diag::note_ambiguous_inherited_constructor_using)
7556 << DConstructedBase;
7557 }
7558 }
7559
7560 if (DiagnosedMultipleConstructedBases)
7561 Shadow->setInvalidDecl();
7562 }
7563
7564 /// Find the constructor to use for inherited construction of a base class,
7565 /// and whether that base class constructor inherits the constructor from a
7566 /// virtual base class (in which case it won't actually invoke it).
7567 std::pair<CXXConstructorDecl *, bool>
7568 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7569 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7570 if (It == InheritedFromBases.end())
7571 return std::make_pair(x: nullptr, y: false);
7572
7573 // This is an intermediary class.
7574 if (It->second)
7575 return std::make_pair(
7576 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7577 y: It->second->constructsVirtualBase());
7578
7579 // This is the base class from which the constructor was inherited.
7580 return std::make_pair(x&: Ctor, y: false);
7581 }
7582};
7583
7584/// Is the special member function which would be selected to perform the
7585/// specified operation on the specified class type a constexpr constructor?
7586static bool specialMemberIsConstexpr(
7587 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7588 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7589 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7590 // Suppress duplicate constraint checking here, in case a constraint check
7591 // caused us to decide to do this. Any truely recursive checks will get
7592 // caught during these checks anyway.
7593 Sema::SatisfactionStackResetRAII SSRAII{S};
7594
7595 // If we're inheriting a constructor, see if we need to call it for this base
7596 // class.
7597 if (InheritedCtor) {
7598 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7599 auto BaseCtor =
7600 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7601 if (BaseCtor)
7602 return BaseCtor->isConstexpr();
7603 }
7604
7605 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7606 return ClassDecl->hasConstexprDefaultConstructor();
7607 if (CSM == CXXSpecialMemberKind::Destructor)
7608 return ClassDecl->hasConstexprDestructor();
7609
7610 Sema::SpecialMemberOverloadResult SMOR =
7611 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7612 if (!SMOR.getMethod())
7613 // A constructor we wouldn't select can't be "involved in initializing"
7614 // anything.
7615 return true;
7616 return SMOR.getMethod()->isConstexpr();
7617}
7618
7619/// Determine whether the specified special member function would be constexpr
7620/// if it were implicitly defined.
7621static bool defaultedSpecialMemberIsConstexpr(
7622 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7623 CXXConstructorDecl *InheritedCtor = nullptr,
7624 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7625 if (!S.getLangOpts().CPlusPlus11)
7626 return false;
7627
7628 // C++11 [dcl.constexpr]p4:
7629 // In the definition of a constexpr constructor [...]
7630 bool Ctor = true;
7631 switch (CSM) {
7632 case CXXSpecialMemberKind::DefaultConstructor:
7633 if (Inherited)
7634 break;
7635 // Since default constructor lookup is essentially trivial (and cannot
7636 // involve, for instance, template instantiation), we compute whether a
7637 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7638 //
7639 // This is important for performance; we need to know whether the default
7640 // constructor is constexpr to determine whether the type is a literal type.
7641 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7642
7643 case CXXSpecialMemberKind::CopyConstructor:
7644 case CXXSpecialMemberKind::MoveConstructor:
7645 // For copy or move constructors, we need to perform overload resolution.
7646 break;
7647
7648 case CXXSpecialMemberKind::CopyAssignment:
7649 case CXXSpecialMemberKind::MoveAssignment:
7650 if (!S.getLangOpts().CPlusPlus14)
7651 return false;
7652 // In C++1y, we need to perform overload resolution.
7653 Ctor = false;
7654 break;
7655
7656 case CXXSpecialMemberKind::Destructor:
7657 return ClassDecl->defaultedDestructorIsConstexpr();
7658
7659 case CXXSpecialMemberKind::Invalid:
7660 return false;
7661 }
7662
7663 // -- if the class is a non-empty union, or for each non-empty anonymous
7664 // union member of a non-union class, exactly one non-static data member
7665 // shall be initialized; [DR1359]
7666 //
7667 // If we squint, this is guaranteed, since exactly one non-static data member
7668 // will be initialized (if the constructor isn't deleted), we just don't know
7669 // which one.
7670 if (Ctor && ClassDecl->isUnion())
7671 return CSM == CXXSpecialMemberKind::DefaultConstructor
7672 ? ClassDecl->hasInClassInitializer() ||
7673 !ClassDecl->hasVariantMembers()
7674 : true;
7675
7676 // -- the class shall not have any virtual base classes;
7677 if (Ctor && ClassDecl->getNumVBases())
7678 return false;
7679
7680 // C++1y [class.copy]p26:
7681 // -- [the class] is a literal type, and
7682 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7683 return false;
7684
7685 // -- every constructor involved in initializing [...] base class
7686 // sub-objects shall be a constexpr constructor;
7687 // -- the assignment operator selected to copy/move each direct base
7688 // class is a constexpr function, and
7689 if (!S.getLangOpts().CPlusPlus23) {
7690 for (const auto &B : ClassDecl->bases()) {
7691 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7692 if (!BaseClassDecl)
7693 continue;
7694 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7695 InheritedCtor, Inherited))
7696 return false;
7697 }
7698 }
7699
7700 // -- every constructor involved in initializing non-static data members
7701 // [...] shall be a constexpr constructor;
7702 // -- every non-static data member and base class sub-object shall be
7703 // initialized
7704 // -- for each non-static data member of X that is of class type (or array
7705 // thereof), the assignment operator selected to copy/move that member is
7706 // a constexpr function
7707 if (!S.getLangOpts().CPlusPlus23) {
7708 for (const auto *F : ClassDecl->fields()) {
7709 if (F->isInvalidDecl())
7710 continue;
7711 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7712 F->hasInClassInitializer())
7713 continue;
7714 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7715 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7716 auto *FieldRecDecl =
7717 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7718 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7719 Quals: BaseType.getCVRQualifiers(),
7720 ConstRHS: ConstArg && !F->isMutable()))
7721 return false;
7722 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7723 return false;
7724 }
7725 }
7726 }
7727
7728 // All OK, it's constexpr!
7729 return true;
7730}
7731
7732namespace {
7733/// RAII object to register a defaulted function as having its exception
7734/// specification computed.
7735struct ComputingExceptionSpec {
7736 Sema &S;
7737
7738 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7739 : S(S) {
7740 Sema::CodeSynthesisContext Ctx;
7741 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7742 Ctx.PointOfInstantiation = Loc;
7743 Ctx.Entity = FD;
7744 S.pushCodeSynthesisContext(Ctx);
7745 }
7746 ~ComputingExceptionSpec() {
7747 S.popCodeSynthesisContext();
7748 }
7749};
7750}
7751
7752static Sema::ImplicitExceptionSpecification
7753ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7754 CXXMethodDecl *MD,
7755 CXXSpecialMemberKind CSM,
7756 Sema::InheritedConstructorInfo *ICI);
7757
7758static Sema::ImplicitExceptionSpecification
7759ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7760 FunctionDecl *FD,
7761 Sema::DefaultedComparisonKind DCK);
7762
7763static Sema::ImplicitExceptionSpecification
7764computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7765 auto DFK = S.getDefaultedFunctionKind(FD);
7766 if (DFK.isSpecialMember())
7767 return ComputeDefaultedSpecialMemberExceptionSpec(
7768 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7769 if (DFK.isComparison())
7770 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7771 DCK: DFK.asComparison());
7772
7773 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7774 assert(CD->getInheritedConstructor() &&
7775 "only defaulted functions and inherited constructors have implicit "
7776 "exception specs");
7777 Sema::InheritedConstructorInfo ICI(
7778 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7779 return ComputeDefaultedSpecialMemberExceptionSpec(
7780 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7781}
7782
7783static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7784 CXXMethodDecl *MD) {
7785 FunctionProtoType::ExtProtoInfo EPI;
7786
7787 // Build an exception specification pointing back at this member.
7788 EPI.ExceptionSpec.Type = EST_Unevaluated;
7789 EPI.ExceptionSpec.SourceDecl = MD;
7790
7791 // Set the calling convention to the default for C++ instance methods.
7792 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7793 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7794 /*IsCXXMethod=*/true));
7795 return EPI;
7796}
7797
7798void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7799 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7800 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7801 return;
7802
7803 // Evaluate the exception specification.
7804 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7805 auto ESI = IES.getExceptionSpec();
7806
7807 // Update the type of the special member to use it.
7808 UpdateExceptionSpec(FD, ESI);
7809}
7810
7811void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7812 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7813
7814 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7815 if (!DefKind) {
7816 assert(FD->getDeclContext()->isDependentContext());
7817 return;
7818 }
7819
7820 if (DefKind.isComparison()) {
7821 auto PT = FD->getParamDecl(i: 0)->getType();
7822 if (const CXXRecordDecl *RD =
7823 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7824 for (FieldDecl *Field : RD->fields()) {
7825 UnusedPrivateFields.remove(X: Field);
7826 }
7827 }
7828 }
7829
7830 if (DefKind.isSpecialMember()
7831 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7832 CSM: DefKind.asSpecialMember(),
7833 DefaultLoc: FD->getDefaultLoc())
7834 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7835 FD->setInvalidDecl();
7836}
7837
7838bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7839 CXXSpecialMemberKind CSM,
7840 SourceLocation DefaultLoc) {
7841 CXXRecordDecl *RD = MD->getParent();
7842
7843 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7844 "not an explicitly-defaulted special member");
7845
7846 // Defer all checking for special members of a dependent type.
7847 if (RD->isDependentType())
7848 return false;
7849
7850 // Whether this was the first-declared instance of the constructor.
7851 // This affects whether we implicitly add an exception spec and constexpr.
7852 bool First = MD == MD->getCanonicalDecl();
7853
7854 bool HadError = false;
7855
7856 // C++11 [dcl.fct.def.default]p1:
7857 // A function that is explicitly defaulted shall
7858 // -- be a special member function [...] (checked elsewhere),
7859 // -- have the same type (except for ref-qualifiers, and except that a
7860 // copy operation can take a non-const reference) as an implicit
7861 // declaration, and
7862 // -- not have default arguments.
7863 // C++2a changes the second bullet to instead delete the function if it's
7864 // defaulted on its first declaration, unless it's "an assignment operator,
7865 // and its return type differs or its parameter type is not a reference".
7866 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7867 bool ShouldDeleteForTypeMismatch = false;
7868 unsigned ExpectedParams = 1;
7869 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7870 CSM == CXXSpecialMemberKind::Destructor)
7871 ExpectedParams = 0;
7872 if (MD->getNumExplicitParams() != ExpectedParams) {
7873 // This checks for default arguments: a copy or move constructor with a
7874 // default argument is classified as a default constructor, and assignment
7875 // operations and destructors can't have default arguments.
7876 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7877 << CSM << MD->getSourceRange();
7878 HadError = true;
7879 } else if (MD->isVariadic()) {
7880 if (DeleteOnTypeMismatch)
7881 ShouldDeleteForTypeMismatch = true;
7882 else {
7883 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7884 << CSM << MD->getSourceRange();
7885 HadError = true;
7886 }
7887 }
7888
7889 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7890
7891 bool CanHaveConstParam = false;
7892 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7893 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7894 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7895 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7896
7897 QualType ReturnType = Context.VoidTy;
7898 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7899 CSM == CXXSpecialMemberKind::MoveAssignment) {
7900 // Check for return type matching.
7901 ReturnType = Type->getReturnType();
7902 QualType ThisType = MD->getFunctionObjectParameterType();
7903
7904 QualType DeclType =
7905 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7906 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7907 DeclType = Context.getAddrSpaceQualType(
7908 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7909 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7910
7911 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7912 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7913 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7914 << ExpectedReturnType;
7915 HadError = true;
7916 }
7917
7918 // A defaulted special member cannot have cv-qualifiers.
7919 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7920 if (DeleteOnTypeMismatch)
7921 ShouldDeleteForTypeMismatch = true;
7922 else {
7923 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7924 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7925 << getLangOpts().CPlusPlus14;
7926 HadError = true;
7927 }
7928 }
7929 // [C++23][dcl.fct.def.default]/p2.2
7930 // if F2 has an implicit object parameter of type “reference to C”,
7931 // F1 may be an explicit object member function whose explicit object
7932 // parameter is of (possibly different) type “reference to C”,
7933 // in which case the type of F1 would differ from the type of F2
7934 // in that the type of F1 has an additional parameter;
7935 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7936 ? MD->getParamDecl(i: 0)->getType()
7937 : QualType();
7938 if (!ExplicitObjectParameter.isNull() &&
7939 (!ExplicitObjectParameter->isReferenceType() ||
7940 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7941 T2: Context.getCanonicalTagType(TD: RD)))) {
7942 if (DeleteOnTypeMismatch)
7943 ShouldDeleteForTypeMismatch = true;
7944 else {
7945 Diag(Loc: MD->getLocation(),
7946 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
7947 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7948 << MD->getSourceRange();
7949 HadError = true;
7950 }
7951 }
7952 }
7953
7954 // Check for parameter type matching.
7955 QualType ArgType =
7956 ExpectedParams
7957 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7958 : QualType();
7959 bool HasConstParam = false;
7960 if (ExpectedParams && ArgType->isReferenceType()) {
7961 // Argument must be reference to possibly-const T.
7962 QualType ReferentType = ArgType->getPointeeType();
7963 HasConstParam = ReferentType.isConstQualified();
7964
7965 if (ReferentType.isVolatileQualified()) {
7966 if (DeleteOnTypeMismatch)
7967 ShouldDeleteForTypeMismatch = true;
7968 else {
7969 Diag(Loc: MD->getLocation(),
7970 DiagID: diag::err_defaulted_special_member_volatile_param)
7971 << CSM;
7972 HadError = true;
7973 }
7974 }
7975
7976 if (HasConstParam && !CanHaveConstParam) {
7977 if (DeleteOnTypeMismatch)
7978 ShouldDeleteForTypeMismatch = true;
7979 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
7980 CSM == CXXSpecialMemberKind::CopyAssignment) {
7981 Diag(Loc: MD->getLocation(),
7982 DiagID: diag::err_defaulted_special_member_copy_const_param)
7983 << (CSM == CXXSpecialMemberKind::CopyAssignment);
7984 // FIXME: Explain why this special member can't be const.
7985 HadError = true;
7986 } else {
7987 Diag(Loc: MD->getLocation(),
7988 DiagID: diag::err_defaulted_special_member_move_const_param)
7989 << (CSM == CXXSpecialMemberKind::MoveAssignment);
7990 HadError = true;
7991 }
7992 }
7993 } else if (ExpectedParams) {
7994 // A copy assignment operator can take its argument by value, but a
7995 // defaulted one cannot.
7996 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
7997 "unexpected non-ref argument");
7998 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
7999 HadError = true;
8000 }
8001
8002 // C++11 [dcl.fct.def.default]p2:
8003 // An explicitly-defaulted function may be declared constexpr only if it
8004 // would have been implicitly declared as constexpr,
8005 // Do not apply this rule to members of class templates, since core issue 1358
8006 // makes such functions always instantiate to constexpr functions. For
8007 // functions which cannot be constexpr (for non-constructors in C++11 and for
8008 // destructors in C++14 and C++17), this is checked elsewhere.
8009 //
8010 // FIXME: This should not apply if the member is deleted.
8011 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8012 ConstArg: HasConstParam);
8013
8014 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8015 // If the instantiated template specialization of a constexpr function
8016 // template or member function of a class template would fail to satisfy
8017 // the requirements for a constexpr function or constexpr constructor, that
8018 // specialization is still a constexpr function or constexpr constructor,
8019 // even though a call to such a function cannot appear in a constant
8020 // expression.
8021 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8022 Constexpr = true;
8023
8024 if ((getLangOpts().CPlusPlus20 ||
8025 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8026 : isa<CXXConstructorDecl>(Val: MD))) &&
8027 MD->isConstexpr() && !Constexpr &&
8028 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8029 if (!MD->isConsteval() && RD->getNumVBases()) {
8030 Diag(Loc: MD->getBeginLoc(),
8031 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8032 << CSM;
8033 for (const auto &I : RD->vbases())
8034 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8035 } else {
8036 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8037 << CSM << MD->isConsteval();
8038 }
8039 HadError = true;
8040 // FIXME: Explain why the special member can't be constexpr.
8041 }
8042
8043 if (First) {
8044 // C++2a [dcl.fct.def.default]p3:
8045 // If a function is explicitly defaulted on its first declaration, it is
8046 // implicitly considered to be constexpr if the implicit declaration
8047 // would be.
8048 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8049 ? ConstexprSpecKind::Consteval
8050 : ConstexprSpecKind::Constexpr)
8051 : ConstexprSpecKind::Unspecified);
8052
8053 if (!Type->hasExceptionSpec()) {
8054 // C++2a [except.spec]p3:
8055 // If a declaration of a function does not have a noexcept-specifier
8056 // [and] is defaulted on its first declaration, [...] the exception
8057 // specification is as specified below
8058 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8059 EPI.ExceptionSpec.Type = EST_Unevaluated;
8060 EPI.ExceptionSpec.SourceDecl = MD;
8061 MD->setType(
8062 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8063 }
8064 }
8065
8066 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8067 if (First) {
8068 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8069 if (!inTemplateInstantiation() && !HadError) {
8070 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8071 if (ShouldDeleteForTypeMismatch) {
8072 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8073 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8074 /*Diagnose*/ true) &&
8075 DefaultLoc.isValid()) {
8076 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8077 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8078 }
8079 }
8080 if (ShouldDeleteForTypeMismatch && !HadError) {
8081 Diag(Loc: MD->getLocation(),
8082 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8083 << CSM;
8084 }
8085 } else {
8086 // C++11 [dcl.fct.def.default]p4:
8087 // [For a] user-provided explicitly-defaulted function [...] if such a
8088 // function is implicitly defined as deleted, the program is ill-formed.
8089 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8090 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8091 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8092 HadError = true;
8093 }
8094 }
8095
8096 return HadError;
8097}
8098
8099namespace {
8100/// Helper class for building and checking a defaulted comparison.
8101///
8102/// Defaulted functions are built in two phases:
8103///
8104/// * First, the set of operations that the function will perform are
8105/// identified, and some of them are checked. If any of the checked
8106/// operations is invalid in certain ways, the comparison function is
8107/// defined as deleted and no body is built.
8108/// * Then, if the function is not defined as deleted, the body is built.
8109///
8110/// This is accomplished by performing two visitation steps over the eventual
8111/// body of the function.
8112template<typename Derived, typename ResultList, typename Result,
8113 typename Subobject>
8114class DefaultedComparisonVisitor {
8115public:
8116 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8117
8118 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8119 DefaultedComparisonKind DCK)
8120 : S(S), RD(RD), FD(FD), DCK(DCK) {
8121 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8122 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8123 // UnresolvedSet to avoid this copy.
8124 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8125 E: Info->getUnqualifiedLookups().end());
8126 }
8127 }
8128
8129 ResultList visit() {
8130 // The type of an lvalue naming a parameter of this function.
8131 QualType ParamLvalType =
8132 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8133
8134 ResultList Results;
8135
8136 switch (DCK) {
8137 case DefaultedComparisonKind::None:
8138 llvm_unreachable("not a defaulted comparison");
8139
8140 case DefaultedComparisonKind::Equal:
8141 case DefaultedComparisonKind::ThreeWay:
8142 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8143 return Results;
8144
8145 case DefaultedComparisonKind::NotEqual:
8146 case DefaultedComparisonKind::Relational:
8147 Results.add(getDerived().visitExpandedSubobject(
8148 ParamLvalType, getDerived().getCompleteObject()));
8149 return Results;
8150 }
8151 llvm_unreachable("");
8152 }
8153
8154protected:
8155 Derived &getDerived() { return static_cast<Derived&>(*this); }
8156
8157 /// Visit the expanded list of subobjects of the given type, as specified in
8158 /// C++2a [class.compare.default].
8159 ///
8160 /// \return \c true if the ResultList object said we're done, \c false if not.
8161 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8162 Qualifiers Quals) {
8163 // C++2a [class.compare.default]p4:
8164 // The direct base class subobjects of C
8165 for (CXXBaseSpecifier &Base : Record->bases())
8166 if (Results.add(getDerived().visitSubobject(
8167 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8168 getDerived().getBase(&Base))))
8169 return true;
8170
8171 // followed by the non-static data members of C
8172 for (FieldDecl *Field : Record->fields()) {
8173 // C++23 [class.bit]p2:
8174 // Unnamed bit-fields are not members ...
8175 if (Field->isUnnamedBitField())
8176 continue;
8177 // Recursively expand anonymous structs.
8178 if (Field->isAnonymousStructOrUnion()) {
8179 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8180 Quals))
8181 return true;
8182 continue;
8183 }
8184
8185 // Figure out the type of an lvalue denoting this field.
8186 Qualifiers FieldQuals = Quals;
8187 if (Field->isMutable())
8188 FieldQuals.removeConst();
8189 QualType FieldType =
8190 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8191
8192 if (Results.add(getDerived().visitSubobject(
8193 FieldType, getDerived().getField(Field))))
8194 return true;
8195 }
8196
8197 // form a list of subobjects.
8198 return false;
8199 }
8200
8201 Result visitSubobject(QualType Type, Subobject Subobj) {
8202 // In that list, any subobject of array type is recursively expanded
8203 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8204 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8205 return getDerived().visitSubobjectArray(CAT->getElementType(),
8206 CAT->getSize(), Subobj);
8207 return getDerived().visitExpandedSubobject(Type, Subobj);
8208 }
8209
8210 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8211 Subobject Subobj) {
8212 return getDerived().visitSubobject(Type, Subobj);
8213 }
8214
8215protected:
8216 Sema &S;
8217 CXXRecordDecl *RD;
8218 FunctionDecl *FD;
8219 DefaultedComparisonKind DCK;
8220 UnresolvedSet<16> Fns;
8221};
8222
8223/// Information about a defaulted comparison, as determined by
8224/// DefaultedComparisonAnalyzer.
8225struct DefaultedComparisonInfo {
8226 bool Deleted = false;
8227 bool Constexpr = true;
8228 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8229
8230 static DefaultedComparisonInfo deleted() {
8231 DefaultedComparisonInfo Deleted;
8232 Deleted.Deleted = true;
8233 return Deleted;
8234 }
8235
8236 bool add(const DefaultedComparisonInfo &R) {
8237 Deleted |= R.Deleted;
8238 Constexpr &= R.Constexpr;
8239 Category = commonComparisonType(A: Category, B: R.Category);
8240 return Deleted;
8241 }
8242};
8243
8244/// An element in the expanded list of subobjects of a defaulted comparison, as
8245/// specified in C++2a [class.compare.default]p4.
8246struct DefaultedComparisonSubobject {
8247 enum { CompleteObject, Member, Base } Kind;
8248 NamedDecl *Decl;
8249 SourceLocation Loc;
8250};
8251
8252/// A visitor over the notional body of a defaulted comparison that determines
8253/// whether that body would be deleted or constexpr.
8254class DefaultedComparisonAnalyzer
8255 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8256 DefaultedComparisonInfo,
8257 DefaultedComparisonInfo,
8258 DefaultedComparisonSubobject> {
8259public:
8260 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8261
8262private:
8263 DiagnosticKind Diagnose;
8264
8265public:
8266 using Base = DefaultedComparisonVisitor;
8267 using Result = DefaultedComparisonInfo;
8268 using Subobject = DefaultedComparisonSubobject;
8269
8270 friend Base;
8271
8272 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8273 DefaultedComparisonKind DCK,
8274 DiagnosticKind Diagnose = NoDiagnostics)
8275 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8276
8277 Result visit() {
8278 if ((DCK == DefaultedComparisonKind::Equal ||
8279 DCK == DefaultedComparisonKind::ThreeWay) &&
8280 RD->hasVariantMembers()) {
8281 // C++2a [class.compare.default]p2 [P2002R0]:
8282 // A defaulted comparison operator function for class C is defined as
8283 // deleted if [...] C has variant members.
8284 if (Diagnose == ExplainDeleted) {
8285 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8286 << FD << RD->isUnion() << RD;
8287 }
8288 return Result::deleted();
8289 }
8290
8291 return Base::visit();
8292 }
8293
8294private:
8295 Subobject getCompleteObject() {
8296 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8297 }
8298
8299 Subobject getBase(CXXBaseSpecifier *Base) {
8300 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8301 .Loc: Base->getBaseTypeLoc()};
8302 }
8303
8304 Subobject getField(FieldDecl *Field) {
8305 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8306 }
8307
8308 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8309 // C++2a [class.compare.default]p2 [P2002R0]:
8310 // A defaulted <=> or == operator function for class C is defined as
8311 // deleted if any non-static data member of C is of reference type
8312 if (Type->isReferenceType()) {
8313 if (Diagnose == ExplainDeleted) {
8314 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8315 << FD << RD;
8316 }
8317 return Result::deleted();
8318 }
8319
8320 // [...] Let xi be an lvalue denoting the ith element [...]
8321 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8322 Expr *Args[] = {&Xi, &Xi};
8323
8324 // All operators start by trying to apply that same operator recursively.
8325 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8326 assert(OO != OO_None && "not an overloaded operator!");
8327 return visitBinaryOperator(OO, Args, Subobj);
8328 }
8329
8330 Result
8331 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8332 Subobject Subobj,
8333 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8334 // Note that there is no need to consider rewritten candidates here if
8335 // we've already found there is no viable 'operator<=>' candidate (and are
8336 // considering synthesizing a '<=>' from '==' and '<').
8337 OverloadCandidateSet CandidateSet(
8338 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8339 OverloadCandidateSet::OperatorRewriteInfo(
8340 OO, FD->getLocation(),
8341 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8342
8343 /// C++2a [class.compare.default]p1 [P2002R0]:
8344 /// [...] the defaulted function itself is never a candidate for overload
8345 /// resolution [...]
8346 CandidateSet.exclude(F: FD);
8347
8348 if (Args[0]->getType()->isOverloadableType())
8349 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8350 else
8351 // FIXME: We determine whether this is a valid expression by checking to
8352 // see if there's a viable builtin operator candidate for it. That isn't
8353 // really what the rules ask us to do, but should give the right results.
8354 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8355
8356 Result R;
8357
8358 OverloadCandidateSet::iterator Best;
8359 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8360 case OR_Success: {
8361 // C++2a [class.compare.secondary]p2 [P2002R0]:
8362 // The operator function [...] is defined as deleted if [...] the
8363 // candidate selected by overload resolution is not a rewritten
8364 // candidate.
8365 if ((DCK == DefaultedComparisonKind::NotEqual ||
8366 DCK == DefaultedComparisonKind::Relational) &&
8367 !Best->RewriteKind) {
8368 if (Diagnose == ExplainDeleted) {
8369 if (Best->Function) {
8370 S.Diag(Loc: Best->Function->getLocation(),
8371 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8372 << FD;
8373 } else {
8374 assert(Best->Conversions.size() == 2 &&
8375 Best->Conversions[0].isUserDefined() &&
8376 "non-user-defined conversion from class to built-in "
8377 "comparison");
8378 S.Diag(Loc: Best->Conversions[0]
8379 .UserDefined.FoundConversionFunction.getDecl()
8380 ->getLocation(),
8381 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8382 << FD;
8383 }
8384 }
8385 return Result::deleted();
8386 }
8387
8388 // Throughout C++2a [class.compare]: if overload resolution does not
8389 // result in a usable function, the candidate function is defined as
8390 // deleted. This requires that we selected an accessible function.
8391 //
8392 // Note that this only considers the access of the function when named
8393 // within the type of the subobject, and not the access path for any
8394 // derived-to-base conversion.
8395 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8396 if (ArgClass && Best->FoundDecl.getDecl() &&
8397 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8398 QualType ObjectType = Subobj.Kind == Subobject::Member
8399 ? Args[0]->getType()
8400 : S.Context.getCanonicalTagType(TD: RD);
8401 if (!S.isMemberAccessibleForDeletion(
8402 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8403 Diag: Diagnose == ExplainDeleted
8404 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8405 << FD << Subobj.Kind << Subobj.Decl
8406 : S.PDiag()))
8407 return Result::deleted();
8408 }
8409
8410 bool NeedsDeducing =
8411 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8412
8413 if (FunctionDecl *BestFD = Best->Function) {
8414 // C++2a [class.compare.default]p3 [P2002R0]:
8415 // A defaulted comparison function is constexpr-compatible if
8416 // [...] no overlod resolution performed [...] results in a
8417 // non-constexpr function.
8418 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8419 // If it's not constexpr, explain why not.
8420 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8421 if (Subobj.Kind != Subobject::CompleteObject)
8422 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8423 << Subobj.Kind << Subobj.Decl;
8424 S.Diag(Loc: BestFD->getLocation(),
8425 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8426 // Bail out after explaining; we don't want any more notes.
8427 return Result::deleted();
8428 }
8429 R.Constexpr &= BestFD->isConstexpr();
8430
8431 if (NeedsDeducing) {
8432 // If any callee has an undeduced return type, deduce it now.
8433 // FIXME: It's not clear how a failure here should be handled. For
8434 // now, we produce an eager diagnostic, because that is forward
8435 // compatible with most (all?) other reasonable options.
8436 if (BestFD->getReturnType()->isUndeducedType() &&
8437 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8438 /*Diagnose=*/false)) {
8439 // Don't produce a duplicate error when asked to explain why the
8440 // comparison is deleted: we diagnosed that when initially checking
8441 // the defaulted operator.
8442 if (Diagnose == NoDiagnostics) {
8443 S.Diag(
8444 Loc: FD->getLocation(),
8445 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8446 << Subobj.Kind << Subobj.Decl;
8447 S.Diag(
8448 Loc: Subobj.Loc,
8449 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8450 << Subobj.Kind << Subobj.Decl;
8451 S.Diag(Loc: BestFD->getLocation(),
8452 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8453 << Subobj.Kind << Subobj.Decl;
8454 }
8455 return Result::deleted();
8456 }
8457 auto *Info = S.Context.CompCategories.lookupInfoForType(
8458 Ty: BestFD->getCallResultType());
8459 if (!Info) {
8460 if (Diagnose == ExplainDeleted) {
8461 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8462 << Subobj.Kind << Subobj.Decl
8463 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8464 S.Diag(Loc: BestFD->getLocation(),
8465 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8466 << Subobj.Kind << Subobj.Decl;
8467 }
8468 return Result::deleted();
8469 }
8470 R.Category = Info->Kind;
8471 }
8472 } else {
8473 QualType T = Best->BuiltinParamTypes[0];
8474 assert(T == Best->BuiltinParamTypes[1] &&
8475 "builtin comparison for different types?");
8476 assert(Best->BuiltinParamTypes[2].isNull() &&
8477 "invalid builtin comparison");
8478
8479 // FIXME: If the type we deduced is a vector type, we mark the
8480 // comparison as deleted because we don't yet support this.
8481 if (isa<VectorType>(Val: T)) {
8482 if (Diagnose == ExplainDeleted) {
8483 S.Diag(Loc: FD->getLocation(),
8484 DiagID: diag::note_defaulted_comparison_vector_types)
8485 << FD;
8486 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8487 }
8488 return Result::deleted();
8489 }
8490
8491 if (NeedsDeducing) {
8492 std::optional<ComparisonCategoryType> Cat =
8493 getComparisonCategoryForBuiltinCmp(T);
8494 assert(Cat && "no category for builtin comparison?");
8495 R.Category = *Cat;
8496 }
8497 }
8498
8499 // Note that we might be rewriting to a different operator. That call is
8500 // not considered until we come to actually build the comparison function.
8501 break;
8502 }
8503
8504 case OR_Ambiguous:
8505 if (Diagnose == ExplainDeleted) {
8506 unsigned Kind = 0;
8507 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8508 Kind = OO == OO_EqualEqual ? 1 : 2;
8509 CandidateSet.NoteCandidates(
8510 PA: PartialDiagnosticAt(
8511 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8512 << FD << Kind << Subobj.Kind << Subobj.Decl),
8513 S, OCD: OCD_AmbiguousCandidates, Args);
8514 }
8515 R = Result::deleted();
8516 break;
8517
8518 case OR_Deleted:
8519 if (Diagnose == ExplainDeleted) {
8520 if ((DCK == DefaultedComparisonKind::NotEqual ||
8521 DCK == DefaultedComparisonKind::Relational) &&
8522 !Best->RewriteKind) {
8523 S.Diag(Loc: Best->Function->getLocation(),
8524 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8525 << FD;
8526 } else {
8527 S.Diag(Loc: Subobj.Loc,
8528 DiagID: diag::note_defaulted_comparison_calls_deleted)
8529 << FD << Subobj.Kind << Subobj.Decl;
8530 S.NoteDeletedFunction(FD: Best->Function);
8531 }
8532 }
8533 R = Result::deleted();
8534 break;
8535
8536 case OR_No_Viable_Function:
8537 // If there's no usable candidate, we're done unless we can rewrite a
8538 // '<=>' in terms of '==' and '<'.
8539 if (OO == OO_Spaceship &&
8540 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8541 // For any kind of comparison category return type, we need a usable
8542 // '==' and a usable '<'.
8543 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8544 SpaceshipCandidates: &CandidateSet)))
8545 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8546 break;
8547 }
8548
8549 if (Diagnose == ExplainDeleted) {
8550 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8551 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8552 << Subobj.Kind << Subobj.Decl;
8553
8554 // For a three-way comparison, list both the candidates for the
8555 // original operator and the candidates for the synthesized operator.
8556 if (SpaceshipCandidates) {
8557 SpaceshipCandidates->NoteCandidates(
8558 S, Args,
8559 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8560 Args, OpLoc: FD->getLocation()));
8561 S.Diag(Loc: Subobj.Loc,
8562 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8563 << (OO == OO_EqualEqual ? 0 : 1);
8564 }
8565
8566 CandidateSet.NoteCandidates(
8567 S, Args,
8568 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8569 OpLoc: FD->getLocation()));
8570 }
8571 R = Result::deleted();
8572 break;
8573 }
8574
8575 return R;
8576 }
8577};
8578
8579/// A list of statements.
8580struct StmtListResult {
8581 bool IsInvalid = false;
8582 llvm::SmallVector<Stmt*, 16> Stmts;
8583
8584 bool add(const StmtResult &S) {
8585 IsInvalid |= S.isInvalid();
8586 if (IsInvalid)
8587 return true;
8588 Stmts.push_back(Elt: S.get());
8589 return false;
8590 }
8591};
8592
8593/// A visitor over the notional body of a defaulted comparison that synthesizes
8594/// the actual body.
8595class DefaultedComparisonSynthesizer
8596 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8597 StmtListResult, StmtResult,
8598 std::pair<ExprResult, ExprResult>> {
8599 SourceLocation Loc;
8600 unsigned ArrayDepth = 0;
8601
8602public:
8603 using Base = DefaultedComparisonVisitor;
8604 using ExprPair = std::pair<ExprResult, ExprResult>;
8605
8606 friend Base;
8607
8608 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8609 DefaultedComparisonKind DCK,
8610 SourceLocation BodyLoc)
8611 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8612
8613 /// Build a suitable function body for this defaulted comparison operator.
8614 StmtResult build() {
8615 Sema::CompoundScopeRAII CompoundScope(S);
8616
8617 StmtListResult Stmts = visit();
8618 if (Stmts.IsInvalid)
8619 return StmtError();
8620
8621 ExprResult RetVal;
8622 switch (DCK) {
8623 case DefaultedComparisonKind::None:
8624 llvm_unreachable("not a defaulted comparison");
8625
8626 case DefaultedComparisonKind::Equal: {
8627 // C++2a [class.eq]p3:
8628 // [...] compar[e] the corresponding elements [...] until the first
8629 // index i where xi == yi yields [...] false. If no such index exists,
8630 // V is true. Otherwise, V is false.
8631 //
8632 // Join the comparisons with '&&'s and return the result. Use a right
8633 // fold (traversing the conditions right-to-left), because that
8634 // short-circuits more naturally.
8635 auto OldStmts = std::move(Stmts.Stmts);
8636 Stmts.Stmts.clear();
8637 ExprResult CmpSoFar;
8638 // Finish a particular comparison chain.
8639 auto FinishCmp = [&] {
8640 if (Expr *Prior = CmpSoFar.get()) {
8641 // Convert the last expression to 'return ...;'
8642 if (RetVal.isUnset() && Stmts.Stmts.empty())
8643 RetVal = CmpSoFar;
8644 // Convert any prior comparison to 'if (!(...)) return false;'
8645 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8646 return true;
8647 CmpSoFar = ExprResult();
8648 }
8649 return false;
8650 };
8651 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8652 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8653 if (!E) {
8654 // Found an array comparison.
8655 if (FinishCmp() || Stmts.add(S: EAsStmt))
8656 return StmtError();
8657 continue;
8658 }
8659
8660 if (CmpSoFar.isUnset()) {
8661 CmpSoFar = E;
8662 continue;
8663 }
8664 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8665 if (CmpSoFar.isInvalid())
8666 return StmtError();
8667 }
8668 if (FinishCmp())
8669 return StmtError();
8670 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8671 // If no such index exists, V is true.
8672 if (RetVal.isUnset())
8673 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8674 break;
8675 }
8676
8677 case DefaultedComparisonKind::ThreeWay: {
8678 // Per C++2a [class.spaceship]p3, as a fallback add:
8679 // return static_cast<R>(std::strong_ordering::equal);
8680 QualType StrongOrdering = S.CheckComparisonCategoryType(
8681 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8682 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8683 if (StrongOrdering.isNull())
8684 return StmtError();
8685 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8686 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8687 ->VD;
8688 RetVal = getDecl(VD: EqualVD);
8689 if (RetVal.isInvalid())
8690 return StmtError();
8691 RetVal = buildStaticCastToR(E: RetVal.get());
8692 break;
8693 }
8694
8695 case DefaultedComparisonKind::NotEqual:
8696 case DefaultedComparisonKind::Relational:
8697 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8698 break;
8699 }
8700
8701 // Build the final return statement.
8702 if (RetVal.isInvalid())
8703 return StmtError();
8704 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8705 if (ReturnStmt.isInvalid())
8706 return StmtError();
8707 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8708
8709 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8710 }
8711
8712private:
8713 ExprResult getDecl(ValueDecl *VD) {
8714 return S.BuildDeclarationNameExpr(
8715 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8716 }
8717
8718 ExprResult getParam(unsigned I) {
8719 ParmVarDecl *PD = FD->getParamDecl(i: I);
8720 return getDecl(VD: PD);
8721 }
8722
8723 ExprPair getCompleteObject() {
8724 unsigned Param = 0;
8725 ExprResult LHS;
8726 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8727 MD && MD->isImplicitObjectMemberFunction()) {
8728 // LHS is '*this'.
8729 LHS = S.ActOnCXXThis(Loc);
8730 if (!LHS.isInvalid())
8731 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8732 } else {
8733 LHS = getParam(I: Param++);
8734 }
8735 ExprResult RHS = getParam(I: Param++);
8736 assert(Param == FD->getNumParams());
8737 return {LHS, RHS};
8738 }
8739
8740 ExprPair getBase(CXXBaseSpecifier *Base) {
8741 ExprPair Obj = getCompleteObject();
8742 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8743 return {ExprError(), ExprError()};
8744 CXXCastPath Path = {Base};
8745 const auto CastToBase = [&](Expr *E) {
8746 QualType ToType = S.Context.getQualifiedType(
8747 T: Base->getType(), Qs: E->getType().getQualifiers());
8748 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8749 };
8750 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8751 }
8752
8753 ExprPair getField(FieldDecl *Field) {
8754 ExprPair Obj = getCompleteObject();
8755 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8756 return {ExprError(), ExprError()};
8757
8758 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8759 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8760 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8761 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8762 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8763 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8764 }
8765
8766 // FIXME: When expanding a subobject, register a note in the code synthesis
8767 // stack to say which subobject we're comparing.
8768
8769 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8770 if (Cond.isInvalid())
8771 return StmtError();
8772
8773 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8774 if (NotCond.isInvalid())
8775 return StmtError();
8776
8777 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8778 assert(!False.isInvalid() && "should never fail");
8779 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8780 if (ReturnFalse.isInvalid())
8781 return StmtError();
8782
8783 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8784 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8785 CK: Sema::ConditionKind::Boolean),
8786 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8787 }
8788
8789 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8790 ExprPair Subobj) {
8791 QualType SizeType = S.Context.getSizeType();
8792 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8793
8794 // Build 'size_t i$n = 0'.
8795 IdentifierInfo *IterationVarName = nullptr;
8796 {
8797 SmallString<8> Str;
8798 llvm::raw_svector_ostream OS(Str);
8799 OS << "i" << ArrayDepth;
8800 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8801 }
8802 VarDecl *IterationVar = VarDecl::Create(
8803 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8804 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8805 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8806 IterationVar->setInit(
8807 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8808 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8809
8810 auto IterRef = [&] {
8811 ExprResult Ref = S.BuildDeclarationNameExpr(
8812 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8813 D: IterationVar);
8814 assert(!Ref.isInvalid() && "can't reference our own variable?");
8815 return Ref.get();
8816 };
8817
8818 // Build 'i$n != Size'.
8819 ExprResult Cond = S.CreateBuiltinBinOp(
8820 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8821 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8822 assert(!Cond.isInvalid() && "should never fail");
8823
8824 // Build '++i$n'.
8825 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8826 assert(!Inc.isInvalid() && "should never fail");
8827
8828 // Build 'a[i$n]' and 'b[i$n]'.
8829 auto Index = [&](ExprResult E) {
8830 if (E.isInvalid())
8831 return ExprError();
8832 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8833 };
8834 Subobj.first = Index(Subobj.first);
8835 Subobj.second = Index(Subobj.second);
8836
8837 // Compare the array elements.
8838 ++ArrayDepth;
8839 StmtResult Substmt = visitSubobject(Type, Subobj);
8840 --ArrayDepth;
8841
8842 if (Substmt.isInvalid())
8843 return StmtError();
8844
8845 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8846 // For outer levels or for an 'operator<=>' we already have a suitable
8847 // statement that returns as necessary.
8848 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8849 assert(DCK == DefaultedComparisonKind::Equal &&
8850 "should have non-expression statement");
8851 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8852 if (Substmt.isInvalid())
8853 return StmtError();
8854 }
8855
8856 // Build 'for (...) ...'
8857 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8858 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8859 CK: Sema::ConditionKind::Boolean),
8860 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8861 Body: Substmt.get());
8862 }
8863
8864 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8865 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8866 return StmtError();
8867
8868 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8869 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8870 ExprResult Op;
8871 if (Type->isOverloadableType())
8872 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8873 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8874 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8875 else
8876 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8877 if (Op.isInvalid())
8878 return StmtError();
8879
8880 switch (DCK) {
8881 case DefaultedComparisonKind::None:
8882 llvm_unreachable("not a defaulted comparison");
8883
8884 case DefaultedComparisonKind::Equal:
8885 // Per C++2a [class.eq]p2, each comparison is individually contextually
8886 // converted to bool.
8887 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8888 if (Op.isInvalid())
8889 return StmtError();
8890 return Op.get();
8891
8892 case DefaultedComparisonKind::ThreeWay: {
8893 // Per C++2a [class.spaceship]p3, form:
8894 // if (R cmp = static_cast<R>(op); cmp != 0)
8895 // return cmp;
8896 QualType R = FD->getReturnType();
8897 Op = buildStaticCastToR(E: Op.get());
8898 if (Op.isInvalid())
8899 return StmtError();
8900
8901 // R cmp = ...;
8902 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8903 VarDecl *VD =
8904 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8905 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8906 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8907 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8908
8909 // cmp != 0
8910 ExprResult VDRef = getDecl(VD);
8911 if (VDRef.isInvalid())
8912 return StmtError();
8913 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8914 Expr *Zero =
8915 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8916 ExprResult Comp;
8917 if (VDRef.get()->getType()->isOverloadableType())
8918 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8919 AllowRewrittenCandidates: true, DefaultedFn: FD);
8920 else
8921 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8922 if (Comp.isInvalid())
8923 return StmtError();
8924 Sema::ConditionResult Cond = S.ActOnCondition(
8925 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8926 if (Cond.isInvalid())
8927 return StmtError();
8928
8929 // return cmp;
8930 VDRef = getDecl(VD);
8931 if (VDRef.isInvalid())
8932 return StmtError();
8933 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8934 if (ReturnStmt.isInvalid())
8935 return StmtError();
8936
8937 // if (...)
8938 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8939 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8940 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8941 }
8942
8943 case DefaultedComparisonKind::NotEqual:
8944 case DefaultedComparisonKind::Relational:
8945 // C++2a [class.compare.secondary]p2:
8946 // Otherwise, the operator function yields x @ y.
8947 return Op.get();
8948 }
8949 llvm_unreachable("");
8950 }
8951
8952 /// Build "static_cast<R>(E)".
8953 ExprResult buildStaticCastToR(Expr *E) {
8954 QualType R = FD->getReturnType();
8955 assert(!R->isUndeducedType() && "type should have been deduced already");
8956
8957 // Don't bother forming a no-op cast in the common case.
8958 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8959 return E;
8960 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8961 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8962 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8963 }
8964};
8965}
8966
8967/// Perform the unqualified lookups that might be needed to form a defaulted
8968/// comparison function for the given operator.
8969static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8970 UnresolvedSetImpl &Operators,
8971 OverloadedOperatorKind Op) {
8972 auto Lookup = [&](OverloadedOperatorKind OO) {
8973 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
8974 };
8975
8976 // Every defaulted operator looks up itself.
8977 Lookup(Op);
8978 // ... and the rewritten form of itself, if any.
8979 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
8980 Lookup(ExtraOp);
8981
8982 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
8983 // synthesize a three-way comparison from '<' and '=='. In a dependent
8984 // context, we also need to look up '==' in case we implicitly declare a
8985 // defaulted 'operator=='.
8986 if (Op == OO_Spaceship) {
8987 Lookup(OO_ExclaimEqual);
8988 Lookup(OO_Less);
8989 Lookup(OO_EqualEqual);
8990 }
8991}
8992
8993bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
8994 DefaultedComparisonKind DCK) {
8995 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
8996
8997 // Perform any unqualified lookups we're going to need to default this
8998 // function.
8999 if (S) {
9000 UnresolvedSet<32> Operators;
9001 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9002 Op: FD->getOverloadedOperator());
9003 FD->setDefaultedOrDeletedInfo(
9004 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9005 Context, Lookups: Operators.pairs()));
9006 }
9007
9008 // C++2a [class.compare.default]p1:
9009 // A defaulted comparison operator function for some class C shall be a
9010 // non-template function declared in the member-specification of C that is
9011 // -- a non-static const non-volatile member of C having one parameter of
9012 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9013 // -- a friend of C having two parameters of type const C& or two
9014 // parameters of type C.
9015
9016 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9017 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9018 if (IsMethod) {
9019 auto *MD = cast<CXXMethodDecl>(Val: FD);
9020 assert(!MD->isStatic() && "comparison function cannot be a static member");
9021
9022 if (MD->getRefQualifier() == RQ_RValue) {
9023 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9024
9025 // Remove the ref qualifier to recover.
9026 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9027 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9028 EPI.RefQualifier = RQ_None;
9029 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9030 Args: FPT->getParamTypes(), EPI));
9031 }
9032
9033 // If we're out-of-class, this is the class we're comparing.
9034 if (!RD)
9035 RD = MD->getParent();
9036 QualType T = MD->getFunctionObjectParameterReferenceType();
9037 if (!T.getNonReferenceType().isConstQualified() &&
9038 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9039 SourceLocation Loc, InsertLoc;
9040 if (MD->isExplicitObjectMemberFunction()) {
9041 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9042 InsertLoc = getLocForEndOfToken(
9043 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9044 } else {
9045 Loc = MD->getLocation();
9046 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9047 InsertLoc = Loc.getRParenLoc();
9048 }
9049 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9050 // corresponding defaulted 'operator<=>' already.
9051 if (!MD->isImplicit()) {
9052 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9053 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9054 }
9055
9056 // Add the 'const' to the type to recover.
9057 if (MD->isExplicitObjectMemberFunction()) {
9058 assert(T->isLValueReferenceType());
9059 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9060 T: T.getNonReferenceType().withConst()));
9061 } else {
9062 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9063 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9064 EPI.TypeQuals.addConst();
9065 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9066 Args: FPT->getParamTypes(), EPI));
9067 }
9068 }
9069
9070 if (MD->isVolatile()) {
9071 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9072
9073 // Remove the 'volatile' from the type to recover.
9074 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9075 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9076 EPI.TypeQuals.removeVolatile();
9077 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9078 Args: FPT->getParamTypes(), EPI));
9079 }
9080 }
9081
9082 if ((FD->getNumParams() -
9083 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9084 (IsMethod ? 1 : 2)) {
9085 // Let's not worry about using a variadic template pack here -- who would do
9086 // such a thing?
9087 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9088 << int(IsMethod) << int(DCK);
9089 return true;
9090 }
9091
9092 const ParmVarDecl *KnownParm = nullptr;
9093 for (const ParmVarDecl *Param : FD->parameters()) {
9094 QualType ParmTy = Param->getType();
9095 if (!KnownParm) {
9096 auto CTy = ParmTy;
9097 // Is it `T const &`?
9098 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9099 QualType ExpectedTy;
9100 if (RD)
9101 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9102 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9103 CTy = Ref->getPointeeType();
9104 if (RD)
9105 ExpectedTy.addConst();
9106 Ok = true;
9107 }
9108
9109 // Is T a class?
9110 if (RD) {
9111 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9112 } else {
9113 RD = CTy->getAsCXXRecordDecl();
9114 Ok &= RD != nullptr;
9115 }
9116
9117 if (Ok) {
9118 KnownParm = Param;
9119 } else {
9120 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9121 // corresponding defaulted 'operator<=>' already.
9122 if (!FD->isImplicit()) {
9123 if (RD) {
9124 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9125 QualType RefTy =
9126 Context.getLValueReferenceType(T: PlainTy.withConst());
9127 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9128 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9129 << Param->getSourceRange();
9130 } else {
9131 assert(!IsMethod && "should know expected type for method");
9132 Diag(Loc: FD->getLocation(),
9133 DiagID: diag::err_defaulted_comparison_param_unknown)
9134 << int(DCK) << ParmTy << Param->getSourceRange();
9135 }
9136 }
9137 return true;
9138 }
9139 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9140 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9141 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9142 << ParmTy << Param->getSourceRange();
9143 return true;
9144 }
9145 }
9146
9147 assert(RD && "must have determined class");
9148 if (IsMethod) {
9149 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9150 // In-class, must be a friend decl.
9151 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9152 } else {
9153 // Out of class, require the defaulted comparison to be a friend (of a
9154 // complete type, per CWG2547).
9155 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9156 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9157 Args: int(1)))
9158 return true;
9159
9160 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9161 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9162 })) {
9163 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9164 << int(DCK) << int(0) << RD;
9165 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9166 return true;
9167 }
9168 }
9169
9170 // C++2a [class.eq]p1, [class.rel]p1:
9171 // A [defaulted comparison other than <=>] shall have a declared return
9172 // type bool.
9173 if (DCK != DefaultedComparisonKind::ThreeWay &&
9174 !FD->getDeclaredReturnType()->isDependentType() &&
9175 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9176 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9177 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9178 << FD->getReturnTypeSourceRange();
9179 return true;
9180 }
9181 // C++2a [class.spaceship]p2 [P2002R0]:
9182 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9183 // R shall not contain a placeholder type.
9184 if (QualType RT = FD->getDeclaredReturnType();
9185 DCK == DefaultedComparisonKind::ThreeWay &&
9186 RT->getContainedDeducedType() &&
9187 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9188 RT->getContainedAutoType()->isConstrained())) {
9189 Diag(Loc: FD->getLocation(),
9190 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9191 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9192 << FD->getReturnTypeSourceRange();
9193 return true;
9194 }
9195
9196 // For a defaulted function in a dependent class, defer all remaining checks
9197 // until instantiation.
9198 if (RD->isDependentType())
9199 return false;
9200
9201 // Determine whether the function should be defined as deleted.
9202 DefaultedComparisonInfo Info =
9203 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9204
9205 bool First = FD == FD->getCanonicalDecl();
9206
9207 if (!First) {
9208 if (Info.Deleted) {
9209 // C++11 [dcl.fct.def.default]p4:
9210 // [For a] user-provided explicitly-defaulted function [...] if such a
9211 // function is implicitly defined as deleted, the program is ill-formed.
9212 //
9213 // This is really just a consequence of the general rule that you can
9214 // only delete a function on its first declaration.
9215 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9216 << FD->isImplicit() << (int)DCK;
9217 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9218 DefaultedComparisonAnalyzer::ExplainDeleted)
9219 .visit();
9220 return true;
9221 }
9222 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9223 // C++20 [class.compare.default]p1:
9224 // [...] A definition of a comparison operator as defaulted that appears
9225 // in a class shall be the first declaration of that function.
9226 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9227 << (int)DCK;
9228 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9229 DiagID: diag::note_previous_declaration);
9230 return true;
9231 }
9232 }
9233
9234 // If we want to delete the function, then do so; there's nothing else to
9235 // check in that case.
9236 if (Info.Deleted) {
9237 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9238 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9239 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9240 << (int)DCK;
9241 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9242 DefaultedComparisonAnalyzer::ExplainDeleted)
9243 .visit();
9244 if (FD->getDefaultLoc().isValid())
9245 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9246 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9247 }
9248 return false;
9249 }
9250
9251 // C++2a [class.spaceship]p2:
9252 // The return type is deduced as the common comparison type of R0, R1, ...
9253 if (DCK == DefaultedComparisonKind::ThreeWay &&
9254 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9255 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9256 if (RetLoc.isInvalid())
9257 RetLoc = FD->getBeginLoc();
9258 // FIXME: Should we really care whether we have the complete type and the
9259 // 'enumerator' constants here? A forward declaration seems sufficient.
9260 QualType Cat = CheckComparisonCategoryType(
9261 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9262 if (Cat.isNull())
9263 return true;
9264 Context.adjustDeducedFunctionResultType(
9265 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9266 }
9267
9268 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9269 // An explicitly-defaulted function that is not defined as deleted may be
9270 // declared constexpr or consteval only if it is constexpr-compatible.
9271 // C++2a [class.compare.default]p3 [P2002R0]:
9272 // A defaulted comparison function is constexpr-compatible if it satisfies
9273 // the requirements for a constexpr function [...]
9274 // The only relevant requirements are that the parameter and return types are
9275 // literal types. The remaining conditions are checked by the analyzer.
9276 //
9277 // We support P2448R2 in language modes earlier than C++23 as an extension.
9278 // The concept of constexpr-compatible was removed.
9279 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9280 // A function explicitly defaulted on its first declaration is implicitly
9281 // inline, and is implicitly constexpr if it is constexpr-suitable.
9282 // C++23 [dcl.constexpr]p3
9283 // A function is constexpr-suitable if
9284 // - it is not a coroutine, and
9285 // - if the function is a constructor or destructor, its class does not
9286 // have any virtual base classes.
9287 if (FD->isConstexpr()) {
9288 if (!getLangOpts().CPlusPlus23 &&
9289 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9290 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9291 !Info.Constexpr) {
9292 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9293 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9294 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9295 DefaultedComparisonAnalyzer::ExplainConstexpr)
9296 .visit();
9297 }
9298 }
9299
9300 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9301 // If a constexpr-compatible function is explicitly defaulted on its first
9302 // declaration, it is implicitly considered to be constexpr.
9303 // FIXME: Only applying this to the first declaration seems problematic, as
9304 // simple reorderings can affect the meaning of the program.
9305 if (First && !FD->isConstexpr() && Info.Constexpr)
9306 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9307
9308 // C++2a [except.spec]p3:
9309 // If a declaration of a function does not have a noexcept-specifier
9310 // [and] is defaulted on its first declaration, [...] the exception
9311 // specification is as specified below
9312 if (FD->getExceptionSpecType() == EST_None) {
9313 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9314 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9315 EPI.ExceptionSpec.Type = EST_Unevaluated;
9316 EPI.ExceptionSpec.SourceDecl = FD;
9317 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9318 Args: FPT->getParamTypes(), EPI));
9319 }
9320
9321 return false;
9322}
9323
9324void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9325 FunctionDecl *Spaceship) {
9326 Sema::CodeSynthesisContext Ctx;
9327 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9328 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9329 Ctx.Entity = Spaceship;
9330 pushCodeSynthesisContext(Ctx);
9331
9332 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9333 EqualEqual->setImplicit();
9334
9335 popCodeSynthesisContext();
9336}
9337
9338void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9339 DefaultedComparisonKind DCK) {
9340 assert(FD->isDefaulted() && !FD->isDeleted() &&
9341 !FD->doesThisDeclarationHaveABody());
9342 if (FD->willHaveBody() || FD->isInvalidDecl())
9343 return;
9344
9345 SynthesizedFunctionScope Scope(*this, FD);
9346
9347 // Add a context note for diagnostics produced after this point.
9348 Scope.addContextNote(UseLoc);
9349
9350 {
9351 // Build and set up the function body.
9352 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9353 // the type of the class being compared.
9354 auto PT = FD->getParamDecl(i: 0)->getType();
9355 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9356 SourceLocation BodyLoc =
9357 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9358 StmtResult Body =
9359 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9360 if (Body.isInvalid()) {
9361 FD->setInvalidDecl();
9362 return;
9363 }
9364 FD->setBody(Body.get());
9365 FD->markUsed(C&: Context);
9366 }
9367
9368 // The exception specification is needed because we are defining the
9369 // function. Note that this will reuse the body we just built.
9370 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9371
9372 if (ASTMutationListener *L = getASTMutationListener())
9373 L->CompletedImplicitDefinition(D: FD);
9374}
9375
9376static Sema::ImplicitExceptionSpecification
9377ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9378 FunctionDecl *FD,
9379 Sema::DefaultedComparisonKind DCK) {
9380 ComputingExceptionSpec CES(S, FD, Loc);
9381 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9382
9383 if (FD->isInvalidDecl())
9384 return ExceptSpec;
9385
9386 // The common case is that we just defined the comparison function. In that
9387 // case, just look at whether the body can throw.
9388 if (FD->hasBody()) {
9389 ExceptSpec.CalledStmt(S: FD->getBody());
9390 } else {
9391 // Otherwise, build a body so we can check it. This should ideally only
9392 // happen when we're not actually marking the function referenced. (This is
9393 // only really important for efficiency: we don't want to build and throw
9394 // away bodies for comparison functions more than we strictly need to.)
9395
9396 // Pretend to synthesize the function body in an unevaluated context.
9397 // Note that we can't actually just go ahead and define the function here:
9398 // we are not permitted to mark its callees as referenced.
9399 Sema::SynthesizedFunctionScope Scope(S, FD);
9400 EnterExpressionEvaluationContext Context(
9401 S, Sema::ExpressionEvaluationContext::Unevaluated);
9402
9403 CXXRecordDecl *RD =
9404 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9405 ? FD->getDeclContext()
9406 : FD->getLexicalDeclContext());
9407 SourceLocation BodyLoc =
9408 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9409 StmtResult Body =
9410 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9411 if (!Body.isInvalid())
9412 ExceptSpec.CalledStmt(S: Body.get());
9413
9414 // FIXME: Can we hold onto this body and just transform it to potentially
9415 // evaluated when we're asked to define the function rather than rebuilding
9416 // it? Either that, or we should only build the bits of the body that we
9417 // need (the expressions, not the statements).
9418 }
9419
9420 return ExceptSpec;
9421}
9422
9423void Sema::CheckDelayedMemberExceptionSpecs() {
9424 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9425 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9426
9427 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9428 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9429
9430 // Perform any deferred checking of exception specifications for virtual
9431 // destructors.
9432 for (auto &Check : Overriding)
9433 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9434
9435 // Perform any deferred checking of exception specifications for befriended
9436 // special members.
9437 for (auto &Check : Equivalent)
9438 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9439}
9440
9441namespace {
9442/// CRTP base class for visiting operations performed by a special member
9443/// function (or inherited constructor).
9444template<typename Derived>
9445struct SpecialMemberVisitor {
9446 Sema &S;
9447 CXXMethodDecl *MD;
9448 CXXSpecialMemberKind CSM;
9449 Sema::InheritedConstructorInfo *ICI;
9450
9451 // Properties of the special member, computed for convenience.
9452 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9453
9454 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9455 Sema::InheritedConstructorInfo *ICI)
9456 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9457 switch (CSM) {
9458 case CXXSpecialMemberKind::DefaultConstructor:
9459 case CXXSpecialMemberKind::CopyConstructor:
9460 case CXXSpecialMemberKind::MoveConstructor:
9461 IsConstructor = true;
9462 break;
9463 case CXXSpecialMemberKind::CopyAssignment:
9464 case CXXSpecialMemberKind::MoveAssignment:
9465 IsAssignment = true;
9466 break;
9467 case CXXSpecialMemberKind::Destructor:
9468 break;
9469 case CXXSpecialMemberKind::Invalid:
9470 llvm_unreachable("invalid special member kind");
9471 }
9472
9473 if (MD->getNumExplicitParams()) {
9474 if (const ReferenceType *RT =
9475 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9476 ConstArg = RT->getPointeeType().isConstQualified();
9477 }
9478 }
9479
9480 Derived &getDerived() { return static_cast<Derived&>(*this); }
9481
9482 /// Is this a "move" special member?
9483 bool isMove() const {
9484 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9485 CSM == CXXSpecialMemberKind::MoveAssignment;
9486 }
9487
9488 /// Look up the corresponding special member in the given class.
9489 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9490 unsigned Quals, bool IsMutable) {
9491 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9492 ConstRHS: ConstArg && !IsMutable);
9493 }
9494
9495 /// Look up the constructor for the specified base class to see if it's
9496 /// overridden due to this being an inherited constructor.
9497 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9498 if (!ICI)
9499 return {};
9500 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9501 auto *BaseCtor =
9502 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9503 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9504 return MD;
9505 return {};
9506 }
9507
9508 /// A base or member subobject.
9509 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9510
9511 /// Get the location to use for a subobject in diagnostics.
9512 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9513 // FIXME: For an indirect virtual base, the direct base leading to
9514 // the indirect virtual base would be a more useful choice.
9515 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9516 return B->getBaseTypeLoc();
9517 else
9518 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9519 }
9520
9521 enum BasesToVisit {
9522 /// Visit all non-virtual (direct) bases.
9523 VisitNonVirtualBases,
9524 /// Visit all direct bases, virtual or not.
9525 VisitDirectBases,
9526 /// Visit all non-virtual bases, and all virtual bases if the class
9527 /// is not abstract.
9528 VisitPotentiallyConstructedBases,
9529 /// Visit all direct or virtual bases.
9530 VisitAllBases
9531 };
9532
9533 // Visit the bases and members of the class.
9534 bool visit(BasesToVisit Bases) {
9535 CXXRecordDecl *RD = MD->getParent();
9536
9537 if (Bases == VisitPotentiallyConstructedBases)
9538 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9539
9540 for (auto &B : RD->bases())
9541 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9542 getDerived().visitBase(&B))
9543 return true;
9544
9545 if (Bases == VisitAllBases)
9546 for (auto &B : RD->vbases())
9547 if (getDerived().visitBase(&B))
9548 return true;
9549
9550 for (auto *F : RD->fields())
9551 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9552 getDerived().visitField(F))
9553 return true;
9554
9555 return false;
9556 }
9557};
9558}
9559
9560namespace {
9561struct SpecialMemberDeletionInfo
9562 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9563 bool Diagnose;
9564
9565 SourceLocation Loc;
9566
9567 bool AllFieldsAreConst;
9568
9569 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9570 CXXSpecialMemberKind CSM,
9571 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9572 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9573 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9574
9575 bool inUnion() const { return MD->getParent()->isUnion(); }
9576
9577 CXXSpecialMemberKind getEffectiveCSM() {
9578 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9579 }
9580
9581 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9582
9583 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9584
9585 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9586 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9587
9588 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9589 bool shouldDeleteForField(FieldDecl *FD);
9590 bool shouldDeleteForAllConstMembers();
9591
9592 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9593 unsigned Quals);
9594 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9595 Sema::SpecialMemberOverloadResult SMOR,
9596 bool IsDtorCallInCtor);
9597
9598 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9599};
9600}
9601
9602/// Is the given special member inaccessible when used on the given
9603/// sub-object.
9604bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9605 CXXMethodDecl *target) {
9606 /// If we're operating on a base class, the object type is the
9607 /// type of this special member.
9608 CanQualType objectTy;
9609 AccessSpecifier access = target->getAccess();
9610 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9611 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9612 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9613
9614 // If we're operating on a field, the object type is the type of the field.
9615 } else {
9616 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9617 }
9618
9619 return S.isMemberAccessibleForDeletion(
9620 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9621}
9622
9623/// Check whether we should delete a special member due to the implicit
9624/// definition containing a call to a special member of a subobject.
9625bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9626 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9627 bool IsDtorCallInCtor) {
9628 CXXMethodDecl *Decl = SMOR.getMethod();
9629 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9630
9631 enum {
9632 NotSet = -1,
9633 NoDecl,
9634 DeletedDecl,
9635 MultipleDecl,
9636 InaccessibleDecl,
9637 NonTrivialDecl
9638 } DiagKind = NotSet;
9639
9640 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9641 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9642 Field->getParent()->isUnion()) {
9643 // [class.default.ctor]p2:
9644 // A defaulted default constructor for class X is defined as deleted if
9645 // - X is a union that has a variant member with a non-trivial default
9646 // constructor and no variant member of X has a default member
9647 // initializer
9648 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9649 if (RD->hasInClassInitializer())
9650 return false;
9651 }
9652 DiagKind = !Decl ? NoDecl : DeletedDecl;
9653 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9654 DiagKind = MultipleDecl;
9655 else if (!isAccessible(Subobj, target: Decl))
9656 DiagKind = InaccessibleDecl;
9657 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9658 !Decl->isTrivial()) {
9659 // A member of a union must have a trivial corresponding special member.
9660 // As a weird special case, a destructor call from a union's constructor
9661 // must be accessible and non-deleted, but need not be trivial. Such a
9662 // destructor is never actually called, but is semantically checked as
9663 // if it were.
9664 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9665 // [class.default.ctor]p2:
9666 // A defaulted default constructor for class X is defined as deleted if
9667 // - X is a union that has a variant member with a non-trivial default
9668 // constructor and no variant member of X has a default member
9669 // initializer
9670 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9671 if (!RD->hasInClassInitializer())
9672 DiagKind = NonTrivialDecl;
9673 } else {
9674 DiagKind = NonTrivialDecl;
9675 }
9676 }
9677
9678 if (DiagKind == NotSet)
9679 return false;
9680
9681 if (Diagnose) {
9682 if (Field) {
9683 S.Diag(Loc: Field->getLocation(),
9684 DiagID: diag::note_deleted_special_member_class_subobject)
9685 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9686 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9687 } else {
9688 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9689 S.Diag(Loc: Base->getBeginLoc(),
9690 DiagID: diag::note_deleted_special_member_class_subobject)
9691 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9692 << Base->getType() << DiagKind << IsDtorCallInCtor
9693 << /*IsObjCPtr*/ false;
9694 }
9695
9696 if (DiagKind == DeletedDecl)
9697 S.NoteDeletedFunction(FD: Decl);
9698 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9699 }
9700
9701 return true;
9702}
9703
9704/// Check whether we should delete a special member function due to having a
9705/// direct or virtual base class or non-static data member of class type M.
9706bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9707 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9708 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9709 bool IsMutable = Field && Field->isMutable();
9710
9711 // C++11 [class.ctor]p5:
9712 // -- any direct or virtual base class, or non-static data member with no
9713 // brace-or-equal-initializer, has class type M (or array thereof) and
9714 // either M has no default constructor or overload resolution as applied
9715 // to M's default constructor results in an ambiguity or in a function
9716 // that is deleted or inaccessible
9717 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9718 // -- a direct or virtual base class B that cannot be copied/moved because
9719 // overload resolution, as applied to B's corresponding special member,
9720 // results in an ambiguity or a function that is deleted or inaccessible
9721 // from the defaulted special member
9722 // C++11 [class.dtor]p5:
9723 // -- any direct or virtual base class [...] has a type with a destructor
9724 // that is deleted or inaccessible
9725 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9726 Field->hasInClassInitializer()) &&
9727 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9728 IsDtorCallInCtor: false))
9729 return true;
9730
9731 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9732 // -- any direct or virtual base class or non-static data member has a
9733 // type with a destructor that is deleted or inaccessible
9734 if (IsConstructor) {
9735 Sema::SpecialMemberOverloadResult SMOR =
9736 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9737 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9738 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9739 return true;
9740 }
9741
9742 return false;
9743}
9744
9745bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9746 FieldDecl *FD, QualType FieldType) {
9747 // The defaulted special functions are defined as deleted if this is a variant
9748 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9749 // type under ARC.
9750 if (!FieldType.hasNonTrivialObjCLifetime())
9751 return false;
9752
9753 // Don't make the defaulted default constructor defined as deleted if the
9754 // member has an in-class initializer.
9755 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9756 FD->hasInClassInitializer())
9757 return false;
9758
9759 if (Diagnose) {
9760 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9761 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9762 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9763 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9764 }
9765
9766 return true;
9767}
9768
9769bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9770 const FieldDecl *FD) {
9771 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9772 // Copy/move constructors/assignment operators are deleted if the field has an
9773 // address-discriminated ptrauth qualifier.
9774 PointerAuthQualifier Q = FieldType.getPointerAuth();
9775
9776 if (!Q || !Q.isAddressDiscriminated())
9777 return false;
9778
9779 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9780 CSM == CXXSpecialMemberKind::Destructor)
9781 return false;
9782
9783 if (Diagnose) {
9784 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9785 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9786 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9787 << /*IsDtorCallInCtor*/ false << 2;
9788 }
9789
9790 return true;
9791}
9792
9793/// Check whether we should delete a special member function due to the class
9794/// having a particular direct or virtual base class.
9795bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9796 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9797 // If program is correct, BaseClass cannot be null, but if it is, the error
9798 // must be reported elsewhere.
9799 if (!BaseClass)
9800 return false;
9801 // If we have an inheriting constructor, check whether we're calling an
9802 // inherited constructor instead of a default constructor.
9803 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9804 if (auto *BaseCtor = SMOR.getMethod()) {
9805 // Note that we do not check access along this path; other than that,
9806 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9807 // FIXME: Check that the base has a usable destructor! Sink this into
9808 // shouldDeleteForClassSubobject.
9809 if (BaseCtor->isDeleted() && Diagnose) {
9810 S.Diag(Loc: Base->getBeginLoc(),
9811 DiagID: diag::note_deleted_special_member_class_subobject)
9812 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9813 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9814 << /*IsObjCPtr*/ false;
9815 S.NoteDeletedFunction(FD: BaseCtor);
9816 }
9817 return BaseCtor->isDeleted();
9818 }
9819 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9820}
9821
9822/// Check whether we should delete a special member function due to the class
9823/// having a particular non-static data member.
9824bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9825 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9826 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9827
9828 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9829 return true;
9830
9831 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9832 return true;
9833
9834 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9835 // For a default constructor, all references must be initialized in-class
9836 // and, if a union, it must have a non-const member.
9837 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9838 if (Diagnose)
9839 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9840 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9841 return true;
9842 }
9843 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9844 // data member of const-qualified type (or array thereof) with no
9845 // brace-or-equal-initializer is not const-default-constructible.
9846 if (!inUnion() && FieldType.isConstQualified() &&
9847 !FD->hasInClassInitializer() &&
9848 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9849 if (Diagnose)
9850 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9851 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9852 return true;
9853 }
9854
9855 if (inUnion() && !FieldType.isConstQualified())
9856 AllFieldsAreConst = false;
9857 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9858 // For a copy constructor, data members must not be of rvalue reference
9859 // type.
9860 if (FieldType->isRValueReferenceType()) {
9861 if (Diagnose)
9862 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9863 << MD->getParent() << FD << FieldType;
9864 return true;
9865 }
9866 } else if (IsAssignment) {
9867 // For an assignment operator, data members must not be of reference type.
9868 if (FieldType->isReferenceType()) {
9869 if (Diagnose)
9870 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9871 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9872 return true;
9873 }
9874 if (!FieldRecord && FieldType.isConstQualified()) {
9875 // C++11 [class.copy]p23:
9876 // -- a non-static data member of const non-class type (or array thereof)
9877 if (Diagnose)
9878 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9879 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9880 return true;
9881 }
9882 }
9883
9884 if (FieldRecord) {
9885 // Some additional restrictions exist on the variant members.
9886 if (!inUnion() && FieldRecord->isUnion() &&
9887 FieldRecord->isAnonymousStructOrUnion()) {
9888 bool AllVariantFieldsAreConst = true;
9889
9890 // FIXME: Handle anonymous unions declared within anonymous unions.
9891 for (auto *UI : FieldRecord->fields()) {
9892 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9893
9894 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9895 return true;
9896
9897 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9898 return true;
9899
9900 if (!UnionFieldType.isConstQualified())
9901 AllVariantFieldsAreConst = false;
9902
9903 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9904 if (UnionFieldRecord &&
9905 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9906 Quals: UnionFieldType.getCVRQualifiers()))
9907 return true;
9908 }
9909
9910 // At least one member in each anonymous union must be non-const
9911 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9912 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9913 if (Diagnose)
9914 S.Diag(Loc: FieldRecord->getLocation(),
9915 DiagID: diag::note_deleted_default_ctor_all_const)
9916 << !!ICI << MD->getParent() << /*anonymous union*/1;
9917 return true;
9918 }
9919
9920 // Don't check the implicit member of the anonymous union type.
9921 // This is technically non-conformant but supported, and we have a
9922 // diagnostic for this elsewhere.
9923 return false;
9924 }
9925
9926 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9927 Quals: FieldType.getCVRQualifiers()))
9928 return true;
9929 }
9930
9931 return false;
9932}
9933
9934/// C++11 [class.ctor] p5:
9935/// A defaulted default constructor for a class X is defined as deleted if
9936/// X is a union and all of its variant members are of const-qualified type.
9937bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9938 // This is a silly definition, because it gives an empty union a deleted
9939 // default constructor. Don't do that.
9940 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9941 AllFieldsAreConst) {
9942 bool AnyFields = false;
9943 for (auto *F : MD->getParent()->fields())
9944 if ((AnyFields = !F->isUnnamedBitField()))
9945 break;
9946 if (!AnyFields)
9947 return false;
9948 if (Diagnose)
9949 S.Diag(Loc: MD->getParent()->getLocation(),
9950 DiagID: diag::note_deleted_default_ctor_all_const)
9951 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9952 return true;
9953 }
9954 return false;
9955}
9956
9957/// Determine whether a defaulted special member function should be defined as
9958/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9959/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9960bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9961 CXXSpecialMemberKind CSM,
9962 InheritedConstructorInfo *ICI,
9963 bool Diagnose) {
9964 if (MD->isInvalidDecl())
9965 return false;
9966 CXXRecordDecl *RD = MD->getParent();
9967 assert(!RD->isDependentType() && "do deletion after instantiation");
9968 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9969 RD->isInvalidDecl())
9970 return false;
9971
9972 // C++11 [expr.lambda.prim]p19:
9973 // The closure type associated with a lambda-expression has a
9974 // deleted (8.4.3) default constructor and a deleted copy
9975 // assignment operator.
9976 // C++2a adds back these operators if the lambda has no lambda-capture.
9977 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
9978 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9979 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9980 if (Diagnose)
9981 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
9982 return true;
9983 }
9984
9985 // C++11 [class.copy]p7, p18:
9986 // If the class definition declares a move constructor or move assignment
9987 // operator, an implicitly declared copy constructor or copy assignment
9988 // operator is defined as deleted.
9989 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
9990 CSM == CXXSpecialMemberKind::CopyAssignment)) {
9991 CXXMethodDecl *UserDeclaredMove = nullptr;
9992
9993 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
9994 // deletion of the corresponding copy operation, not both copy operations.
9995 // MSVC 2015 has adopted the standards conforming behavior.
9996 bool DeletesOnlyMatchingCopy =
9997 getLangOpts().MSVCCompat &&
9998 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
9999
10000 if (RD->hasUserDeclaredMoveConstructor() &&
10001 (!DeletesOnlyMatchingCopy ||
10002 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10003 if (!Diagnose) return true;
10004
10005 // Find any user-declared move constructor.
10006 for (auto *I : RD->ctors()) {
10007 if (I->isMoveConstructor()) {
10008 UserDeclaredMove = I;
10009 break;
10010 }
10011 }
10012 assert(UserDeclaredMove);
10013 } else if (RD->hasUserDeclaredMoveAssignment() &&
10014 (!DeletesOnlyMatchingCopy ||
10015 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10016 if (!Diagnose) return true;
10017
10018 // Find any user-declared move assignment operator.
10019 for (auto *I : RD->methods()) {
10020 if (I->isMoveAssignmentOperator()) {
10021 UserDeclaredMove = I;
10022 break;
10023 }
10024 }
10025 assert(UserDeclaredMove);
10026 }
10027
10028 if (UserDeclaredMove) {
10029 Diag(Loc: UserDeclaredMove->getLocation(),
10030 DiagID: diag::note_deleted_copy_user_declared_move)
10031 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10032 << UserDeclaredMove->isMoveAssignmentOperator();
10033 return true;
10034 }
10035 }
10036
10037 // Do access control from the special member function
10038 ContextRAII MethodContext(*this, MD);
10039
10040 // C++11 [class.dtor]p5:
10041 // -- for a virtual destructor, lookup of the non-array deallocation function
10042 // results in an ambiguity or in a function that is deleted or inaccessible
10043 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10044 FunctionDecl *OperatorDelete = nullptr;
10045 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10046 DeclarationName Name =
10047 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10048 ImplicitDeallocationParameters IDP = {
10049 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10050 AlignedAllocationMode::No, SizedDeallocationMode::No};
10051 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10052 Operator&: OperatorDelete, IDP,
10053 /*Diagnose=*/false)) {
10054 if (Diagnose)
10055 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10056 return true;
10057 }
10058 }
10059
10060 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10061
10062 // Per DR1611, do not consider virtual bases of constructors of abstract
10063 // classes, since we are not going to construct them.
10064 // Per DR1658, do not consider virtual bases of destructors of abstract
10065 // classes either.
10066 // Per DR2180, for assignment operators we only assign (and thus only
10067 // consider) direct bases.
10068 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10069 : SMI.VisitPotentiallyConstructedBases))
10070 return true;
10071
10072 if (SMI.shouldDeleteForAllConstMembers())
10073 return true;
10074
10075 if (getLangOpts().CUDA) {
10076 // We should delete the special member in CUDA mode if target inference
10077 // failed.
10078 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10079 // is treated as certain special member, which may not reflect what special
10080 // member MD really is. However inferTargetForImplicitSpecialMember
10081 // expects CSM to match MD, therefore recalculate CSM.
10082 assert(ICI || CSM == getSpecialMember(MD));
10083 auto RealCSM = CSM;
10084 if (ICI)
10085 RealCSM = getSpecialMember(MD);
10086
10087 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10088 ConstRHS: SMI.ConstArg, Diagnose);
10089 }
10090
10091 return false;
10092}
10093
10094void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10095 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
10096 assert(DFK && "not a defaultable function");
10097 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10098
10099 if (DFK.isSpecialMember()) {
10100 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10101 ICI: nullptr, /*Diagnose=*/true);
10102 } else {
10103 DefaultedComparisonAnalyzer(
10104 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10105 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10106 .visit();
10107 }
10108}
10109
10110/// Perform lookup for a special member of the specified kind, and determine
10111/// whether it is trivial. If the triviality can be determined without the
10112/// lookup, skip it. This is intended for use when determining whether a
10113/// special member of a containing object is trivial, and thus does not ever
10114/// perform overload resolution for default constructors.
10115///
10116/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10117/// member that was most likely to be intended to be trivial, if any.
10118///
10119/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10120/// determine whether the special member is trivial.
10121static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10122 CXXSpecialMemberKind CSM, unsigned Quals,
10123 bool ConstRHS, TrivialABIHandling TAH,
10124 CXXMethodDecl **Selected) {
10125 if (Selected)
10126 *Selected = nullptr;
10127
10128 switch (CSM) {
10129 case CXXSpecialMemberKind::Invalid:
10130 llvm_unreachable("not a special member");
10131
10132 case CXXSpecialMemberKind::DefaultConstructor:
10133 // C++11 [class.ctor]p5:
10134 // A default constructor is trivial if:
10135 // - all the [direct subobjects] have trivial default constructors
10136 //
10137 // Note, no overload resolution is performed in this case.
10138 if (RD->hasTrivialDefaultConstructor())
10139 return true;
10140
10141 if (Selected) {
10142 // If there's a default constructor which could have been trivial, dig it
10143 // out. Otherwise, if there's any user-provided default constructor, point
10144 // to that as an example of why there's not a trivial one.
10145 CXXConstructorDecl *DefCtor = nullptr;
10146 if (RD->needsImplicitDefaultConstructor())
10147 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10148 for (auto *CI : RD->ctors()) {
10149 if (!CI->isDefaultConstructor())
10150 continue;
10151 DefCtor = CI;
10152 if (!DefCtor->isUserProvided())
10153 break;
10154 }
10155
10156 *Selected = DefCtor;
10157 }
10158
10159 return false;
10160
10161 case CXXSpecialMemberKind::Destructor:
10162 // C++11 [class.dtor]p5:
10163 // A destructor is trivial if:
10164 // - all the direct [subobjects] have trivial destructors
10165 if (RD->hasTrivialDestructor() ||
10166 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10167 RD->hasTrivialDestructorForCall()))
10168 return true;
10169
10170 if (Selected) {
10171 if (RD->needsImplicitDestructor())
10172 S.DeclareImplicitDestructor(ClassDecl: RD);
10173 *Selected = RD->getDestructor();
10174 }
10175
10176 return false;
10177
10178 case CXXSpecialMemberKind::CopyConstructor:
10179 // C++11 [class.copy]p12:
10180 // A copy constructor is trivial if:
10181 // - the constructor selected to copy each direct [subobject] is trivial
10182 if (RD->hasTrivialCopyConstructor() ||
10183 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10184 RD->hasTrivialCopyConstructorForCall())) {
10185 if (Quals == Qualifiers::Const)
10186 // We must either select the trivial copy constructor or reach an
10187 // ambiguity; no need to actually perform overload resolution.
10188 return true;
10189 } else if (!Selected) {
10190 return false;
10191 }
10192 // In C++98, we are not supposed to perform overload resolution here, but we
10193 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10194 // cases like B as having a non-trivial copy constructor:
10195 // struct A { template<typename T> A(T&); };
10196 // struct B { mutable A a; };
10197 goto NeedOverloadResolution;
10198
10199 case CXXSpecialMemberKind::CopyAssignment:
10200 // C++11 [class.copy]p25:
10201 // A copy assignment operator is trivial if:
10202 // - the assignment operator selected to copy each direct [subobject] is
10203 // trivial
10204 if (RD->hasTrivialCopyAssignment()) {
10205 if (Quals == Qualifiers::Const)
10206 return true;
10207 } else if (!Selected) {
10208 return false;
10209 }
10210 // In C++98, we are not supposed to perform overload resolution here, but we
10211 // treat that as a language defect.
10212 goto NeedOverloadResolution;
10213
10214 case CXXSpecialMemberKind::MoveConstructor:
10215 case CXXSpecialMemberKind::MoveAssignment:
10216 NeedOverloadResolution:
10217 Sema::SpecialMemberOverloadResult SMOR =
10218 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10219
10220 // The standard doesn't describe how to behave if the lookup is ambiguous.
10221 // We treat it as not making the member non-trivial, just like the standard
10222 // mandates for the default constructor. This should rarely matter, because
10223 // the member will also be deleted.
10224 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10225 return true;
10226
10227 if (!SMOR.getMethod()) {
10228 assert(SMOR.getKind() ==
10229 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10230 return false;
10231 }
10232
10233 // We deliberately don't check if we found a deleted special member. We're
10234 // not supposed to!
10235 if (Selected)
10236 *Selected = SMOR.getMethod();
10237
10238 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10239 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10240 CSM == CXXSpecialMemberKind::MoveConstructor))
10241 return SMOR.getMethod()->isTrivialForCall();
10242 return SMOR.getMethod()->isTrivial();
10243 }
10244
10245 llvm_unreachable("unknown special method kind");
10246}
10247
10248static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10249 for (auto *CI : RD->ctors())
10250 if (!CI->isImplicit())
10251 return CI;
10252
10253 // Look for constructor templates.
10254 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10255 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10256 if (CXXConstructorDecl *CD =
10257 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10258 return CD;
10259 }
10260
10261 return nullptr;
10262}
10263
10264/// The kind of subobject we are checking for triviality. The values of this
10265/// enumeration are used in diagnostics.
10266enum TrivialSubobjectKind {
10267 /// The subobject is a base class.
10268 TSK_BaseClass,
10269 /// The subobject is a non-static data member.
10270 TSK_Field,
10271 /// The object is actually the complete object.
10272 TSK_CompleteObject
10273};
10274
10275/// Check whether the special member selected for a given type would be trivial.
10276static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10277 QualType SubType, bool ConstRHS,
10278 CXXSpecialMemberKind CSM,
10279 TrivialSubobjectKind Kind,
10280 TrivialABIHandling TAH, bool Diagnose) {
10281 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10282 if (!SubRD)
10283 return true;
10284
10285 CXXMethodDecl *Selected;
10286 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10287 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10288 return true;
10289
10290 if (Diagnose) {
10291 if (ConstRHS)
10292 SubType.addConst();
10293
10294 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10295 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10296 << Kind << SubType.getUnqualifiedType();
10297 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10298 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10299 } else if (!Selected)
10300 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10301 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10302 else if (Selected->isUserProvided()) {
10303 if (Kind == TSK_CompleteObject)
10304 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10305 << Kind << SubType.getUnqualifiedType() << CSM;
10306 else {
10307 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10308 << Kind << SubType.getUnqualifiedType() << CSM;
10309 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10310 }
10311 } else {
10312 if (Kind != TSK_CompleteObject)
10313 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10314 << Kind << SubType.getUnqualifiedType() << CSM;
10315
10316 // Explain why the defaulted or deleted special member isn't trivial.
10317 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10318 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10319 }
10320 }
10321
10322 return false;
10323}
10324
10325/// Check whether the members of a class type allow a special member to be
10326/// trivial.
10327static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10328 CXXSpecialMemberKind CSM, bool ConstArg,
10329 TrivialABIHandling TAH, bool Diagnose) {
10330 for (const auto *FI : RD->fields()) {
10331 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10332 continue;
10333
10334 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10335
10336 // Pretend anonymous struct or union members are members of this class.
10337 if (FI->isAnonymousStructOrUnion()) {
10338 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10339 CSM, ConstArg, TAH, Diagnose))
10340 return false;
10341 continue;
10342 }
10343
10344 // C++11 [class.ctor]p5:
10345 // A default constructor is trivial if [...]
10346 // -- no non-static data member of its class has a
10347 // brace-or-equal-initializer
10348 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10349 FI->hasInClassInitializer()) {
10350 if (Diagnose)
10351 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10352 << FI;
10353 return false;
10354 }
10355
10356 // Objective C ARC 4.3.5:
10357 // [...] nontrivally ownership-qualified types are [...] not trivially
10358 // default constructible, copy constructible, move constructible, copy
10359 // assignable, move assignable, or destructible [...]
10360 if (FieldType.hasNonTrivialObjCLifetime()) {
10361 if (Diagnose)
10362 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10363 << RD << FieldType.getObjCLifetime();
10364 return false;
10365 }
10366
10367 bool ConstRHS = ConstArg && !FI->isMutable();
10368 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10369 CSM, Kind: TSK_Field, TAH, Diagnose))
10370 return false;
10371 }
10372
10373 return true;
10374}
10375
10376void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10377 CXXSpecialMemberKind CSM) {
10378 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10379
10380 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10381 CSM == CXXSpecialMemberKind::CopyAssignment);
10382 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10383 Kind: TSK_CompleteObject,
10384 TAH: TrivialABIHandling::IgnoreTrivialABI,
10385 /*Diagnose*/ true);
10386}
10387
10388bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10389 TrivialABIHandling TAH, bool Diagnose) {
10390 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10391 "not special enough");
10392
10393 CXXRecordDecl *RD = MD->getParent();
10394
10395 bool ConstArg = false;
10396
10397 // C++11 [class.copy]p12, p25: [DR1593]
10398 // A [special member] is trivial if [...] its parameter-type-list is
10399 // equivalent to the parameter-type-list of an implicit declaration [...]
10400 switch (CSM) {
10401 case CXXSpecialMemberKind::DefaultConstructor:
10402 case CXXSpecialMemberKind::Destructor:
10403 // Trivial default constructors and destructors cannot have parameters.
10404 break;
10405
10406 case CXXSpecialMemberKind::CopyConstructor:
10407 case CXXSpecialMemberKind::CopyAssignment: {
10408 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10409 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10410
10411 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10412 // if they are not user-provided and their parameter-type-list is equivalent
10413 // to the parameter-type-list of an implicit declaration. This maintains the
10414 // behavior before dr2171 was implemented.
10415 //
10416 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10417 // trivial, if they are not user-provided, regardless of the qualifiers on
10418 // the reference type.
10419 const bool ClangABICompat14 = Context.getLangOpts().getClangABICompat() <=
10420 LangOptions::ClangABI::Ver14;
10421 if (!RT ||
10422 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10423 ClangABICompat14)) {
10424 if (Diagnose)
10425 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10426 << Param0->getSourceRange() << Param0->getType()
10427 << Context.getLValueReferenceType(
10428 T: Context.getCanonicalTagType(TD: RD).withConst());
10429 return false;
10430 }
10431
10432 ConstArg = RT->getPointeeType().isConstQualified();
10433 break;
10434 }
10435
10436 case CXXSpecialMemberKind::MoveConstructor:
10437 case CXXSpecialMemberKind::MoveAssignment: {
10438 // Trivial move operations always have non-cv-qualified parameters.
10439 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10440 const RValueReferenceType *RT =
10441 Param0->getType()->getAs<RValueReferenceType>();
10442 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10443 if (Diagnose)
10444 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10445 << Param0->getSourceRange() << Param0->getType()
10446 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10447 return false;
10448 }
10449 break;
10450 }
10451
10452 case CXXSpecialMemberKind::Invalid:
10453 llvm_unreachable("not a special member");
10454 }
10455
10456 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10457 if (Diagnose)
10458 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10459 DiagID: diag::note_nontrivial_default_arg)
10460 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10461 return false;
10462 }
10463 if (MD->isVariadic()) {
10464 if (Diagnose)
10465 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10466 return false;
10467 }
10468
10469 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10470 // A copy/move [constructor or assignment operator] is trivial if
10471 // -- the [member] selected to copy/move each direct base class subobject
10472 // is trivial
10473 //
10474 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10475 // A [default constructor or destructor] is trivial if
10476 // -- all the direct base classes have trivial [default constructors or
10477 // destructors]
10478 for (const auto &BI : RD->bases())
10479 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10480 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10481 return false;
10482
10483 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10484 // A copy/move [constructor or assignment operator] for a class X is
10485 // trivial if
10486 // -- for each non-static data member of X that is of class type (or array
10487 // thereof), the constructor selected to copy/move that member is
10488 // trivial
10489 //
10490 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10491 // A [default constructor or destructor] is trivial if
10492 // -- for all of the non-static data members of its class that are of class
10493 // type (or array thereof), each such class has a trivial [default
10494 // constructor or destructor]
10495 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10496 return false;
10497
10498 // C++11 [class.dtor]p5:
10499 // A destructor is trivial if [...]
10500 // -- the destructor is not virtual
10501 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10502 if (Diagnose)
10503 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10504 return false;
10505 }
10506
10507 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10508 // A [special member] for class X is trivial if [...]
10509 // -- class X has no virtual functions and no virtual base classes
10510 if (CSM != CXXSpecialMemberKind::Destructor &&
10511 MD->getParent()->isDynamicClass()) {
10512 if (!Diagnose)
10513 return false;
10514
10515 if (RD->getNumVBases()) {
10516 // Check for virtual bases. We already know that the corresponding
10517 // member in all bases is trivial, so vbases must all be direct.
10518 CXXBaseSpecifier &BS = *RD->vbases_begin();
10519 assert(BS.isVirtual());
10520 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10521 return false;
10522 }
10523
10524 // Must have a virtual method.
10525 for (const auto *MI : RD->methods()) {
10526 if (MI->isVirtual()) {
10527 SourceLocation MLoc = MI->getBeginLoc();
10528 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10529 return false;
10530 }
10531 }
10532
10533 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10534 }
10535
10536 // Looks like it's trivial!
10537 return true;
10538}
10539
10540namespace {
10541struct FindHiddenVirtualMethod {
10542 Sema *S;
10543 CXXMethodDecl *Method;
10544 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10545 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10546
10547private:
10548 /// Check whether any most overridden method from MD in Methods
10549 static bool CheckMostOverridenMethods(
10550 const CXXMethodDecl *MD,
10551 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10552 if (MD->size_overridden_methods() == 0)
10553 return Methods.count(Ptr: MD->getCanonicalDecl());
10554 for (const CXXMethodDecl *O : MD->overridden_methods())
10555 if (CheckMostOverridenMethods(MD: O, Methods))
10556 return true;
10557 return false;
10558 }
10559
10560public:
10561 /// Member lookup function that determines whether a given C++
10562 /// method overloads virtual methods in a base class without overriding any,
10563 /// to be used with CXXRecordDecl::lookupInBases().
10564 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10565 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10566 DeclarationName Name = Method->getDeclName();
10567 assert(Name.getNameKind() == DeclarationName::Identifier);
10568
10569 bool foundSameNameMethod = false;
10570 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10571 for (Path.Decls = BaseRecord->lookup(Name).begin();
10572 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10573 NamedDecl *D = *Path.Decls;
10574 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10575 MD = MD->getCanonicalDecl();
10576 foundSameNameMethod = true;
10577 // Interested only in hidden virtual methods.
10578 if (!MD->isVirtual())
10579 continue;
10580 // If the method we are checking overrides a method from its base
10581 // don't warn about the other overloaded methods. Clang deviates from
10582 // GCC by only diagnosing overloads of inherited virtual functions that
10583 // do not override any other virtual functions in the base. GCC's
10584 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10585 // function from a base class. These cases may be better served by a
10586 // warning (not specific to virtual functions) on call sites when the
10587 // call would select a different function from the base class, were it
10588 // visible.
10589 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10590 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10591 return true;
10592 // Collect the overload only if its hidden.
10593 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10594 overloadedMethods.push_back(Elt: MD);
10595 }
10596 }
10597
10598 if (foundSameNameMethod)
10599 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10600 in_end: overloadedMethods.end());
10601 return foundSameNameMethod;
10602 }
10603};
10604} // end anonymous namespace
10605
10606/// Add the most overridden methods from MD to Methods
10607static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10608 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10609 if (MD->size_overridden_methods() == 0)
10610 Methods.insert(Ptr: MD->getCanonicalDecl());
10611 else
10612 for (const CXXMethodDecl *O : MD->overridden_methods())
10613 AddMostOverridenMethods(MD: O, Methods);
10614}
10615
10616void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10617 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10618 if (!MD->getDeclName().isIdentifier())
10619 return;
10620
10621 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10622 /*bool RecordPaths=*/false,
10623 /*bool DetectVirtual=*/false);
10624 FindHiddenVirtualMethod FHVM;
10625 FHVM.Method = MD;
10626 FHVM.S = this;
10627
10628 // Keep the base methods that were overridden or introduced in the subclass
10629 // by 'using' in a set. A base method not in this set is hidden.
10630 CXXRecordDecl *DC = MD->getParent();
10631 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10632 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10633 ND = shad->getTargetDecl();
10634 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10635 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10636 }
10637
10638 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10639 OverloadedMethods = FHVM.OverloadedMethods;
10640}
10641
10642void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10643 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10644 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10645 PartialDiagnostic PD = PDiag(
10646 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10647 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10648 Diag(Loc: overloadedMD->getLocation(), PD);
10649 }
10650}
10651
10652void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10653 if (MD->isInvalidDecl())
10654 return;
10655
10656 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10657 return;
10658
10659 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10660 FindHiddenVirtualMethods(MD, OverloadedMethods);
10661 if (!OverloadedMethods.empty()) {
10662 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10663 << MD << (OverloadedMethods.size() > 1);
10664
10665 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10666 }
10667}
10668
10669void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10670 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10671 // No diagnostics if this is a template instantiation.
10672 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10673 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10674 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10675 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10676 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10677 }
10678 RD.dropAttr<TrivialABIAttr>();
10679 };
10680
10681 // Ill-formed if the struct has virtual functions.
10682 if (RD.isPolymorphic()) {
10683 PrintDiagAndRemoveAttr(1);
10684 return;
10685 }
10686
10687 for (const auto &B : RD.bases()) {
10688 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10689 // virtual base.
10690 if (!B.getType()->isDependentType() &&
10691 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10692 PrintDiagAndRemoveAttr(2);
10693 return;
10694 }
10695
10696 if (B.isVirtual()) {
10697 PrintDiagAndRemoveAttr(3);
10698 return;
10699 }
10700 }
10701
10702 for (const auto *FD : RD.fields()) {
10703 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10704 // non-trivial for the purpose of calls.
10705 QualType FT = FD->getType();
10706 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10707 PrintDiagAndRemoveAttr(4);
10708 return;
10709 }
10710
10711 // Ill-formed if the field is an address-discriminated value.
10712 if (FT.hasAddressDiscriminatedPointerAuth()) {
10713 PrintDiagAndRemoveAttr(6);
10714 return;
10715 }
10716
10717 if (const auto *RT =
10718 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10719 if (!RT->isDependentType() &&
10720 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10721 ->canPassInRegisters()) {
10722 PrintDiagAndRemoveAttr(5);
10723 return;
10724 }
10725 }
10726
10727 if (IsCXXTriviallyRelocatableType(RD))
10728 return;
10729
10730 // Ill-formed if the copy and move constructors are deleted.
10731 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10732 // If the type is dependent, then assume it might have
10733 // implicit copy or move ctor because we won't know yet at this point.
10734 if (RD.isDependentType())
10735 return true;
10736 if (RD.needsImplicitCopyConstructor() &&
10737 !RD.defaultedCopyConstructorIsDeleted())
10738 return true;
10739 if (RD.needsImplicitMoveConstructor() &&
10740 !RD.defaultedMoveConstructorIsDeleted())
10741 return true;
10742 for (const CXXConstructorDecl *CD : RD.ctors())
10743 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10744 return true;
10745 return false;
10746 };
10747
10748 if (!HasNonDeletedCopyOrMoveConstructor()) {
10749 PrintDiagAndRemoveAttr(0);
10750 return;
10751 }
10752}
10753
10754void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10755 CXXRecordDecl &RD) {
10756 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10757 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10758 return;
10759
10760 const CXXRecordDecl *PrimaryBase = &RD;
10761 if (PrimaryBase->hasAnyDependentBases())
10762 return;
10763
10764 while (1) {
10765 assert(PrimaryBase);
10766 const CXXRecordDecl *Base = nullptr;
10767 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10768 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10769 continue;
10770 Base = BasePtr.getType()->getAsCXXRecordDecl();
10771 break;
10772 }
10773 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10774 break;
10775 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10776 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10777 << &RD << Base;
10778 PrimaryBase = Base;
10779 }
10780
10781 if (!RD.isPolymorphic())
10782 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10783 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10784 << &RD;
10785}
10786
10787void Sema::ActOnFinishCXXMemberSpecification(
10788 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10789 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10790 if (!TagDecl)
10791 return;
10792
10793 AdjustDeclIfTemplate(Decl&: TagDecl);
10794
10795 for (const ParsedAttr &AL : AttrList) {
10796 if (AL.getKind() != ParsedAttr::AT_Visibility)
10797 continue;
10798 AL.setInvalid();
10799 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10800 }
10801
10802 ActOnFields(S, RecLoc: RLoc, TagDecl,
10803 Fields: llvm::ArrayRef(
10804 // strict aliasing violation!
10805 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10806 FieldCollector->getCurNumFields()),
10807 LBrac, RBrac, AttrList);
10808
10809 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10810}
10811
10812/// Find the equality comparison functions that should be implicitly declared
10813/// in a given class definition, per C++2a [class.compare.default]p3.
10814static void findImplicitlyDeclaredEqualityComparisons(
10815 ASTContext &Ctx, CXXRecordDecl *RD,
10816 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10817 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10818 if (!RD->lookup(Name: EqEq).empty())
10819 // Member operator== explicitly declared: no implicit operator==s.
10820 return;
10821
10822 // Traverse friends looking for an '==' or a '<=>'.
10823 for (FriendDecl *Friend : RD->friends()) {
10824 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10825 if (!FD) continue;
10826
10827 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10828 // Friend operator== explicitly declared: no implicit operator==s.
10829 Spaceships.clear();
10830 return;
10831 }
10832
10833 if (FD->getOverloadedOperator() == OO_Spaceship &&
10834 FD->isExplicitlyDefaulted())
10835 Spaceships.push_back(Elt: FD);
10836 }
10837
10838 // Look for members named 'operator<=>'.
10839 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10840 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10841 // Note that we could find a non-function here (either a function template
10842 // or a using-declaration). Neither case results in an implicit
10843 // 'operator=='.
10844 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10845 if (FD->isExplicitlyDefaulted())
10846 Spaceships.push_back(Elt: FD);
10847 }
10848}
10849
10850void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10851 // Don't add implicit special members to templated classes.
10852 // FIXME: This means unqualified lookups for 'operator=' within a class
10853 // template don't work properly.
10854 if (!ClassDecl->isDependentType()) {
10855 if (ClassDecl->needsImplicitDefaultConstructor()) {
10856 ++getASTContext().NumImplicitDefaultConstructors;
10857
10858 if (ClassDecl->hasInheritedConstructor())
10859 DeclareImplicitDefaultConstructor(ClassDecl);
10860 }
10861
10862 if (ClassDecl->needsImplicitCopyConstructor()) {
10863 ++getASTContext().NumImplicitCopyConstructors;
10864
10865 // If the properties or semantics of the copy constructor couldn't be
10866 // determined while the class was being declared, force a declaration
10867 // of it now.
10868 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10869 ClassDecl->hasInheritedConstructor())
10870 DeclareImplicitCopyConstructor(ClassDecl);
10871 // For the MS ABI we need to know whether the copy ctor is deleted. A
10872 // prerequisite for deleting the implicit copy ctor is that the class has
10873 // a move ctor or move assignment that is either user-declared or whose
10874 // semantics are inherited from a subobject. FIXME: We should provide a
10875 // more direct way for CodeGen to ask whether the constructor was deleted.
10876 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10877 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10878 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10879 ClassDecl->hasUserDeclaredMoveAssignment() ||
10880 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10881 DeclareImplicitCopyConstructor(ClassDecl);
10882 }
10883
10884 if (getLangOpts().CPlusPlus11 &&
10885 ClassDecl->needsImplicitMoveConstructor()) {
10886 ++getASTContext().NumImplicitMoveConstructors;
10887
10888 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10889 ClassDecl->hasInheritedConstructor())
10890 DeclareImplicitMoveConstructor(ClassDecl);
10891 }
10892
10893 if (ClassDecl->needsImplicitCopyAssignment()) {
10894 ++getASTContext().NumImplicitCopyAssignmentOperators;
10895
10896 // If we have a dynamic class, then the copy assignment operator may be
10897 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10898 // it shows up in the right place in the vtable and that we diagnose
10899 // problems with the implicit exception specification.
10900 if (ClassDecl->isDynamicClass() ||
10901 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10902 ClassDecl->hasInheritedAssignment())
10903 DeclareImplicitCopyAssignment(ClassDecl);
10904 }
10905
10906 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10907 ++getASTContext().NumImplicitMoveAssignmentOperators;
10908
10909 // Likewise for the move assignment operator.
10910 if (ClassDecl->isDynamicClass() ||
10911 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10912 ClassDecl->hasInheritedAssignment())
10913 DeclareImplicitMoveAssignment(ClassDecl);
10914 }
10915
10916 if (ClassDecl->needsImplicitDestructor()) {
10917 ++getASTContext().NumImplicitDestructors;
10918
10919 // If we have a dynamic class, then the destructor may be virtual, so we
10920 // have to declare the destructor immediately. This ensures that, e.g., it
10921 // shows up in the right place in the vtable and that we diagnose problems
10922 // with the implicit exception specification.
10923 if (ClassDecl->isDynamicClass() ||
10924 ClassDecl->needsOverloadResolutionForDestructor())
10925 DeclareImplicitDestructor(ClassDecl);
10926 }
10927 }
10928
10929 // C++2a [class.compare.default]p3:
10930 // If the member-specification does not explicitly declare any member or
10931 // friend named operator==, an == operator function is declared implicitly
10932 // for each defaulted three-way comparison operator function defined in
10933 // the member-specification
10934 // FIXME: Consider doing this lazily.
10935 // We do this during the initial parse for a class template, not during
10936 // instantiation, so that we can handle unqualified lookups for 'operator=='
10937 // when parsing the template.
10938 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10939 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10940 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10941 Spaceships&: DefaultedSpaceships);
10942 for (auto *FD : DefaultedSpaceships)
10943 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10944 }
10945}
10946
10947unsigned
10948Sema::ActOnReenterTemplateScope(Decl *D,
10949 llvm::function_ref<Scope *()> EnterScope) {
10950 if (!D)
10951 return 0;
10952 AdjustDeclIfTemplate(Decl&: D);
10953
10954 // In order to get name lookup right, reenter template scopes in order from
10955 // outermost to innermost.
10956 SmallVector<TemplateParameterList *, 4> ParameterLists;
10957 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10958
10959 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10960 for (unsigned i = 0; i < DD->getNumTemplateParameterLists(); ++i)
10961 ParameterLists.push_back(Elt: DD->getTemplateParameterList(index: i));
10962
10963 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10964 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10965 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10966 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
10967 LookupDC = VD->getDeclContext();
10968
10969 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10970 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
10971 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
10972 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10973 }
10974 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
10975 for (unsigned i = 0; i < TD->getNumTemplateParameterLists(); ++i)
10976 ParameterLists.push_back(Elt: TD->getTemplateParameterList(i));
10977
10978 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
10979 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
10980 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
10981 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
10982 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
10983 }
10984 }
10985 // FIXME: Alias declarations and concepts.
10986
10987 unsigned Count = 0;
10988 Scope *InnermostTemplateScope = nullptr;
10989 for (TemplateParameterList *Params : ParameterLists) {
10990 // Ignore explicit specializations; they don't contribute to the template
10991 // depth.
10992 if (Params->size() == 0)
10993 continue;
10994
10995 InnermostTemplateScope = EnterScope();
10996 for (NamedDecl *Param : *Params) {
10997 if (Param->getDeclName()) {
10998 InnermostTemplateScope->AddDecl(D: Param);
10999 IdResolver.AddDecl(D: Param);
11000 }
11001 }
11002 ++Count;
11003 }
11004
11005 // Associate the new template scopes with the corresponding entities.
11006 if (InnermostTemplateScope) {
11007 assert(LookupDC && "no enclosing DeclContext for template lookup");
11008 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11009 }
11010
11011 return Count;
11012}
11013
11014void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11015 if (!RecordD) return;
11016 AdjustDeclIfTemplate(Decl&: RecordD);
11017 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11018 PushDeclContext(S, DC: Record);
11019}
11020
11021void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11022 if (!RecordD) return;
11023 PopDeclContext();
11024}
11025
11026void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11027 if (!Param)
11028 return;
11029
11030 S->AddDecl(D: Param);
11031 if (Param->getDeclName())
11032 IdResolver.AddDecl(D: Param);
11033}
11034
11035void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11036}
11037
11038/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11039/// C++ method declaration. We're (re-)introducing the given
11040/// function parameter into scope for use in parsing later parts of
11041/// the method declaration. For example, we could see an
11042/// ActOnParamDefaultArgument event for this parameter.
11043void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11044 if (!ParamD)
11045 return;
11046
11047 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11048
11049 S->AddDecl(D: Param);
11050 if (Param->getDeclName())
11051 IdResolver.AddDecl(D: Param);
11052}
11053
11054void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11055 if (!MethodD)
11056 return;
11057
11058 AdjustDeclIfTemplate(Decl&: MethodD);
11059
11060 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11061
11062 // Now that we have our default arguments, check the constructor
11063 // again. It could produce additional diagnostics or affect whether
11064 // the class has implicitly-declared destructors, among other
11065 // things.
11066 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11067 CheckConstructor(Constructor);
11068
11069 // Check the default arguments, which we may have added.
11070 if (!Method->isInvalidDecl())
11071 CheckCXXDefaultArguments(FD: Method);
11072}
11073
11074// Emit the given diagnostic for each non-address-space qualifier.
11075// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11076static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11077 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11078 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11079 bool DiagOccurred = false;
11080 FTI.MethodQualifiers->forEachQualifier(
11081 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11082 SourceLocation SL) {
11083 // This diagnostic should be emitted on any qualifier except an addr
11084 // space qualifier. However, forEachQualifier currently doesn't visit
11085 // addr space qualifiers, so there's no way to write this condition
11086 // right now; we just diagnose on everything.
11087 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11088 DiagOccurred = true;
11089 });
11090 if (DiagOccurred)
11091 D.setInvalidType();
11092 }
11093}
11094
11095static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11096 unsigned Kind) {
11097 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11098 return;
11099
11100 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11101 if (Chunk.Kind == DeclaratorChunk::Paren ||
11102 Chunk.Kind == DeclaratorChunk::Function)
11103 return;
11104
11105 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11106 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11107 << Kind << Chunk.getSourceRange();
11108 D.setInvalidType();
11109}
11110
11111QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11112 StorageClass &SC) {
11113 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11114
11115 // C++ [class.ctor]p3:
11116 // A constructor shall not be virtual (10.3) or static (9.4). A
11117 // constructor can be invoked for a const, volatile or const
11118 // volatile object. A constructor shall not be declared const,
11119 // volatile, or const volatile (9.3.2).
11120 if (isVirtual) {
11121 if (!D.isInvalidType())
11122 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11123 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11124 << SourceRange(D.getIdentifierLoc());
11125 D.setInvalidType();
11126 }
11127 if (SC == SC_Static) {
11128 if (!D.isInvalidType())
11129 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11130 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11131 << SourceRange(D.getIdentifierLoc());
11132 D.setInvalidType();
11133 SC = SC_None;
11134 }
11135
11136 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11137 diagnoseIgnoredQualifiers(
11138 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11139 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11140 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11141 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11142 D.setInvalidType();
11143 }
11144
11145 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11146 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11147
11148 // C++0x [class.ctor]p4:
11149 // A constructor shall not be declared with a ref-qualifier.
11150 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11151 if (FTI.hasRefQualifier()) {
11152 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11153 << FTI.RefQualifierIsLValueRef
11154 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11155 D.setInvalidType();
11156 }
11157
11158 // Rebuild the function type "R" without any type qualifiers (in
11159 // case any of the errors above fired) and with "void" as the
11160 // return type, since constructors don't have return types.
11161 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11162 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11163 return R;
11164
11165 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11166 EPI.TypeQuals = Qualifiers();
11167 EPI.RefQualifier = RQ_None;
11168
11169 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11170}
11171
11172void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11173 CXXRecordDecl *ClassDecl
11174 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11175 if (!ClassDecl)
11176 return Constructor->setInvalidDecl();
11177
11178 // C++ [class.copy]p3:
11179 // A declaration of a constructor for a class X is ill-formed if
11180 // its first parameter is of type (optionally cv-qualified) X and
11181 // either there are no other parameters or else all other
11182 // parameters have default arguments.
11183 if (!Constructor->isInvalidDecl() &&
11184 Constructor->hasOneParamOrDefaultArgs() &&
11185 !Constructor->isFunctionTemplateSpecialization()) {
11186 CanQualType ParamType =
11187 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11188 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11189 if (ParamType == ClassTy) {
11190 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11191 const char *ConstRef
11192 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11193 : " const &";
11194 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11195 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11196
11197 // FIXME: Rather that making the constructor invalid, we should endeavor
11198 // to fix the type.
11199 Constructor->setInvalidDecl();
11200 }
11201 }
11202}
11203
11204bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11205 CXXRecordDecl *RD = Destructor->getParent();
11206
11207 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11208 SourceLocation Loc;
11209
11210 if (!Destructor->isImplicit())
11211 Loc = Destructor->getLocation();
11212 else
11213 Loc = RD->getLocation();
11214
11215 DeclarationName Name =
11216 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11217 // If we have a virtual destructor, look up the deallocation function
11218 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11219 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11220 Expr *ThisArg = nullptr;
11221
11222 // If the notional 'delete this' expression requires a non-trivial
11223 // conversion from 'this' to the type of a destroying operator delete's
11224 // first parameter, perform that conversion now.
11225 if (OperatorDelete->isDestroyingOperatorDelete()) {
11226 unsigned AddressParamIndex = 0;
11227 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11228 ++AddressParamIndex;
11229 QualType ParamType =
11230 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11231 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11232 // C++ [class.dtor]p13:
11233 // ... as if for the expression 'delete this' appearing in a
11234 // non-virtual destructor of the destructor's class.
11235 ContextRAII SwitchContext(*this, Destructor);
11236 ExprResult This = ActOnCXXThis(
11237 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11238 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11239 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11240 Action: AssignmentAction::Passing);
11241 if (This.isInvalid()) {
11242 // FIXME: Register this as a context note so that it comes out
11243 // in the right order.
11244 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11245 return true;
11246 }
11247 ThisArg = This.get();
11248 }
11249 }
11250
11251 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11252 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11253 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11254
11255 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11256 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11257 Context.getLangOpts())) {
11258 // In Microsoft ABI whenever a class has a defined operator delete,
11259 // scalar deleting destructors check the 3rd bit of the implicit
11260 // parameter and if it is set, then, global operator delete must be
11261 // called instead of the class-specific one. Find and save the global
11262 // operator delete for that case. Do not diagnose at this point because
11263 // the lack of a global operator delete is not an error if there are no
11264 // delete calls that require it.
11265 FunctionDecl *GlobalOperatorDelete =
11266 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11267 /*LookForGlobal*/ true, Name);
11268 if (GlobalOperatorDelete) {
11269 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11270 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11271 }
11272 }
11273
11274 if (Context.getTargetInfo().emitVectorDeletingDtors(
11275 Context.getLangOpts())) {
11276 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11277 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11278 DeclarationName VDeleteName =
11279 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11280 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11281 StartLoc: Loc, RD, /*Diagnose*/ false,
11282 /*LookForGlobal*/ false, Name: VDeleteName);
11283 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11284 FunctionDecl *GlobalArrOperatorDelete =
11285 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11286 /*LookForGlobal*/ true,
11287 Name: VDeleteName);
11288 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11289 if (GlobalArrOperatorDelete &&
11290 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11291 DestructorIsExported))
11292 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11293 } else if (!ArrOperatorDelete) {
11294 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11295 StartLoc: Loc, RD, /*Diagnose*/ false,
11296 /*LookForGlobal*/ true, Name: VDeleteName);
11297 }
11298 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11299 if (ArrOperatorDelete &&
11300 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11301 DestructorIsExported))
11302 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11303 }
11304 }
11305 }
11306
11307 return false;
11308}
11309
11310QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11311 StorageClass& SC) {
11312 // C++ [class.dtor]p1:
11313 // [...] A typedef-name that names a class is a class-name
11314 // (7.1.3); however, a typedef-name that names a class shall not
11315 // be used as the identifier in the declarator for a destructor
11316 // declaration.
11317 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11318 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11319 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11320 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11321 else if (const TemplateSpecializationType *TST =
11322 DeclaratorType->getAs<TemplateSpecializationType>())
11323 if (TST->isTypeAlias())
11324 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11325 << DeclaratorType << 1;
11326
11327 // C++ [class.dtor]p2:
11328 // A destructor is used to destroy objects of its class type. A
11329 // destructor takes no parameters, and no return type can be
11330 // specified for it (not even void). The address of a destructor
11331 // shall not be taken. A destructor shall not be static. A
11332 // destructor can be invoked for a const, volatile or const
11333 // volatile object. A destructor shall not be declared const,
11334 // volatile or const volatile (9.3.2).
11335 if (SC == SC_Static) {
11336 if (!D.isInvalidType())
11337 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11338 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11339 << SourceRange(D.getIdentifierLoc())
11340 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11341
11342 SC = SC_None;
11343 }
11344 if (!D.isInvalidType()) {
11345 // Destructors don't have return types, but the parser will
11346 // happily parse something like:
11347 //
11348 // class X {
11349 // float ~X();
11350 // };
11351 //
11352 // The return type will be eliminated later.
11353 if (D.getDeclSpec().hasTypeSpecifier())
11354 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11355 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11356 << SourceRange(D.getIdentifierLoc());
11357 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11358 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11359 FallbackLoc: SourceLocation(),
11360 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11361 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11362 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11363 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11364 D.setInvalidType();
11365 }
11366 }
11367
11368 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11369 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11370
11371 // C++0x [class.dtor]p2:
11372 // A destructor shall not be declared with a ref-qualifier.
11373 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11374 if (FTI.hasRefQualifier()) {
11375 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11376 << FTI.RefQualifierIsLValueRef
11377 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11378 D.setInvalidType();
11379 }
11380
11381 // Make sure we don't have any parameters.
11382 if (FTIHasNonVoidParameters(FTI)) {
11383 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11384
11385 // Delete the parameters.
11386 FTI.freeParams();
11387 D.setInvalidType();
11388 }
11389
11390 // Make sure the destructor isn't variadic.
11391 if (FTI.isVariadic) {
11392 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11393 D.setInvalidType();
11394 }
11395
11396 // Rebuild the function type "R" without any type qualifiers or
11397 // parameters (in case any of the errors above fired) and with
11398 // "void" as the return type, since destructors don't have return
11399 // types.
11400 if (!D.isInvalidType())
11401 return R;
11402
11403 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11404 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11405 EPI.Variadic = false;
11406 EPI.TypeQuals = Qualifiers();
11407 EPI.RefQualifier = RQ_None;
11408 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11409}
11410
11411static void extendLeft(SourceRange &R, SourceRange Before) {
11412 if (Before.isInvalid())
11413 return;
11414 R.setBegin(Before.getBegin());
11415 if (R.getEnd().isInvalid())
11416 R.setEnd(Before.getEnd());
11417}
11418
11419static void extendRight(SourceRange &R, SourceRange After) {
11420 if (After.isInvalid())
11421 return;
11422 if (R.getBegin().isInvalid())
11423 R.setBegin(After.getBegin());
11424 R.setEnd(After.getEnd());
11425}
11426
11427void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11428 StorageClass& SC) {
11429 // C++ [class.conv.fct]p1:
11430 // Neither parameter types nor return type can be specified. The
11431 // type of a conversion function (8.3.5) is "function taking no
11432 // parameter returning conversion-type-id."
11433 if (SC == SC_Static) {
11434 if (!D.isInvalidType())
11435 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11436 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11437 << D.getName().getSourceRange();
11438 D.setInvalidType();
11439 SC = SC_None;
11440 }
11441
11442 TypeSourceInfo *ConvTSI = nullptr;
11443 QualType ConvType =
11444 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11445
11446 const DeclSpec &DS = D.getDeclSpec();
11447 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11448 // Conversion functions don't have return types, but the parser will
11449 // happily parse something like:
11450 //
11451 // class X {
11452 // float operator bool();
11453 // };
11454 //
11455 // The return type will be changed later anyway.
11456 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11457 << SourceRange(DS.getTypeSpecTypeLoc())
11458 << SourceRange(D.getIdentifierLoc());
11459 D.setInvalidType();
11460 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11461 // It's also plausible that the user writes type qualifiers in the wrong
11462 // place, such as:
11463 // struct S { const operator int(); };
11464 // FIXME: we could provide a fixit to move the qualifiers onto the
11465 // conversion type.
11466 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11467 << SourceRange(D.getIdentifierLoc()) << 0;
11468 D.setInvalidType();
11469 }
11470 const auto *Proto = R->castAs<FunctionProtoType>();
11471 // Make sure we don't have any parameters.
11472 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11473 unsigned NumParam = Proto->getNumParams();
11474
11475 // [C++2b]
11476 // A conversion function shall have no non-object parameters.
11477 if (NumParam == 1) {
11478 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11479 if (const auto *First =
11480 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11481 First && First->isExplicitObjectParameter())
11482 NumParam--;
11483 }
11484
11485 if (NumParam != 0) {
11486 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11487 // Delete the parameters.
11488 FTI.freeParams();
11489 D.setInvalidType();
11490 } else if (Proto->isVariadic()) {
11491 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11492 D.setInvalidType();
11493 }
11494
11495 // Diagnose "&operator bool()" and other such nonsense. This
11496 // is actually a gcc extension which we don't support.
11497 if (Proto->getReturnType() != ConvType) {
11498 bool NeedsTypedef = false;
11499 SourceRange Before, After;
11500
11501 // Walk the chunks and extract information on them for our diagnostic.
11502 bool PastFunctionChunk = false;
11503 for (auto &Chunk : D.type_objects()) {
11504 switch (Chunk.Kind) {
11505 case DeclaratorChunk::Function:
11506 if (!PastFunctionChunk) {
11507 if (Chunk.Fun.HasTrailingReturnType) {
11508 TypeSourceInfo *TRT = nullptr;
11509 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11510 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11511 }
11512 PastFunctionChunk = true;
11513 break;
11514 }
11515 [[fallthrough]];
11516 case DeclaratorChunk::Array:
11517 NeedsTypedef = true;
11518 extendRight(R&: After, After: Chunk.getSourceRange());
11519 break;
11520
11521 case DeclaratorChunk::Pointer:
11522 case DeclaratorChunk::BlockPointer:
11523 case DeclaratorChunk::Reference:
11524 case DeclaratorChunk::MemberPointer:
11525 case DeclaratorChunk::Pipe:
11526 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11527 break;
11528
11529 case DeclaratorChunk::Paren:
11530 extendLeft(R&: Before, Before: Chunk.Loc);
11531 extendRight(R&: After, After: Chunk.EndLoc);
11532 break;
11533 }
11534 }
11535
11536 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11537 After.isValid() ? After.getBegin() :
11538 D.getIdentifierLoc();
11539 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11540 DB << Before << After;
11541
11542 if (!NeedsTypedef) {
11543 DB << /*don't need a typedef*/0;
11544
11545 // If we can provide a correct fix-it hint, do so.
11546 if (After.isInvalid() && ConvTSI) {
11547 SourceLocation InsertLoc =
11548 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11549 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11550 << FixItHint::CreateInsertionFromRange(
11551 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11552 << FixItHint::CreateRemoval(RemoveRange: Before);
11553 }
11554 } else if (!Proto->getReturnType()->isDependentType()) {
11555 DB << /*typedef*/1 << Proto->getReturnType();
11556 } else if (getLangOpts().CPlusPlus11) {
11557 DB << /*alias template*/2 << Proto->getReturnType();
11558 } else {
11559 DB << /*might not be fixable*/3;
11560 }
11561
11562 // Recover by incorporating the other type chunks into the result type.
11563 // Note, this does *not* change the name of the function. This is compatible
11564 // with the GCC extension:
11565 // struct S { &operator int(); } s;
11566 // int &r = s.operator int(); // ok in GCC
11567 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11568 ConvType = Proto->getReturnType();
11569 }
11570
11571 // C++ [class.conv.fct]p4:
11572 // The conversion-type-id shall not represent a function type nor
11573 // an array type.
11574 if (ConvType->isArrayType()) {
11575 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11576 ConvType = Context.getPointerType(T: ConvType);
11577 D.setInvalidType();
11578 } else if (ConvType->isFunctionType()) {
11579 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11580 ConvType = Context.getPointerType(T: ConvType);
11581 D.setInvalidType();
11582 }
11583
11584 // Rebuild the function type "R" without any parameters (in case any
11585 // of the errors above fired) and with the conversion type as the
11586 // return type.
11587 if (D.isInvalidType())
11588 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11589
11590 // C++0x explicit conversion operators.
11591 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11592 Diag(Loc: DS.getExplicitSpecLoc(),
11593 DiagID: getLangOpts().CPlusPlus11
11594 ? diag::warn_cxx98_compat_explicit_conversion_functions
11595 : diag::ext_explicit_conversion_functions)
11596 << SourceRange(DS.getExplicitSpecRange());
11597}
11598
11599Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11600 assert(Conversion && "Expected to receive a conversion function declaration");
11601
11602 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11603
11604 // Make sure we aren't redeclaring the conversion function.
11605 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11606 // C++ [class.conv.fct]p1:
11607 // [...] A conversion function is never used to convert a
11608 // (possibly cv-qualified) object to the (possibly cv-qualified)
11609 // same object type (or a reference to it), to a (possibly
11610 // cv-qualified) base class of that type (or a reference to it),
11611 // or to (possibly cv-qualified) void.
11612 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11613 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11614 ConvType = ConvTypeRef->getPointeeType();
11615 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11616 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11617 /* Suppress diagnostics for instantiations. */;
11618 else if (Conversion->size_overridden_methods() != 0)
11619 /* Suppress diagnostics for overriding virtual function in a base class. */;
11620 else if (ConvType->isRecordType()) {
11621 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11622 if (ConvType == ClassType)
11623 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11624 << ClassType;
11625 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11626 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11627 << ClassType << ConvType;
11628 } else if (ConvType->isVoidType()) {
11629 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11630 << ClassType << ConvType;
11631 }
11632
11633 if (FunctionTemplateDecl *ConversionTemplate =
11634 Conversion->getDescribedFunctionTemplate()) {
11635 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11636 ConvType = ConvTypePtr->getPointeeType();
11637 }
11638 if (ConvType->isUndeducedAutoType()) {
11639 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11640 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11641 << ConvType->castAs<AutoType>()->getKeyword()
11642 << /* in declaration of conversion function template= */ 24;
11643 }
11644
11645 return ConversionTemplate;
11646 }
11647
11648 return Conversion;
11649}
11650
11651void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11652 DeclarationName Name, QualType R) {
11653 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11654}
11655
11656void Sema::CheckExplicitObjectLambda(Declarator &D) {
11657 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11658}
11659
11660void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11661 DeclarationName Name, QualType R,
11662 bool IsLambda, DeclContext *DC) {
11663 if (!D.isFunctionDeclarator())
11664 return;
11665
11666 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11667 if (FTI.NumParams == 0)
11668 return;
11669 ParmVarDecl *ExplicitObjectParam = nullptr;
11670 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11671 const auto &ParamInfo = FTI.Params[Idx];
11672 if (!ParamInfo.Param)
11673 continue;
11674 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11675 if (!Param->isExplicitObjectParameter())
11676 continue;
11677 if (Idx == 0) {
11678 ExplicitObjectParam = Param;
11679 continue;
11680 } else {
11681 Diag(Loc: Param->getLocation(),
11682 DiagID: diag::err_explicit_object_parameter_must_be_first)
11683 << IsLambda << Param->getSourceRange();
11684 }
11685 }
11686 if (!ExplicitObjectParam)
11687 return;
11688
11689 if (ExplicitObjectParam->hasDefaultArg()) {
11690 Diag(Loc: ExplicitObjectParam->getLocation(),
11691 DiagID: diag::err_explicit_object_default_arg)
11692 << ExplicitObjectParam->getSourceRange();
11693 D.setInvalidType();
11694 }
11695
11696 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11697 (D.getContext() == clang::DeclaratorContext::Member &&
11698 D.isStaticMember())) {
11699 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11700 DiagID: diag::err_explicit_object_parameter_nonmember)
11701 << D.getSourceRange() << /*static=*/0 << IsLambda;
11702 D.setInvalidType();
11703 }
11704
11705 if (D.getDeclSpec().isVirtualSpecified()) {
11706 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11707 DiagID: diag::err_explicit_object_parameter_nonmember)
11708 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11709 D.setInvalidType();
11710 }
11711
11712 // Friend declarations require some care. Consider:
11713 //
11714 // namespace N {
11715 // struct A{};
11716 // int f(A);
11717 // }
11718 //
11719 // struct S {
11720 // struct T {
11721 // int f(this T);
11722 // };
11723 //
11724 // friend int T::f(this T); // Allow this.
11725 // friend int f(this S); // But disallow this.
11726 // friend int N::f(this A); // And disallow this.
11727 // };
11728 //
11729 // Here, it seems to suffice to check whether the scope
11730 // specifier designates a class type.
11731 if (D.getDeclSpec().isFriendSpecified() &&
11732 !isa_and_present<CXXRecordDecl>(
11733 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11734 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11735 DiagID: diag::err_explicit_object_parameter_nonmember)
11736 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11737 D.setInvalidType();
11738 }
11739
11740 if (IsLambda && FTI.hasMutableQualifier()) {
11741 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11742 DiagID: diag::err_explicit_object_parameter_mutable)
11743 << D.getSourceRange();
11744 }
11745
11746 if (IsLambda)
11747 return;
11748
11749 if (!DC || !DC->isRecord()) {
11750 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11751 "should have been diagnosed already");
11752 return;
11753 }
11754
11755 // CWG2674: constructors and destructors cannot have explicit parameters.
11756 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11757 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11758 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11759 DiagID: diag::err_explicit_object_parameter_constructor)
11760 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11761 << D.getSourceRange();
11762 D.setInvalidType();
11763 }
11764}
11765
11766namespace {
11767/// Utility class to accumulate and print a diagnostic listing the invalid
11768/// specifier(s) on a declaration.
11769struct BadSpecifierDiagnoser {
11770 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11771 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11772 ~BadSpecifierDiagnoser() {
11773 Diagnostic << Specifiers;
11774 }
11775
11776 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11777 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11778 }
11779 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11780 return check(SpecLoc,
11781 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11782 }
11783 void check(SourceLocation SpecLoc, const char *Spec) {
11784 if (SpecLoc.isInvalid()) return;
11785 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11786 if (!Specifiers.empty()) Specifiers += " ";
11787 Specifiers += Spec;
11788 }
11789
11790 Sema &S;
11791 Sema::SemaDiagnosticBuilder Diagnostic;
11792 std::string Specifiers;
11793};
11794}
11795
11796bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11797 StorageClass &SC) {
11798 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11799 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11800 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11801
11802 // C++ [temp.deduct.guide]p3:
11803 // A deduction-gide shall be declared in the same scope as the
11804 // corresponding class template.
11805 if (!CurContext->getRedeclContext()->Equals(
11806 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11807 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11808 << GuidedTemplateDecl;
11809 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11810 }
11811
11812 auto &DS = D.getMutableDeclSpec();
11813 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11814 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11815 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11816 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11817 BadSpecifierDiagnoser Diagnoser(
11818 *this, D.getIdentifierLoc(),
11819 diag::err_deduction_guide_invalid_specifier);
11820
11821 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11822 DS.ClearStorageClassSpecs();
11823 SC = SC_None;
11824
11825 // 'explicit' is permitted.
11826 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11827 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11828 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11829 DS.ClearConstexprSpec();
11830
11831 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11832 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11833 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11834 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11835 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11836 DS.ClearTypeQualifiers();
11837
11838 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11839 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11840 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11841 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11842 DS.ClearTypeSpecType();
11843 }
11844
11845 if (D.isInvalidType())
11846 return true;
11847
11848 // Check the declarator is simple enough.
11849 bool FoundFunction = false;
11850 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11851 if (Chunk.Kind == DeclaratorChunk::Paren)
11852 continue;
11853 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11854 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11855 DiagID: diag::err_deduction_guide_with_complex_decl)
11856 << D.getSourceRange();
11857 break;
11858 }
11859 if (!Chunk.Fun.hasTrailingReturnType())
11860 return Diag(Loc: D.getName().getBeginLoc(),
11861 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11862
11863 // Check that the return type is written as a specialization of
11864 // the template specified as the deduction-guide's name.
11865 // The template name may not be qualified. [temp.deduct.guide]
11866 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11867 TypeSourceInfo *TSI = nullptr;
11868 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11869 assert(TSI && "deduction guide has valid type but invalid return type?");
11870 bool AcceptableReturnType = false;
11871 bool MightInstantiateToSpecialization = false;
11872 if (auto RetTST =
11873 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11874 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11875 bool TemplateMatches = Context.hasSameTemplateName(
11876 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11877
11878 const QualifiedTemplateName *Qualifiers =
11879 SpecifiedName.getAsQualifiedTemplateName();
11880 assert(Qualifiers && "expected QualifiedTemplate");
11881 bool SimplyWritten =
11882 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11883 if (SimplyWritten && TemplateMatches)
11884 AcceptableReturnType = true;
11885 else {
11886 // This could still instantiate to the right type, unless we know it
11887 // names the wrong class template.
11888 auto *TD = SpecifiedName.getAsTemplateDecl();
11889 MightInstantiateToSpecialization =
11890 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11891 }
11892 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11893 MightInstantiateToSpecialization = true;
11894 }
11895
11896 if (!AcceptableReturnType)
11897 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11898 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11899 << GuidedTemplate << TSI->getType()
11900 << MightInstantiateToSpecialization
11901 << TSI->getTypeLoc().getSourceRange();
11902
11903 // Keep going to check that we don't have any inner declarator pieces (we
11904 // could still have a function returning a pointer to a function).
11905 FoundFunction = true;
11906 }
11907
11908 if (D.isFunctionDefinition())
11909 // we can still create a valid deduction guide here.
11910 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11911 return false;
11912}
11913
11914//===----------------------------------------------------------------------===//
11915// Namespace Handling
11916//===----------------------------------------------------------------------===//
11917
11918/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11919/// reopened.
11920static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11921 SourceLocation Loc,
11922 IdentifierInfo *II, bool *IsInline,
11923 NamespaceDecl *PrevNS) {
11924 assert(*IsInline != PrevNS->isInline());
11925
11926 // 'inline' must appear on the original definition, but not necessarily
11927 // on all extension definitions, so the note should point to the first
11928 // definition to avoid confusion.
11929 PrevNS = PrevNS->getFirstDecl();
11930
11931 if (PrevNS->isInline())
11932 // The user probably just forgot the 'inline', so suggest that it
11933 // be added back.
11934 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11935 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11936 else
11937 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11938
11939 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11940 *IsInline = PrevNS->isInline();
11941}
11942
11943/// ActOnStartNamespaceDef - This is called at the start of a namespace
11944/// definition.
11945Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11946 SourceLocation InlineLoc,
11947 SourceLocation NamespaceLoc,
11948 SourceLocation IdentLoc, IdentifierInfo *II,
11949 SourceLocation LBrace,
11950 const ParsedAttributesView &AttrList,
11951 UsingDirectiveDecl *&UD, bool IsNested) {
11952 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11953 // For anonymous namespace, take the location of the left brace.
11954 SourceLocation Loc = II ? IdentLoc : LBrace;
11955 bool IsInline = InlineLoc.isValid();
11956 bool IsInvalid = false;
11957 bool IsStd = false;
11958 bool AddToKnown = false;
11959 Scope *DeclRegionScope = NamespcScope->getParent();
11960
11961 NamespaceDecl *PrevNS = nullptr;
11962 if (II) {
11963 // C++ [namespace.std]p7:
11964 // A translation unit shall not declare namespace std to be an inline
11965 // namespace (9.8.2).
11966 //
11967 // Precondition: the std namespace is in the file scope and is declared to
11968 // be inline
11969 auto DiagnoseInlineStdNS = [&]() {
11970 assert(IsInline && II->isStr("std") &&
11971 CurContext->getRedeclContext()->isTranslationUnit() &&
11972 "Precondition of DiagnoseInlineStdNS not met");
11973 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
11974 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
11975 IsInline = false;
11976 };
11977 // C++ [namespace.def]p2:
11978 // The identifier in an original-namespace-definition shall not
11979 // have been previously defined in the declarative region in
11980 // which the original-namespace-definition appears. The
11981 // identifier in an original-namespace-definition is the name of
11982 // the namespace. Subsequently in that declarative region, it is
11983 // treated as an original-namespace-name.
11984 //
11985 // Since namespace names are unique in their scope, and we don't
11986 // look through using directives, just look for any ordinary names
11987 // as if by qualified name lookup.
11988 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
11989 RedeclarationKind::ForExternalRedeclaration);
11990 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
11991 NamedDecl *PrevDecl =
11992 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
11993 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
11994
11995 if (PrevNS) {
11996 // This is an extended namespace definition.
11997 if (IsInline && II->isStr(Str: "std") &&
11998 CurContext->getRedeclContext()->isTranslationUnit())
11999 DiagnoseInlineStdNS();
12000 else if (IsInline != PrevNS->isInline())
12001 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12002 IsInline: &IsInline, PrevNS);
12003 } else if (PrevDecl) {
12004 // This is an invalid name redefinition.
12005 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12006 << II;
12007 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12008 IsInvalid = true;
12009 // Continue on to push Namespc as current DeclContext and return it.
12010 } else if (II->isStr(Str: "std") &&
12011 CurContext->getRedeclContext()->isTranslationUnit()) {
12012 if (IsInline)
12013 DiagnoseInlineStdNS();
12014 // This is the first "real" definition of the namespace "std", so update
12015 // our cache of the "std" namespace to point at this definition.
12016 PrevNS = getStdNamespace();
12017 IsStd = true;
12018 AddToKnown = !IsInline;
12019 } else {
12020 // We've seen this namespace for the first time.
12021 AddToKnown = !IsInline;
12022 }
12023 } else {
12024 // Anonymous namespaces.
12025
12026 // Determine whether the parent already has an anonymous namespace.
12027 DeclContext *Parent = CurContext->getRedeclContext();
12028 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12029 PrevNS = TU->getAnonymousNamespace();
12030 } else {
12031 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12032 PrevNS = ND->getAnonymousNamespace();
12033 }
12034
12035 if (PrevNS && IsInline != PrevNS->isInline())
12036 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12037 IsInline: &IsInline, PrevNS);
12038 }
12039
12040 NamespaceDecl *Namespc = NamespaceDecl::Create(
12041 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12042 if (IsInvalid)
12043 Namespc->setInvalidDecl();
12044
12045 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12046 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12047 ProcessAPINotes(D: Namespc);
12048
12049 // FIXME: Should we be merging attributes?
12050 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12051 PushNamespaceVisibilityAttr(Attr, Loc);
12052
12053 if (IsStd)
12054 StdNamespace = Namespc;
12055 if (AddToKnown)
12056 KnownNamespaces[Namespc] = false;
12057
12058 if (II) {
12059 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12060 } else {
12061 // Link the anonymous namespace into its parent.
12062 DeclContext *Parent = CurContext->getRedeclContext();
12063 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12064 TU->setAnonymousNamespace(Namespc);
12065 } else {
12066 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12067 }
12068
12069 CurContext->addDecl(D: Namespc);
12070
12071 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12072 // behaves as if it were replaced by
12073 // namespace unique { /* empty body */ }
12074 // using namespace unique;
12075 // namespace unique { namespace-body }
12076 // where all occurrences of 'unique' in a translation unit are
12077 // replaced by the same identifier and this identifier differs
12078 // from all other identifiers in the entire program.
12079
12080 // We just create the namespace with an empty name and then add an
12081 // implicit using declaration, just like the standard suggests.
12082 //
12083 // CodeGen enforces the "universally unique" aspect by giving all
12084 // declarations semantically contained within an anonymous
12085 // namespace internal linkage.
12086
12087 if (!PrevNS) {
12088 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12089 /* 'using' */ UsingLoc: LBrace,
12090 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12091 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12092 /* identifier */ IdentLoc: SourceLocation(),
12093 Nominated: Namespc,
12094 /* Ancestor */ CommonAncestor: Parent);
12095 UD->setImplicit();
12096 Parent->addDecl(D: UD);
12097 }
12098 }
12099
12100 ActOnDocumentableDecl(D: Namespc);
12101
12102 // Although we could have an invalid decl (i.e. the namespace name is a
12103 // redefinition), push it as current DeclContext and try to continue parsing.
12104 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12105 // for the namespace has the declarations that showed up in that particular
12106 // namespace definition.
12107 PushDeclContext(S: NamespcScope, DC: Namespc);
12108 return Namespc;
12109}
12110
12111/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12112/// is a namespace alias, returns the namespace it points to.
12113static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12114 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12115 return AD->getNamespace();
12116 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12117}
12118
12119void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12120 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12121 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12122 Namespc->setRBraceLoc(RBrace);
12123 PopDeclContext();
12124 if (Namespc->hasAttr<VisibilityAttr>())
12125 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12126 // If this namespace contains an export-declaration, export it now.
12127 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12128 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12129}
12130
12131CXXRecordDecl *Sema::getStdBadAlloc() const {
12132 return cast_or_null<CXXRecordDecl>(
12133 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12134}
12135
12136EnumDecl *Sema::getStdAlignValT() const {
12137 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12138}
12139
12140NamespaceDecl *Sema::getStdNamespace() const {
12141 return cast_or_null<NamespaceDecl>(
12142 Val: StdNamespace.get(Source: Context.getExternalSource()));
12143}
12144
12145namespace {
12146
12147enum UnsupportedSTLSelect {
12148 USS_InvalidMember,
12149 USS_MissingMember,
12150 USS_NonTrivial,
12151 USS_Other
12152};
12153
12154struct InvalidSTLDiagnoser {
12155 Sema &S;
12156 SourceLocation Loc;
12157 QualType TyForDiags;
12158
12159 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12160 const VarDecl *VD = nullptr) {
12161 {
12162 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12163 << TyForDiags << ((int)Sel);
12164 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12165 assert(!Name.empty());
12166 D << Name;
12167 }
12168 }
12169 if (Sel == USS_InvalidMember) {
12170 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12171 << VD << VD->getSourceRange();
12172 }
12173 return QualType();
12174 }
12175};
12176} // namespace
12177
12178QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12179 SourceLocation Loc,
12180 ComparisonCategoryUsage Usage) {
12181 assert(getLangOpts().CPlusPlus &&
12182 "Looking for comparison category type outside of C++.");
12183
12184 // Use an elaborated type for diagnostics which has a name containing the
12185 // prepended 'std' namespace but not any inline namespace names.
12186 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12187 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12188 /*Prefix=*/std::nullopt);
12189 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12190 TD: Info->Record,
12191 /*OwnsTag=*/false);
12192 };
12193
12194 // Check if we've already successfully checked the comparison category type
12195 // before. If so, skip checking it again.
12196 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12197 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12198 // The only thing we need to check is that the type has a reachable
12199 // definition in the current context.
12200 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12201 return QualType();
12202
12203 return Info->getType();
12204 }
12205
12206 // If lookup failed
12207 if (!Info) {
12208 std::string NameForDiags = "std::";
12209 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12210 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12211 << NameForDiags << (int)Usage;
12212 return QualType();
12213 }
12214
12215 assert(Info->Kind == Kind);
12216 assert(Info->Record);
12217
12218 // Update the Record decl in case we encountered a forward declaration on our
12219 // first pass. FIXME: This is a bit of a hack.
12220 if (Info->Record->hasDefinition())
12221 Info->Record = Info->Record->getDefinition();
12222
12223 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12224 return QualType();
12225
12226 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12227
12228 if (!Info->Record->isTriviallyCopyable())
12229 return UnsupportedSTLError(USS_NonTrivial);
12230
12231 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12232 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12233 // Tolerate empty base classes.
12234 if (Base->isEmpty())
12235 continue;
12236 // Reject STL implementations which have at least one non-empty base.
12237 return UnsupportedSTLError();
12238 }
12239
12240 // Check that the STL has implemented the types using a single integer field.
12241 // This expectation allows better codegen for builtin operators. We require:
12242 // (1) The class has exactly one field.
12243 // (2) The field is an integral or enumeration type.
12244 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12245 if (std::distance(first: FIt, last: FEnd) != 1 ||
12246 !FIt->getType()->isIntegralOrEnumerationType()) {
12247 return UnsupportedSTLError();
12248 }
12249
12250 // Build each of the require values and store them in Info.
12251 for (ComparisonCategoryResult CCR :
12252 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12253 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12254 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12255
12256 if (!ValInfo)
12257 return UnsupportedSTLError(USS_MissingMember, MemName);
12258
12259 VarDecl *VD = ValInfo->VD;
12260 assert(VD && "should not be null!");
12261
12262 // Attempt to diagnose reasons why the STL definition of this type
12263 // might be foobar, including it failing to be a constant expression.
12264 // TODO Handle more ways the lookup or result can be invalid.
12265 if (!VD->isStaticDataMember() ||
12266 !VD->isUsableInConstantExpressions(C: Context))
12267 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12268
12269 // Attempt to evaluate the var decl as a constant expression and extract
12270 // the value of its first field as a ICE. If this fails, the STL
12271 // implementation is not supported.
12272 if (!ValInfo->hasValidIntValue())
12273 return UnsupportedSTLError();
12274
12275 MarkVariableReferenced(Loc, Var: VD);
12276 }
12277
12278 // We've successfully built the required types and expressions. Update
12279 // the cache and return the newly cached value.
12280 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12281 return Info->getType();
12282}
12283
12284NamespaceDecl *Sema::getOrCreateStdNamespace() {
12285 if (!StdNamespace) {
12286 // The "std" namespace has not yet been defined, so build one implicitly.
12287 StdNamespace = NamespaceDecl::Create(
12288 C&: Context, DC: Context.getTranslationUnitDecl(),
12289 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12290 Id: &PP.getIdentifierTable().get(Name: "std"),
12291 /*PrevDecl=*/nullptr, /*Nested=*/false);
12292 getStdNamespace()->setImplicit(true);
12293 // We want the created NamespaceDecl to be available for redeclaration
12294 // lookups, but not for regular name lookups.
12295 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12296 getStdNamespace()->clearIdentifierNamespace();
12297 }
12298
12299 return getStdNamespace();
12300}
12301
12302static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12303 const char *ClassName,
12304 ClassTemplateDecl **CachedDecl,
12305 const Decl **MalformedDecl) {
12306 // We're looking for implicit instantiations of
12307 // template <typename U> class std::{ClassName}.
12308
12309 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12310 // it.
12311 return false;
12312
12313 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12314 if (!MalformedDecl)
12315 return;
12316 if (!D)
12317 D = SugaredType->getAsTagDecl();
12318 if (!D || !D->isInStdNamespace())
12319 return;
12320 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12321 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12322 *MalformedDecl = D;
12323 };
12324
12325 ClassTemplateDecl *Template = nullptr;
12326 ArrayRef<TemplateArgument> Arguments;
12327 if (const TemplateSpecializationType *TST =
12328 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12329 Template = dyn_cast_or_null<ClassTemplateDecl>(
12330 Val: TST->getTemplateName().getAsTemplateDecl());
12331 Arguments = TST->template_arguments();
12332 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12333 Template = TT->getTemplateDecl();
12334 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12335 }
12336
12337 if (!Template) {
12338 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12339 return false;
12340 }
12341
12342 if (!*CachedDecl) {
12343 // Haven't recognized std::{ClassName} yet, maybe this is it.
12344 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12345 // semantics of this are slightly different, most notably the existing
12346 // "lookup" semantics explicitly diagnose an invalid definition as an
12347 // error.
12348 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12349 if (TemplateClass->getIdentifier() !=
12350 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12351 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12352 NS: TemplateClass->getNonTransparentDeclContext()))
12353 return false;
12354 // This is a template called std::{ClassName}, but is it the right
12355 // template?
12356 TemplateParameterList *Params = Template->getTemplateParameters();
12357 if (Params->getMinRequiredArguments() != 1 ||
12358 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12359 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12360 if (MalformedDecl)
12361 *MalformedDecl = TemplateClass;
12362 return false;
12363 }
12364
12365 // It's the right template.
12366 *CachedDecl = Template;
12367 }
12368
12369 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12370 return false;
12371
12372 // This is an instance of std::{ClassName}. Find the argument type.
12373 if (TypeArg) {
12374 QualType ArgType = Arguments[0].getAsType();
12375 // FIXME: Since TST only has as-written arguments, we have to perform the
12376 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12377 // - If an explicitly-specified template argument type is a lifetime type
12378 // with no lifetime qualifier, the __strong lifetime qualifier is
12379 // inferred.
12380 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12381 !ArgType.getObjCLifetime()) {
12382 Qualifiers Qs;
12383 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12384 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12385 }
12386 *TypeArg = ArgType;
12387 }
12388
12389 return true;
12390}
12391
12392bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12393 assert(getLangOpts().CPlusPlus &&
12394 "Looking for std::initializer_list outside of C++.");
12395
12396 // We're looking for implicit instantiations of
12397 // template <typename E> class std::initializer_list.
12398
12399 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12400 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12401}
12402
12403bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12404 const Decl **MalformedDecl) {
12405 assert(getLangOpts().CPlusPlus &&
12406 "Looking for std::type_identity outside of C++.");
12407
12408 // We're looking for implicit instantiations of
12409 // template <typename T> struct std::type_identity.
12410
12411 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12412 CachedDecl: &StdTypeIdentity, MalformedDecl);
12413}
12414
12415static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12416 const char *ClassName,
12417 bool *WasMalformed) {
12418 if (!S.StdNamespace)
12419 return nullptr;
12420
12421 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12422 Sema::LookupOrdinaryName);
12423 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12424 return nullptr;
12425
12426 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12427 if (!Template) {
12428 Result.suppressDiagnostics();
12429 // We found something weird. Complain about the first thing we found.
12430 NamedDecl *Found = *Result.begin();
12431 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12432 << ClassName;
12433 if (WasMalformed)
12434 *WasMalformed = true;
12435 return nullptr;
12436 }
12437
12438 // We found some template with the correct name. Now verify that it's
12439 // correct.
12440 TemplateParameterList *Params = Template->getTemplateParameters();
12441 if (Params->getMinRequiredArguments() != 1 ||
12442 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12443 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12444 << ClassName;
12445 if (WasMalformed)
12446 *WasMalformed = true;
12447 return nullptr;
12448 }
12449
12450 return Template;
12451}
12452
12453static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12454 QualType TypeParam, SourceLocation Loc) {
12455 assert(S.getStdNamespace());
12456 TemplateArgumentListInfo Args(Loc, Loc);
12457 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12458 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12459
12460 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12461 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12462 /*ForNestedNameSpecifier=*/false);
12463}
12464
12465QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12466 if (!StdInitializerList) {
12467 bool WasMalformed = false;
12468 StdInitializerList =
12469 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12470 if (!StdInitializerList) {
12471 if (!WasMalformed)
12472 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12473 return QualType();
12474 }
12475 }
12476 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12477}
12478
12479QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12480 if (!StdTypeIdentity) {
12481 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12482 /*WasMalformed=*/nullptr);
12483 if (!StdTypeIdentity)
12484 return QualType();
12485 }
12486 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12487}
12488
12489bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12490 // C++ [dcl.init.list]p2:
12491 // A constructor is an initializer-list constructor if its first parameter
12492 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12493 // std::initializer_list<E> for some type E, and either there are no other
12494 // parameters or else all other parameters have default arguments.
12495 if (!Ctor->hasOneParamOrDefaultArgs())
12496 return false;
12497
12498 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12499 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12500 ArgType = RT->getPointeeType().getUnqualifiedType();
12501
12502 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12503}
12504
12505/// Determine whether a using statement is in a context where it will be
12506/// apply in all contexts.
12507static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12508 switch (CurContext->getDeclKind()) {
12509 case Decl::TranslationUnit:
12510 return true;
12511 case Decl::LinkageSpec:
12512 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12513 default:
12514 return false;
12515 }
12516}
12517
12518namespace {
12519
12520// Callback to only accept typo corrections that are namespaces.
12521class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12522public:
12523 bool ValidateCandidate(const TypoCorrection &candidate) override {
12524 if (NamedDecl *ND = candidate.getCorrectionDecl())
12525 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12526 return false;
12527 }
12528
12529 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12530 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12531 }
12532};
12533
12534}
12535
12536static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12537 Sema &S) {
12538 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12539 Module *M = ND->getOwningModule();
12540 assert(M && "hidden namespace definition not in a module?");
12541
12542 if (M->isExplicitGlobalModule())
12543 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12544 DiagID: diag::err_module_unimported_use_header)
12545 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12546 << /*Header Name*/ false;
12547 else
12548 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12549 DiagID: diag::err_module_unimported_use)
12550 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12551 << M->getTopLevelModuleName();
12552}
12553
12554static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12555 CXXScopeSpec &SS,
12556 SourceLocation IdentLoc,
12557 IdentifierInfo *Ident) {
12558 R.clear();
12559 NamespaceValidatorCCC CCC{};
12560 if (TypoCorrection Corrected =
12561 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12562 Mode: CorrectTypoKind::ErrorRecovery)) {
12563 // Generally we find it is confusing more than helpful to diagnose the
12564 // invisible namespace.
12565 // See https://github.com/llvm/llvm-project/issues/73893.
12566 //
12567 // However, we should diagnose when the users are trying to using an
12568 // invisible namespace. So we handle the case specially here.
12569 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12570 Corrected.requiresImport()) {
12571 DiagnoseInvisibleNamespace(Corrected, S);
12572 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12573 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12574 bool DroppedSpecifier =
12575 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12576 S.diagnoseTypo(Correction: Corrected,
12577 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12578 << Ident << DC << DroppedSpecifier << SS.getRange(),
12579 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12580 } else {
12581 S.diagnoseTypo(Correction: Corrected,
12582 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12583 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12584 }
12585 R.addDecl(D: Corrected.getFoundDecl());
12586 return true;
12587 }
12588 return false;
12589}
12590
12591Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12592 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12593 SourceLocation IdentLoc,
12594 IdentifierInfo *NamespcName,
12595 const ParsedAttributesView &AttrList) {
12596 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12597 assert(NamespcName && "Invalid NamespcName.");
12598 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12599
12600 // Get the innermost enclosing declaration scope.
12601 S = S->getDeclParent();
12602
12603 UsingDirectiveDecl *UDir = nullptr;
12604 NestedNameSpecifier Qualifier = SS.getScopeRep();
12605
12606 // Lookup namespace name.
12607 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12608 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12609 if (R.isAmbiguous())
12610 return nullptr;
12611
12612 if (R.empty()) {
12613 R.clear();
12614 // Allow "using namespace std;" or "using namespace ::std;" even if
12615 // "std" hasn't been defined yet, for GCC compatibility.
12616 if ((!Qualifier ||
12617 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12618 NamespcName->isStr(Str: "std")) {
12619 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12620 R.addDecl(D: getOrCreateStdNamespace());
12621 R.resolveKind();
12622 }
12623 // Otherwise, attempt typo correction.
12624 else
12625 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12626 }
12627
12628 if (!R.empty()) {
12629 NamedDecl *Named = R.getRepresentativeDecl();
12630 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12631 assert(NS && "expected namespace decl");
12632
12633 // The use of a nested name specifier may trigger deprecation warnings.
12634 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12635
12636 // C++ [namespace.udir]p1:
12637 // A using-directive specifies that the names in the nominated
12638 // namespace can be used in the scope in which the
12639 // using-directive appears after the using-directive. During
12640 // unqualified name lookup (3.4.1), the names appear as if they
12641 // were declared in the nearest enclosing namespace which
12642 // contains both the using-directive and the nominated
12643 // namespace. [Note: in this context, "contains" means "contains
12644 // directly or indirectly". ]
12645
12646 // Find enclosing context containing both using-directive and
12647 // nominated namespace.
12648 DeclContext *CommonAncestor = NS;
12649 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12650 CommonAncestor = CommonAncestor->getParent();
12651
12652 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12653 QualifierLoc: SS.getWithLocInContext(Context),
12654 IdentLoc, Nominated: Named, CommonAncestor);
12655
12656 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12657 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12658 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12659 }
12660
12661 PushUsingDirective(S, UDir);
12662 } else {
12663 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12664 }
12665
12666 if (UDir) {
12667 ProcessDeclAttributeList(S, D: UDir, AttrList);
12668 ProcessAPINotes(D: UDir);
12669 }
12670
12671 return UDir;
12672}
12673
12674void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12675 // If the scope has an associated entity and the using directive is at
12676 // namespace or translation unit scope, add the UsingDirectiveDecl into
12677 // its lookup structure so qualified name lookup can find it.
12678 DeclContext *Ctx = S->getEntity();
12679 if (Ctx && !Ctx->isFunctionOrMethod())
12680 Ctx->addDecl(D: UDir);
12681 else
12682 // Otherwise, it is at block scope. The using-directives will affect lookup
12683 // only to the end of the scope.
12684 S->PushUsingDirective(UDir);
12685}
12686
12687Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12688 SourceLocation UsingLoc,
12689 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12690 UnqualifiedId &Name,
12691 SourceLocation EllipsisLoc,
12692 const ParsedAttributesView &AttrList) {
12693 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12694
12695 if (SS.isEmpty()) {
12696 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12697 return nullptr;
12698 }
12699
12700 switch (Name.getKind()) {
12701 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12702 case UnqualifiedIdKind::IK_Identifier:
12703 case UnqualifiedIdKind::IK_OperatorFunctionId:
12704 case UnqualifiedIdKind::IK_LiteralOperatorId:
12705 case UnqualifiedIdKind::IK_ConversionFunctionId:
12706 break;
12707
12708 case UnqualifiedIdKind::IK_ConstructorName:
12709 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12710 // C++11 inheriting constructors.
12711 Diag(Loc: Name.getBeginLoc(),
12712 DiagID: getLangOpts().CPlusPlus11
12713 ? diag::warn_cxx98_compat_using_decl_constructor
12714 : diag::err_using_decl_constructor)
12715 << SS.getRange();
12716
12717 if (getLangOpts().CPlusPlus11) break;
12718
12719 return nullptr;
12720
12721 case UnqualifiedIdKind::IK_DestructorName:
12722 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12723 return nullptr;
12724
12725 case UnqualifiedIdKind::IK_TemplateId:
12726 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12727 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12728 return nullptr;
12729
12730 case UnqualifiedIdKind::IK_DeductionGuideName:
12731 llvm_unreachable("cannot parse qualified deduction guide name");
12732 }
12733
12734 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12735 DeclarationName TargetName = TargetNameInfo.getName();
12736 if (!TargetName)
12737 return nullptr;
12738
12739 // Warn about access declarations.
12740 if (UsingLoc.isInvalid()) {
12741 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12742 ? diag::err_access_decl
12743 : diag::warn_access_decl_deprecated)
12744 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12745 }
12746
12747 if (EllipsisLoc.isInvalid()) {
12748 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12749 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12750 return nullptr;
12751 } else {
12752 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12753 !TargetNameInfo.containsUnexpandedParameterPack()) {
12754 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12755 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12756 EllipsisLoc = SourceLocation();
12757 }
12758 }
12759
12760 NamedDecl *UD =
12761 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12762 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12763 /*IsInstantiation*/ false,
12764 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12765 if (UD)
12766 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12767
12768 return UD;
12769}
12770
12771Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12772 SourceLocation UsingLoc,
12773 SourceLocation EnumLoc, SourceRange TyLoc,
12774 const IdentifierInfo &II, ParsedType Ty,
12775 const CXXScopeSpec &SS) {
12776 TypeSourceInfo *TSI = nullptr;
12777 SourceLocation IdentLoc = TyLoc.getBegin();
12778 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12779 if (EnumTy.isNull()) {
12780 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12781 ? diag::err_using_enum_is_dependent
12782 : diag::err_unknown_typename)
12783 << II.getName()
12784 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12785 TyLoc.getEnd());
12786 return nullptr;
12787 }
12788
12789 if (EnumTy->isDependentType()) {
12790 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12791 return nullptr;
12792 }
12793
12794 auto *Enum = EnumTy->getAsEnumDecl();
12795 if (!Enum) {
12796 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12797 return nullptr;
12798 }
12799
12800 if (TSI == nullptr)
12801 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12802
12803 auto *UD =
12804 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12805
12806 if (UD)
12807 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12808
12809 return UD;
12810}
12811
12812/// Determine whether a using declaration considers the given
12813/// declarations as "equivalent", e.g., if they are redeclarations of
12814/// the same entity or are both typedefs of the same type.
12815static bool
12816IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12817 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12818 return true;
12819
12820 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12821 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12822 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12823 T2: TD2->getUnderlyingType());
12824
12825 // Two using_if_exists using-declarations are equivalent if both are
12826 // unresolved.
12827 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12828 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12829 return true;
12830
12831 return false;
12832}
12833
12834bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12835 const LookupResult &Previous,
12836 UsingShadowDecl *&PrevShadow) {
12837 // Diagnose finding a decl which is not from a base class of the
12838 // current class. We do this now because there are cases where this
12839 // function will silently decide not to build a shadow decl, which
12840 // will pre-empt further diagnostics.
12841 //
12842 // We don't need to do this in C++11 because we do the check once on
12843 // the qualifier.
12844 //
12845 // FIXME: diagnose the following if we care enough:
12846 // struct A { int foo; };
12847 // struct B : A { using A::foo; };
12848 // template <class T> struct C : A {};
12849 // template <class T> struct D : C<T> { using B::foo; } // <---
12850 // This is invalid (during instantiation) in C++03 because B::foo
12851 // resolves to the using decl in B, which is not a base class of D<T>.
12852 // We can't diagnose it immediately because C<T> is an unknown
12853 // specialization. The UsingShadowDecl in D<T> then points directly
12854 // to A::foo, which will look well-formed when we instantiate.
12855 // The right solution is to not collapse the shadow-decl chain.
12856 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12857 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12858 DeclContext *OrigDC = Orig->getDeclContext();
12859
12860 // Handle enums and anonymous structs.
12861 if (isa<EnumDecl>(Val: OrigDC))
12862 OrigDC = OrigDC->getParent();
12863 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12864 while (OrigRec->isAnonymousStructOrUnion())
12865 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12866
12867 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12868 if (OrigDC == CurContext) {
12869 Diag(Loc: Using->getLocation(),
12870 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12871 << Using->getQualifierLoc().getSourceRange();
12872 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12873 Using->setInvalidDecl();
12874 return true;
12875 }
12876
12877 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12878 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12879 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12880 << Using->getQualifierLoc().getSourceRange();
12881 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12882 Using->setInvalidDecl();
12883 return true;
12884 }
12885 }
12886
12887 if (Previous.empty()) return false;
12888
12889 NamedDecl *Target = Orig;
12890 if (isa<UsingShadowDecl>(Val: Target))
12891 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12892
12893 // If the target happens to be one of the previous declarations, we
12894 // don't have a conflict.
12895 //
12896 // FIXME: but we might be increasing its access, in which case we
12897 // should redeclare it.
12898 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12899 bool FoundEquivalentDecl = false;
12900 for (NamedDecl *Element : Previous) {
12901 NamedDecl *D = Element->getUnderlyingDecl();
12902 // We can have UsingDecls in our Previous results because we use the same
12903 // LookupResult for checking whether the UsingDecl itself is a valid
12904 // redeclaration.
12905 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12906 continue;
12907
12908 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12909 // C++ [class.mem]p19:
12910 // If T is the name of a class, then [every named member other than
12911 // a non-static data member] shall have a name different from T
12912 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12913 !isa<IndirectFieldDecl>(Val: Target) &&
12914 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12915 DiagnoseClassNameShadow(
12916 DC: CurContext,
12917 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12918 return true;
12919 }
12920
12921 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12922 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12923 PrevShadow = Shadow;
12924 FoundEquivalentDecl = true;
12925 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12926 // We don't conflict with an existing using shadow decl of an equivalent
12927 // declaration, but we're not a redeclaration of it.
12928 FoundEquivalentDecl = true;
12929 }
12930
12931 if (isVisible(D))
12932 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12933 }
12934
12935 if (FoundEquivalentDecl)
12936 return false;
12937
12938 // Always emit a diagnostic for a mismatch between an unresolved
12939 // using_if_exists and a resolved using declaration in either direction.
12940 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12941 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12942 if (!NonTag && !Tag)
12943 return false;
12944 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12945 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12946 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
12947 DiagID: diag::note_using_decl_conflict);
12948 BUD->setInvalidDecl();
12949 return true;
12950 }
12951
12952 if (FunctionDecl *FD = Target->getAsFunction()) {
12953 NamedDecl *OldDecl = nullptr;
12954 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12955 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12956 case OverloadKind::Overload:
12957 return false;
12958
12959 case OverloadKind::NonFunction:
12960 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12961 break;
12962
12963 // We found a decl with the exact signature.
12964 case OverloadKind::Match:
12965 // If we're in a record, we want to hide the target, so we
12966 // return true (without a diagnostic) to tell the caller not to
12967 // build a shadow decl.
12968 if (CurContext->isRecord())
12969 return true;
12970
12971 // If we're not in a record, this is an error.
12972 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12973 break;
12974 }
12975
12976 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12977 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
12978 BUD->setInvalidDecl();
12979 return true;
12980 }
12981
12982 // Target is not a function.
12983
12984 if (isa<TagDecl>(Val: Target)) {
12985 // No conflict between a tag and a non-tag.
12986 if (!Tag) return false;
12987
12988 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12989 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12990 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
12991 BUD->setInvalidDecl();
12992 return true;
12993 }
12994
12995 // No conflict between a tag and a non-tag.
12996 if (!NonTag) return false;
12997
12998 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12999 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13000 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13001 BUD->setInvalidDecl();
13002 return true;
13003}
13004
13005/// Determine whether a direct base class is a virtual base class.
13006static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13007 if (!Derived->getNumVBases())
13008 return false;
13009 for (auto &B : Derived->bases())
13010 if (B.getType()->getAsCXXRecordDecl() == Base)
13011 return B.isVirtual();
13012 llvm_unreachable("not a direct base class");
13013}
13014
13015UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13016 NamedDecl *Orig,
13017 UsingShadowDecl *PrevDecl) {
13018 // If we resolved to another shadow declaration, just coalesce them.
13019 NamedDecl *Target = Orig;
13020 if (isa<UsingShadowDecl>(Val: Target)) {
13021 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13022 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13023 }
13024
13025 NamedDecl *NonTemplateTarget = Target;
13026 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13027 NonTemplateTarget = TargetTD->getTemplatedDecl();
13028
13029 UsingShadowDecl *Shadow;
13030 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13031 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13032 bool IsVirtualBase =
13033 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13034 Base: Using->getQualifier().getAsRecordDecl());
13035 Shadow = ConstructorUsingShadowDecl::Create(
13036 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13037 } else {
13038 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13039 Name: Target->getDeclName(), Introducer: BUD, Target);
13040 }
13041 BUD->addShadowDecl(S: Shadow);
13042
13043 Shadow->setAccess(BUD->getAccess());
13044 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13045 Shadow->setInvalidDecl();
13046
13047 Shadow->setPreviousDecl(PrevDecl);
13048
13049 if (S)
13050 PushOnScopeChains(D: Shadow, S);
13051 else
13052 CurContext->addDecl(D: Shadow);
13053
13054
13055 return Shadow;
13056}
13057
13058void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13059 if (Shadow->getDeclName().getNameKind() ==
13060 DeclarationName::CXXConversionFunctionName)
13061 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13062
13063 // Remove it from the DeclContext...
13064 Shadow->getDeclContext()->removeDecl(D: Shadow);
13065
13066 // ...and the scope, if applicable...
13067 if (S) {
13068 S->RemoveDecl(D: Shadow);
13069 IdResolver.RemoveDecl(D: Shadow);
13070 }
13071
13072 // ...and the using decl.
13073 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13074
13075 // TODO: complain somehow if Shadow was used. It shouldn't
13076 // be possible for this to happen, because...?
13077}
13078
13079/// Find the base specifier for a base class with the given type.
13080static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13081 QualType DesiredBase,
13082 bool &AnyDependentBases) {
13083 // Check whether the named type is a direct base class.
13084 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13085 for (auto &Base : Derived->bases()) {
13086 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13087 if (CanonicalDesiredBase == BaseType)
13088 return &Base;
13089 if (BaseType->isDependentType())
13090 AnyDependentBases = true;
13091 }
13092 return nullptr;
13093}
13094
13095namespace {
13096class UsingValidatorCCC final : public CorrectionCandidateCallback {
13097public:
13098 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13099 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13100 : HasTypenameKeyword(HasTypenameKeyword),
13101 IsInstantiation(IsInstantiation), OldNNS(NNS),
13102 RequireMemberOf(RequireMemberOf) {}
13103
13104 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13105 NamedDecl *ND = Candidate.getCorrectionDecl();
13106
13107 // Keywords are not valid here.
13108 if (!ND || isa<NamespaceDecl>(Val: ND))
13109 return false;
13110
13111 // Completely unqualified names are invalid for a 'using' declaration.
13112 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13113 return false;
13114
13115 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13116 // reject.
13117
13118 if (RequireMemberOf) {
13119 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13120 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13121 // No-one ever wants a using-declaration to name an injected-class-name
13122 // of a base class, unless they're declaring an inheriting constructor.
13123 ASTContext &Ctx = ND->getASTContext();
13124 if (!Ctx.getLangOpts().CPlusPlus11)
13125 return false;
13126 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13127
13128 // Check that the injected-class-name is named as a member of its own
13129 // type; we don't want to suggest 'using Derived::Base;', since that
13130 // means something else.
13131 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13132 ? Candidate.getCorrectionSpecifier()
13133 : OldNNS;
13134 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13135 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13136 return false;
13137
13138 // Check that this inheriting constructor declaration actually names a
13139 // direct base class of the current class.
13140 bool AnyDependentBases = false;
13141 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13142 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13143 AnyDependentBases) &&
13144 !AnyDependentBases)
13145 return false;
13146 } else {
13147 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13148 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13149 return false;
13150
13151 // FIXME: Check that the base class member is accessible?
13152 }
13153 } else {
13154 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13155 if (FoundRecord && FoundRecord->isInjectedClassName())
13156 return false;
13157 }
13158
13159 if (isa<TypeDecl>(Val: ND))
13160 return HasTypenameKeyword || !IsInstantiation;
13161
13162 return !HasTypenameKeyword;
13163 }
13164
13165 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13166 return std::make_unique<UsingValidatorCCC>(args&: *this);
13167 }
13168
13169private:
13170 bool HasTypenameKeyword;
13171 bool IsInstantiation;
13172 NestedNameSpecifier OldNNS;
13173 CXXRecordDecl *RequireMemberOf;
13174};
13175} // end anonymous namespace
13176
13177void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13178 // It is really dumb that we have to do this.
13179 LookupResult::Filter F = Previous.makeFilter();
13180 while (F.hasNext()) {
13181 NamedDecl *D = F.next();
13182 if (!isDeclInScope(D, Ctx: CurContext, S))
13183 F.erase();
13184 // If we found a local extern declaration that's not ordinarily visible,
13185 // and this declaration is being added to a non-block scope, ignore it.
13186 // We're only checking for scope conflicts here, not also for violations
13187 // of the linkage rules.
13188 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13189 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13190 F.erase();
13191 }
13192 F.done();
13193}
13194
13195NamedDecl *Sema::BuildUsingDeclaration(
13196 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13197 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13198 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13199 const ParsedAttributesView &AttrList, bool IsInstantiation,
13200 bool IsUsingIfExists) {
13201 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13202 SourceLocation IdentLoc = NameInfo.getLoc();
13203 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13204
13205 // FIXME: We ignore attributes for now.
13206
13207 // For an inheriting constructor declaration, the name of the using
13208 // declaration is the name of a constructor in this class, not in the
13209 // base class.
13210 DeclarationNameInfo UsingName = NameInfo;
13211 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13212 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13213 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13214 Ty: Context.getCanonicalTagType(TD: RD)));
13215
13216 // Do the redeclaration lookup in the current scope.
13217 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13218 RedeclarationKind::ForVisibleRedeclaration);
13219 Previous.setHideTags(false);
13220 if (S) {
13221 LookupName(R&: Previous, S);
13222
13223 FilterUsingLookup(S, Previous);
13224 } else {
13225 assert(IsInstantiation && "no scope in non-instantiation");
13226 if (CurContext->isRecord())
13227 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13228 else {
13229 // No redeclaration check is needed here; in non-member contexts we
13230 // diagnosed all possible conflicts with other using-declarations when
13231 // building the template:
13232 //
13233 // For a dependent non-type using declaration, the only valid case is
13234 // if we instantiate to a single enumerator. We check for conflicts
13235 // between shadow declarations we introduce, and we check in the template
13236 // definition for conflicts between a non-type using declaration and any
13237 // other declaration, which together covers all cases.
13238 //
13239 // A dependent typename using declaration will never successfully
13240 // instantiate, since it will always name a class member, so we reject
13241 // that in the template definition.
13242 }
13243 }
13244
13245 // Check for invalid redeclarations.
13246 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13247 SS, NameLoc: IdentLoc, Previous))
13248 return nullptr;
13249
13250 // 'using_if_exists' doesn't make sense on an inherited constructor.
13251 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13252 DeclarationName::CXXConstructorName) {
13253 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13254 return nullptr;
13255 }
13256
13257 DeclContext *LookupContext = computeDeclContext(SS);
13258 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13259 if (!LookupContext || EllipsisLoc.isValid()) {
13260 NamedDecl *D;
13261 // Dependent scope, or an unexpanded pack
13262 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13263 SS, NameInfo, NameLoc: IdentLoc))
13264 return nullptr;
13265
13266 if (Previous.isSingleResult() &&
13267 Previous.getFoundDecl()->isTemplateParameter())
13268 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13269
13270 if (HasTypenameKeyword) {
13271 // FIXME: not all declaration name kinds are legal here
13272 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13273 UsingLoc, TypenameLoc,
13274 QualifierLoc,
13275 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13276 EllipsisLoc);
13277 } else {
13278 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13279 QualifierLoc, NameInfo, EllipsisLoc);
13280 }
13281 D->setAccess(AS);
13282 CurContext->addDecl(D);
13283 ProcessDeclAttributeList(S, D, AttrList);
13284 return D;
13285 }
13286
13287 auto Build = [&](bool Invalid) {
13288 UsingDecl *UD =
13289 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13290 NameInfo: UsingName, HasTypenameKeyword);
13291 UD->setAccess(AS);
13292 CurContext->addDecl(D: UD);
13293 ProcessDeclAttributeList(S, D: UD, AttrList);
13294 UD->setInvalidDecl(Invalid);
13295 return UD;
13296 };
13297 auto BuildInvalid = [&]{ return Build(true); };
13298 auto BuildValid = [&]{ return Build(false); };
13299
13300 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13301 return BuildInvalid();
13302
13303 // Look up the target name.
13304 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13305
13306 // Unlike most lookups, we don't always want to hide tag
13307 // declarations: tag names are visible through the using declaration
13308 // even if hidden by ordinary names, *except* in a dependent context
13309 // where they may be used by two-phase lookup.
13310 if (!IsInstantiation)
13311 R.setHideTags(false);
13312
13313 // For the purposes of this lookup, we have a base object type
13314 // equal to that of the current context.
13315 if (CurContext->isRecord()) {
13316 R.setBaseObjectType(
13317 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13318 }
13319
13320 LookupQualifiedName(R, LookupCtx: LookupContext);
13321
13322 // Validate the context, now we have a lookup
13323 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13324 NameLoc: IdentLoc, R: &R))
13325 return nullptr;
13326
13327 if (R.empty() && IsUsingIfExists)
13328 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13329 Name: UsingName.getName()),
13330 AS: AS_public);
13331
13332 // Try to correct typos if possible. If constructor name lookup finds no
13333 // results, that means the named class has no explicit constructors, and we
13334 // suppressed declaring implicit ones (probably because it's dependent or
13335 // invalid).
13336 if (R.empty() &&
13337 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13338 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13339 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13340 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13341 auto *II = NameInfo.getName().getAsIdentifierInfo();
13342 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13343 CurContext->isStdNamespace() &&
13344 isa<TranslationUnitDecl>(Val: LookupContext) &&
13345 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13346 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13347 return nullptr;
13348 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13349 dyn_cast<CXXRecordDecl>(Val: CurContext));
13350 if (TypoCorrection Corrected =
13351 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13352 Mode: CorrectTypoKind::ErrorRecovery)) {
13353 // We reject candidates where DroppedSpecifier == true, hence the
13354 // literal '0' below.
13355 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13356 << NameInfo.getName() << LookupContext << 0
13357 << SS.getRange());
13358
13359 // If we picked a correction with no attached Decl we can't do anything
13360 // useful with it, bail out.
13361 NamedDecl *ND = Corrected.getCorrectionDecl();
13362 if (!ND)
13363 return BuildInvalid();
13364
13365 // If we corrected to an inheriting constructor, handle it as one.
13366 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13367 if (RD && RD->isInjectedClassName()) {
13368 // The parent of the injected class name is the class itself.
13369 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13370
13371 // Fix up the information we'll use to build the using declaration.
13372 if (Corrected.WillReplaceSpecifier()) {
13373 NestedNameSpecifierLocBuilder Builder;
13374 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13375 R: QualifierLoc.getSourceRange());
13376 QualifierLoc = Builder.getWithLocInContext(Context);
13377 }
13378
13379 // In this case, the name we introduce is the name of a derived class
13380 // constructor.
13381 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13382 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13383 Ty: Context.getCanonicalTagType(TD: CurClass)));
13384 UsingName.setNamedTypeInfo(nullptr);
13385 for (auto *Ctor : LookupConstructors(Class: RD))
13386 R.addDecl(D: Ctor);
13387 R.resolveKind();
13388 } else {
13389 // FIXME: Pick up all the declarations if we found an overloaded
13390 // function.
13391 UsingName.setName(ND->getDeclName());
13392 R.addDecl(D: ND);
13393 }
13394 } else {
13395 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13396 << NameInfo.getName() << LookupContext << SS.getRange();
13397 return BuildInvalid();
13398 }
13399 }
13400
13401 if (R.isAmbiguous())
13402 return BuildInvalid();
13403
13404 if (HasTypenameKeyword) {
13405 // If we asked for a typename and got a non-type decl, error out.
13406 if (!R.getAsSingle<TypeDecl>() &&
13407 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13408 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13409 for (const NamedDecl *D : R)
13410 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13411 DiagID: diag::note_using_decl_target);
13412 return BuildInvalid();
13413 }
13414 } else {
13415 // If we asked for a non-typename and we got a type, error out,
13416 // but only if this is an instantiation of an unresolved using
13417 // decl. Otherwise just silently find the type name.
13418 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13419 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13420 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13421 return BuildInvalid();
13422 }
13423 }
13424
13425 // C++14 [namespace.udecl]p6:
13426 // A using-declaration shall not name a namespace.
13427 if (R.getAsSingle<NamespaceDecl>()) {
13428 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13429 << SS.getRange();
13430 // Suggest using 'using namespace ...' instead.
13431 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13432 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13433 return BuildInvalid();
13434 }
13435
13436 UsingDecl *UD = BuildValid();
13437
13438 // Some additional rules apply to inheriting constructors.
13439 if (UsingName.getName().getNameKind() ==
13440 DeclarationName::CXXConstructorName) {
13441 // Suppress access diagnostics; the access check is instead performed at the
13442 // point of use for an inheriting constructor.
13443 R.suppressDiagnostics();
13444 if (CheckInheritingConstructorUsingDecl(UD))
13445 return UD;
13446 }
13447
13448 for (NamedDecl *D : R) {
13449 UsingShadowDecl *PrevDecl = nullptr;
13450 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13451 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13452 }
13453
13454 return UD;
13455}
13456
13457NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13458 SourceLocation UsingLoc,
13459 SourceLocation EnumLoc,
13460 SourceLocation NameLoc,
13461 TypeSourceInfo *EnumType,
13462 EnumDecl *ED) {
13463 bool Invalid = false;
13464
13465 if (CurContext->getRedeclContext()->isRecord()) {
13466 /// In class scope, check if this is a duplicate, for better a diagnostic.
13467 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13468 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13469 RedeclarationKind::ForVisibleRedeclaration);
13470
13471 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13472
13473 for (NamedDecl *D : Previous)
13474 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13475 if (UED->getEnumDecl() == ED) {
13476 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13477 << SourceRange(EnumLoc, NameLoc);
13478 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13479 Invalid = true;
13480 break;
13481 }
13482 }
13483
13484 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13485 Invalid = true;
13486
13487 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13488 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13489 UD->setAccess(AS);
13490 CurContext->addDecl(D: UD);
13491
13492 if (Invalid) {
13493 UD->setInvalidDecl();
13494 return UD;
13495 }
13496
13497 // Create the shadow decls for each enumerator
13498 for (EnumConstantDecl *EC : ED->enumerators()) {
13499 UsingShadowDecl *PrevDecl = nullptr;
13500 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13501 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13502 RedeclarationKind::ForVisibleRedeclaration);
13503 LookupName(R&: Previous, S);
13504 FilterUsingLookup(S, Previous);
13505
13506 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13507 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13508 }
13509
13510 return UD;
13511}
13512
13513NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13514 ArrayRef<NamedDecl *> Expansions) {
13515 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13516 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13517 isa<UsingPackDecl>(InstantiatedFrom));
13518
13519 auto *UPD =
13520 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13521 UPD->setAccess(InstantiatedFrom->getAccess());
13522 CurContext->addDecl(D: UPD);
13523 return UPD;
13524}
13525
13526bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13527 assert(!UD->hasTypename() && "expecting a constructor name");
13528
13529 QualType SourceType(UD->getQualifier().getAsType(), 0);
13530 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13531
13532 // Check whether the named type is a direct base class.
13533 bool AnyDependentBases = false;
13534 auto *Base =
13535 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13536 if (!Base && !AnyDependentBases) {
13537 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13538 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13539 UD->setInvalidDecl();
13540 return true;
13541 }
13542
13543 if (Base)
13544 Base->setInheritConstructors();
13545
13546 return false;
13547}
13548
13549bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13550 bool HasTypenameKeyword,
13551 const CXXScopeSpec &SS,
13552 SourceLocation NameLoc,
13553 const LookupResult &Prev) {
13554 NestedNameSpecifier Qual = SS.getScopeRep();
13555
13556 // C++03 [namespace.udecl]p8:
13557 // C++0x [namespace.udecl]p10:
13558 // A using-declaration is a declaration and can therefore be used
13559 // repeatedly where (and only where) multiple declarations are
13560 // allowed.
13561 //
13562 // That's in non-member contexts.
13563 if (!CurContext->getRedeclContext()->isRecord()) {
13564 // A dependent qualifier outside a class can only ever resolve to an
13565 // enumeration type. Therefore it conflicts with any other non-type
13566 // declaration in the same scope.
13567 // FIXME: How should we check for dependent type-type conflicts at block
13568 // scope?
13569 if (Qual.isDependent() && !HasTypenameKeyword) {
13570 for (auto *D : Prev) {
13571 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13572 bool OldCouldBeEnumerator =
13573 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13574 Diag(Loc: NameLoc,
13575 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13576 : diag::err_redefinition_different_kind)
13577 << Prev.getLookupName();
13578 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13579 return true;
13580 }
13581 }
13582 }
13583 return false;
13584 }
13585
13586 NestedNameSpecifier CNNS = Qual.getCanonical();
13587 for (const NamedDecl *D : Prev) {
13588 bool DTypename;
13589 NestedNameSpecifier DQual = std::nullopt;
13590 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13591 DTypename = UD->hasTypename();
13592 DQual = UD->getQualifier();
13593 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13594 DTypename = false;
13595 DQual = UD->getQualifier();
13596 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13597 DTypename = true;
13598 DQual = UD->getQualifier();
13599 } else
13600 continue;
13601
13602 // using decls differ if one says 'typename' and the other doesn't.
13603 // FIXME: non-dependent using decls?
13604 if (HasTypenameKeyword != DTypename) continue;
13605
13606 // using decls differ if they name different scopes (but note that
13607 // template instantiation can cause this check to trigger when it
13608 // didn't before instantiation).
13609 if (CNNS != DQual.getCanonical())
13610 continue;
13611
13612 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13613 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13614 return true;
13615 }
13616
13617 return false;
13618}
13619
13620bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13621 const CXXScopeSpec &SS,
13622 const DeclarationNameInfo &NameInfo,
13623 SourceLocation NameLoc,
13624 const LookupResult *R, const UsingDecl *UD) {
13625 DeclContext *NamedContext = computeDeclContext(SS);
13626 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13627 "resolvable context must have exactly one set of decls");
13628
13629 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13630 // relationship.
13631 bool Cxx20Enumerator = false;
13632 if (NamedContext) {
13633 EnumConstantDecl *EC = nullptr;
13634 if (R)
13635 EC = R->getAsSingle<EnumConstantDecl>();
13636 else if (UD && UD->shadow_size() == 1)
13637 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13638 if (EC)
13639 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13640
13641 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13642 // C++14 [namespace.udecl]p7:
13643 // A using-declaration shall not name a scoped enumerator.
13644 // C++20 p1099 permits enumerators.
13645 if (EC && R && ED->isScoped())
13646 Diag(Loc: SS.getBeginLoc(),
13647 DiagID: getLangOpts().CPlusPlus20
13648 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13649 : diag::ext_using_decl_scoped_enumerator)
13650 << SS.getRange();
13651
13652 // We want to consider the scope of the enumerator
13653 NamedContext = ED->getDeclContext();
13654 }
13655 }
13656
13657 if (!CurContext->isRecord()) {
13658 // C++03 [namespace.udecl]p3:
13659 // C++0x [namespace.udecl]p8:
13660 // A using-declaration for a class member shall be a member-declaration.
13661 // C++20 [namespace.udecl]p7
13662 // ... other than an enumerator ...
13663
13664 // If we weren't able to compute a valid scope, it might validly be a
13665 // dependent class or enumeration scope. If we have a 'typename' keyword,
13666 // the scope must resolve to a class type.
13667 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13668 : !HasTypename)
13669 return false; // OK
13670
13671 Diag(Loc: NameLoc,
13672 DiagID: Cxx20Enumerator
13673 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13674 : diag::err_using_decl_can_not_refer_to_class_member)
13675 << SS.getRange();
13676
13677 if (Cxx20Enumerator)
13678 return false; // OK
13679
13680 auto *RD = NamedContext
13681 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13682 : nullptr;
13683 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13684 // See if there's a helpful fixit
13685
13686 if (!R) {
13687 // We will have already diagnosed the problem on the template
13688 // definition, Maybe we should do so again?
13689 } else if (R->getAsSingle<TypeDecl>()) {
13690 if (getLangOpts().CPlusPlus11) {
13691 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13692 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13693 << diag::MemClassWorkaround::AliasDecl
13694 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13695 Code: NameInfo.getName().getAsString() +
13696 " = ");
13697 } else {
13698 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13699 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13700 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13701 << diag::MemClassWorkaround::TypedefDecl
13702 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13703 << FixItHint::CreateInsertion(
13704 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13705 }
13706 } else if (R->getAsSingle<VarDecl>()) {
13707 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13708 // repeating the type of the static data member here.
13709 FixItHint FixIt;
13710 if (getLangOpts().CPlusPlus11) {
13711 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13712 FixIt = FixItHint::CreateReplacement(
13713 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13714 }
13715
13716 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13717 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13718 } else if (R->getAsSingle<EnumConstantDecl>()) {
13719 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13720 // repeating the type of the enumeration here, and we can't do so if
13721 // the type is anonymous.
13722 FixItHint FixIt;
13723 if (getLangOpts().CPlusPlus11) {
13724 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13725 FixIt = FixItHint::CreateReplacement(
13726 RemoveRange: UsingLoc,
13727 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13728 }
13729
13730 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13731 << (getLangOpts().CPlusPlus11
13732 ? diag::MemClassWorkaround::ConstexprVar
13733 : diag::MemClassWorkaround::ConstVar)
13734 << FixIt;
13735 }
13736 }
13737
13738 return true; // Fail
13739 }
13740
13741 // If the named context is dependent, we can't decide much.
13742 if (!NamedContext) {
13743 // FIXME: in C++0x, we can diagnose if we can prove that the
13744 // nested-name-specifier does not refer to a base class, which is
13745 // still possible in some cases.
13746
13747 // Otherwise we have to conservatively report that things might be
13748 // okay.
13749 return false;
13750 }
13751
13752 // The current scope is a record.
13753 if (!NamedContext->isRecord()) {
13754 // Ideally this would point at the last name in the specifier,
13755 // but we don't have that level of source info.
13756 Diag(Loc: SS.getBeginLoc(),
13757 DiagID: Cxx20Enumerator
13758 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13759 : diag::err_using_decl_nested_name_specifier_is_not_class)
13760 << SS.getScopeRep() << SS.getRange();
13761
13762 if (Cxx20Enumerator)
13763 return false; // OK
13764
13765 return true;
13766 }
13767
13768 if (!NamedContext->isDependentContext() &&
13769 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13770 return true;
13771
13772 // C++26 [namespace.udecl]p3:
13773 // In a using-declaration used as a member-declaration, each
13774 // using-declarator shall either name an enumerator or have a
13775 // nested-name-specifier naming a base class of the current class
13776 // ([expr.prim.this]). ...
13777 // "have a nested-name-specifier naming a base class of the current class"
13778 // was introduced by CWG400.
13779
13780 if (cast<CXXRecordDecl>(Val: CurContext)
13781 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13782
13783 if (Cxx20Enumerator) {
13784 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13785 << SS.getScopeRep() << SS.getRange();
13786 return false;
13787 }
13788
13789 if (CurContext == NamedContext) {
13790 Diag(Loc: SS.getBeginLoc(),
13791 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13792 << SS.getRange();
13793 return true;
13794 }
13795
13796 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13797 Diag(Loc: SS.getBeginLoc(),
13798 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13799 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13800 << SS.getRange();
13801 }
13802 return true;
13803 }
13804
13805 return false;
13806}
13807
13808Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13809 MultiTemplateParamsArg TemplateParamLists,
13810 SourceLocation UsingLoc, UnqualifiedId &Name,
13811 const ParsedAttributesView &AttrList,
13812 TypeResult Type, Decl *DeclFromDeclSpec) {
13813
13814 if (Type.isInvalid())
13815 return nullptr;
13816
13817 bool Invalid = false;
13818 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13819 TypeSourceInfo *TInfo = nullptr;
13820 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13821
13822 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13823 return nullptr;
13824
13825 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13826 UPPC: UPPC_DeclarationType)) {
13827 Invalid = true;
13828 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13829 Loc: TInfo->getTypeLoc().getBeginLoc());
13830 }
13831
13832 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13833 TemplateParamLists.size()
13834 ? forRedeclarationInCurContext()
13835 : RedeclarationKind::ForVisibleRedeclaration);
13836 LookupName(R&: Previous, S);
13837
13838 // Warn about shadowing the name of a template parameter.
13839 if (Previous.isSingleResult() &&
13840 Previous.getFoundDecl()->isTemplateParameter()) {
13841 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13842 Previous.clear();
13843 }
13844
13845 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13846 "name in alias declaration must be an identifier");
13847 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13848 IdLoc: Name.StartLocation,
13849 Id: Name.Identifier, TInfo);
13850
13851 NewTD->setAccess(AS);
13852
13853 if (Invalid)
13854 NewTD->setInvalidDecl();
13855
13856 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13857 AddPragmaAttributes(S, D: NewTD);
13858 ProcessAPINotes(D: NewTD);
13859
13860 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13861 Invalid |= NewTD->isInvalidDecl();
13862
13863 // Get the innermost enclosing declaration scope.
13864 S = S->getDeclParent();
13865
13866 bool Redeclaration = false;
13867
13868 NamedDecl *NewND;
13869 if (TemplateParamLists.size()) {
13870 TypeAliasTemplateDecl *OldDecl = nullptr;
13871 TemplateParameterList *OldTemplateParams = nullptr;
13872
13873 if (TemplateParamLists.size() != 1) {
13874 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13875 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13876 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13877 Invalid = true;
13878 }
13879 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13880
13881 // Check that we can declare a template here.
13882 if (CheckTemplateDeclScope(S, TemplateParams))
13883 return nullptr;
13884
13885 // Only consider previous declarations in the same scope.
13886 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13887 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13888 if (!Previous.empty()) {
13889 Redeclaration = true;
13890
13891 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13892 if (!OldDecl && !Invalid) {
13893 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13894 << Name.Identifier;
13895
13896 NamedDecl *OldD = Previous.getRepresentativeDecl();
13897 if (OldD->getLocation().isValid())
13898 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13899
13900 Invalid = true;
13901 }
13902
13903 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13904 if (TemplateParameterListsAreEqual(New: TemplateParams,
13905 Old: OldDecl->getTemplateParameters(),
13906 /*Complain=*/true,
13907 Kind: TPL_TemplateMatch))
13908 OldTemplateParams =
13909 OldDecl->getMostRecentDecl()->getTemplateParameters();
13910 else
13911 Invalid = true;
13912
13913 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13914 if (!Invalid &&
13915 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13916 T2: NewTD->getUnderlyingType())) {
13917 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13918 // but we can't reasonably accept it.
13919 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13920 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13921 if (OldTD->getLocation().isValid())
13922 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13923 Invalid = true;
13924 }
13925 }
13926 }
13927
13928 // Merge any previous default template arguments into our parameters,
13929 // and check the parameter list.
13930 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13931 TPC: TPC_Other))
13932 return nullptr;
13933
13934 TypeAliasTemplateDecl *NewDecl =
13935 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13936 Name: Name.Identifier, Params: TemplateParams,
13937 Decl: NewTD);
13938 NewTD->setDescribedAliasTemplate(NewDecl);
13939
13940 NewDecl->setAccess(AS);
13941
13942 if (Invalid)
13943 NewDecl->setInvalidDecl();
13944 else if (OldDecl) {
13945 NewDecl->setPreviousDecl(OldDecl);
13946 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
13947 }
13948
13949 NewND = NewDecl;
13950 } else {
13951 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13952 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
13953 handleTagNumbering(Tag: TD, TagScope: S);
13954 }
13955 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
13956 NewND = NewTD;
13957 }
13958
13959 PushOnScopeChains(D: NewND, S);
13960 ActOnDocumentableDecl(D: NewND);
13961 return NewND;
13962}
13963
13964Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
13965 SourceLocation AliasLoc,
13966 IdentifierInfo *Alias, CXXScopeSpec &SS,
13967 SourceLocation IdentLoc,
13968 IdentifierInfo *Ident) {
13969
13970 // Lookup the namespace name.
13971 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
13972 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
13973
13974 if (R.isAmbiguous())
13975 return nullptr;
13976
13977 if (R.empty()) {
13978 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
13979 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
13980 return nullptr;
13981 }
13982 }
13983 assert(!R.isAmbiguous() && !R.empty());
13984 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
13985
13986 // Check if we have a previous declaration with the same name.
13987 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
13988 RedeclarationKind::ForVisibleRedeclaration);
13989 LookupName(R&: PrevR, S);
13990
13991 // Check we're not shadowing a template parameter.
13992 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
13993 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
13994 PrevR.clear();
13995 }
13996
13997 // Filter out any other lookup result from an enclosing scope.
13998 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13999 /*AllowInlineNamespace*/false);
14000
14001 // Find the previous declaration and check that we can redeclare it.
14002 NamespaceAliasDecl *Prev = nullptr;
14003 if (PrevR.isSingleResult()) {
14004 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14005 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14006 // We already have an alias with the same name that points to the same
14007 // namespace; check that it matches.
14008 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14009 Prev = AD;
14010 } else if (isVisible(D: PrevDecl)) {
14011 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14012 << Alias;
14013 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14014 << AD->getNamespace();
14015 return nullptr;
14016 }
14017 } else if (isVisible(D: PrevDecl)) {
14018 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14019 ? diag::err_redefinition
14020 : diag::err_redefinition_different_kind;
14021 Diag(Loc: AliasLoc, DiagID) << Alias;
14022 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14023 return nullptr;
14024 }
14025 }
14026
14027 // The use of a nested name specifier may trigger deprecation warnings.
14028 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14029
14030 NamespaceAliasDecl *AliasDecl =
14031 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14032 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14033 IdentLoc, Namespace: ND);
14034 if (Prev)
14035 AliasDecl->setPreviousDecl(Prev);
14036
14037 PushOnScopeChains(D: AliasDecl, S);
14038 return AliasDecl;
14039}
14040
14041namespace {
14042struct SpecialMemberExceptionSpecInfo
14043 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14044 SourceLocation Loc;
14045 Sema::ImplicitExceptionSpecification ExceptSpec;
14046
14047 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14048 CXXSpecialMemberKind CSM,
14049 Sema::InheritedConstructorInfo *ICI,
14050 SourceLocation Loc)
14051 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14052
14053 bool visitBase(CXXBaseSpecifier *Base);
14054 bool visitField(FieldDecl *FD);
14055
14056 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14057 unsigned Quals);
14058
14059 void visitSubobjectCall(Subobject Subobj,
14060 Sema::SpecialMemberOverloadResult SMOR);
14061};
14062}
14063
14064bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14065 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14066 if (!BaseClass)
14067 return false;
14068
14069 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14070 if (auto *BaseCtor = SMOR.getMethod()) {
14071 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14072 return false;
14073 }
14074
14075 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14076 return false;
14077}
14078
14079bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14080 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14081 FD->hasInClassInitializer()) {
14082 Expr *E = FD->getInClassInitializer();
14083 if (!E)
14084 // FIXME: It's a little wasteful to build and throw away a
14085 // CXXDefaultInitExpr here.
14086 // FIXME: We should have a single context note pointing at Loc, and
14087 // this location should be MD->getLocation() instead, since that's
14088 // the location where we actually use the default init expression.
14089 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
14090 if (E)
14091 ExceptSpec.CalledExpr(E);
14092 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14093 ->getAsCXXRecordDecl()) {
14094 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14095 }
14096 return false;
14097}
14098
14099void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14100 Subobject Subobj,
14101 unsigned Quals) {
14102 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14103 bool IsMutable = Field && Field->isMutable();
14104 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14105}
14106
14107void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14108 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14109 // Note, if lookup fails, it doesn't matter what exception specification we
14110 // choose because the special member will be deleted.
14111 if (CXXMethodDecl *MD = SMOR.getMethod())
14112 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14113}
14114
14115bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14116 llvm::APSInt Result;
14117 ExprResult Converted = CheckConvertedConstantExpression(
14118 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14119 ExplicitSpec.setExpr(Converted.get());
14120 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14121 ExplicitSpec.setKind(Result.getBoolValue()
14122 ? ExplicitSpecKind::ResolvedTrue
14123 : ExplicitSpecKind::ResolvedFalse);
14124 return true;
14125 }
14126 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14127 return false;
14128}
14129
14130ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14131 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14132 if (!ExplicitExpr->isTypeDependent())
14133 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14134 return ES;
14135}
14136
14137static Sema::ImplicitExceptionSpecification
14138ComputeDefaultedSpecialMemberExceptionSpec(
14139 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14140 Sema::InheritedConstructorInfo *ICI) {
14141 ComputingExceptionSpec CES(S, MD, Loc);
14142
14143 CXXRecordDecl *ClassDecl = MD->getParent();
14144
14145 // C++ [except.spec]p14:
14146 // An implicitly declared special member function (Clause 12) shall have an
14147 // exception-specification. [...]
14148 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14149 if (ClassDecl->isInvalidDecl())
14150 return Info.ExceptSpec;
14151
14152 // FIXME: If this diagnostic fires, we're probably missing a check for
14153 // attempting to resolve an exception specification before it's known
14154 // at a higher level.
14155 if (S.RequireCompleteType(Loc: MD->getLocation(),
14156 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14157 DiagID: diag::err_exception_spec_incomplete_type))
14158 return Info.ExceptSpec;
14159
14160 // C++1z [except.spec]p7:
14161 // [Look for exceptions thrown by] a constructor selected [...] to
14162 // initialize a potentially constructed subobject,
14163 // C++1z [except.spec]p8:
14164 // The exception specification for an implicitly-declared destructor, or a
14165 // destructor without a noexcept-specifier, is potentially-throwing if and
14166 // only if any of the destructors for any of its potentially constructed
14167 // subojects is potentially throwing.
14168 // FIXME: We respect the first rule but ignore the "potentially constructed"
14169 // in the second rule to resolve a core issue (no number yet) that would have
14170 // us reject:
14171 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14172 // struct B : A {};
14173 // struct C : B { void f(); };
14174 // ... due to giving B::~B() a non-throwing exception specification.
14175 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14176 : Info.VisitAllBases);
14177
14178 return Info.ExceptSpec;
14179}
14180
14181namespace {
14182/// RAII object to register a special member as being currently declared.
14183struct DeclaringSpecialMember {
14184 Sema &S;
14185 Sema::SpecialMemberDecl D;
14186 Sema::ContextRAII SavedContext;
14187 bool WasAlreadyBeingDeclared;
14188
14189 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14190 : S(S), D(RD, CSM), SavedContext(S, RD) {
14191 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14192 if (WasAlreadyBeingDeclared)
14193 // This almost never happens, but if it does, ensure that our cache
14194 // doesn't contain a stale result.
14195 S.SpecialMemberCache.clear();
14196 else {
14197 // Register a note to be produced if we encounter an error while
14198 // declaring the special member.
14199 Sema::CodeSynthesisContext Ctx;
14200 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14201 // FIXME: We don't have a location to use here. Using the class's
14202 // location maintains the fiction that we declare all special members
14203 // with the class, but (1) it's not clear that lying about that helps our
14204 // users understand what's going on, and (2) there may be outer contexts
14205 // on the stack (some of which are relevant) and printing them exposes
14206 // our lies.
14207 Ctx.PointOfInstantiation = RD->getLocation();
14208 Ctx.Entity = RD;
14209 Ctx.SpecialMember = CSM;
14210 S.pushCodeSynthesisContext(Ctx);
14211 }
14212 }
14213 ~DeclaringSpecialMember() {
14214 if (!WasAlreadyBeingDeclared) {
14215 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14216 S.popCodeSynthesisContext();
14217 }
14218 }
14219
14220 /// Are we already trying to declare this special member?
14221 bool isAlreadyBeingDeclared() const {
14222 return WasAlreadyBeingDeclared;
14223 }
14224};
14225}
14226
14227void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14228 // Look up any existing declarations, but don't trigger declaration of all
14229 // implicit special members with this name.
14230 DeclarationName Name = FD->getDeclName();
14231 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14232 RedeclarationKind::ForExternalRedeclaration);
14233 for (auto *D : FD->getParent()->lookup(Name))
14234 if (auto *Acceptable = R.getAcceptableDecl(D))
14235 R.addDecl(D: Acceptable);
14236 R.resolveKind();
14237 R.suppressDiagnostics();
14238
14239 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14240 DeclIsDefn: FD->isThisDeclarationADefinition());
14241}
14242
14243void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14244 QualType ResultTy,
14245 ArrayRef<QualType> Args) {
14246 // Build an exception specification pointing back at this constructor.
14247 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14248
14249 LangAS AS = getDefaultCXXMethodAddrSpace();
14250 if (AS != LangAS::Default) {
14251 EPI.TypeQuals.addAddressSpace(space: AS);
14252 }
14253
14254 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14255 SpecialMem->setType(QT);
14256
14257 // During template instantiation of implicit special member functions we need
14258 // a reliable TypeSourceInfo for the function prototype in order to allow
14259 // functions to be substituted.
14260 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14261 TypeSourceInfo *TSI =
14262 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14263 SpecialMem->setTypeSourceInfo(TSI);
14264 }
14265}
14266
14267CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14268 CXXRecordDecl *ClassDecl) {
14269 // C++ [class.ctor]p5:
14270 // A default constructor for a class X is a constructor of class X
14271 // that can be called without an argument. If there is no
14272 // user-declared constructor for class X, a default constructor is
14273 // implicitly declared. An implicitly-declared default constructor
14274 // is an inline public member of its class.
14275 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14276 "Should not build implicit default constructor!");
14277
14278 DeclaringSpecialMember DSM(*this, ClassDecl,
14279 CXXSpecialMemberKind::DefaultConstructor);
14280 if (DSM.isAlreadyBeingDeclared())
14281 return nullptr;
14282
14283 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14284 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14285
14286 // Create the actual constructor declaration.
14287 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14288 SourceLocation ClassLoc = ClassDecl->getLocation();
14289 DeclarationName Name
14290 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14291 DeclarationNameInfo NameInfo(Name, ClassLoc);
14292 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14293 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14294 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14295 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14296 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14297 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14298 : ConstexprSpecKind::Unspecified);
14299 DefaultCon->setAccess(AS_public);
14300 DefaultCon->setDefaulted();
14301
14302 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14303
14304 if (getLangOpts().CUDA)
14305 CUDA().inferTargetForImplicitSpecialMember(
14306 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14307 /* ConstRHS */ false,
14308 /* Diagnose */ false);
14309
14310 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14311 // constructors is easy to compute.
14312 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14313
14314 // Note that we have declared this constructor.
14315 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14316
14317 Scope *S = getScopeForContext(Ctx: ClassDecl);
14318 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14319
14320 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14321 CSM: CXXSpecialMemberKind::DefaultConstructor))
14322 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14323
14324 if (S)
14325 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14326 ClassDecl->addDecl(D: DefaultCon);
14327
14328 return DefaultCon;
14329}
14330
14331void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14332 CXXConstructorDecl *Constructor) {
14333 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14334 !Constructor->doesThisDeclarationHaveABody() &&
14335 !Constructor->isDeleted()) &&
14336 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14337 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14338 return;
14339
14340 CXXRecordDecl *ClassDecl = Constructor->getParent();
14341 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14342 if (ClassDecl->isInvalidDecl()) {
14343 return;
14344 }
14345
14346 SynthesizedFunctionScope Scope(*this, Constructor);
14347
14348 // The exception specification is needed because we are defining the
14349 // function.
14350 ResolveExceptionSpec(Loc: CurrentLocation,
14351 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14352 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14353
14354 // Add a context note for diagnostics produced after this point.
14355 Scope.addContextNote(UseLoc: CurrentLocation);
14356
14357 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14358 Constructor->setInvalidDecl();
14359 return;
14360 }
14361
14362 SourceLocation Loc = Constructor->getEndLoc().isValid()
14363 ? Constructor->getEndLoc()
14364 : Constructor->getLocation();
14365 Constructor->setBody(new (Context) CompoundStmt(Loc));
14366 Constructor->markUsed(C&: Context);
14367
14368 if (ASTMutationListener *L = getASTMutationListener()) {
14369 L->CompletedImplicitDefinition(D: Constructor);
14370 }
14371
14372 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14373}
14374
14375void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14376 // Perform any delayed checks on exception specifications.
14377 CheckDelayedMemberExceptionSpecs();
14378}
14379
14380/// Find or create the fake constructor we synthesize to model constructing an
14381/// object of a derived class via a constructor of a base class.
14382CXXConstructorDecl *
14383Sema::findInheritingConstructor(SourceLocation Loc,
14384 CXXConstructorDecl *BaseCtor,
14385 ConstructorUsingShadowDecl *Shadow) {
14386 CXXRecordDecl *Derived = Shadow->getParent();
14387 SourceLocation UsingLoc = Shadow->getLocation();
14388
14389 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14390 // For now we use the name of the base class constructor as a member of the
14391 // derived class to indicate a (fake) inherited constructor name.
14392 DeclarationName Name = BaseCtor->getDeclName();
14393
14394 // Check to see if we already have a fake constructor for this inherited
14395 // constructor call.
14396 for (NamedDecl *Ctor : Derived->lookup(Name))
14397 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14398 ->getInheritedConstructor()
14399 .getConstructor(),
14400 D2: BaseCtor))
14401 return cast<CXXConstructorDecl>(Val: Ctor);
14402
14403 DeclarationNameInfo NameInfo(Name, UsingLoc);
14404 TypeSourceInfo *TInfo =
14405 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14406 FunctionProtoTypeLoc ProtoLoc =
14407 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14408
14409 // Check the inherited constructor is valid and find the list of base classes
14410 // from which it was inherited.
14411 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14412
14413 bool Constexpr = BaseCtor->isConstexpr() &&
14414 defaultedSpecialMemberIsConstexpr(
14415 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14416 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14417
14418 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14419 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14420 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14421 /*isInline=*/true,
14422 /*isImplicitlyDeclared=*/true,
14423 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14424 Inherited: InheritedConstructor(Shadow, BaseCtor),
14425 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14426 if (Shadow->isInvalidDecl())
14427 DerivedCtor->setInvalidDecl();
14428
14429 // Build an unevaluated exception specification for this fake constructor.
14430 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14431 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14432 EPI.ExceptionSpec.Type = EST_Unevaluated;
14433 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14434 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14435 Args: FPT->getParamTypes(), EPI));
14436
14437 // Build the parameter declarations.
14438 SmallVector<ParmVarDecl *, 16> ParamDecls;
14439 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14440 TypeSourceInfo *TInfo =
14441 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14442 ParmVarDecl *PD = ParmVarDecl::Create(
14443 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14444 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14445 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14446 PD->setImplicit();
14447 // Ensure attributes are propagated onto parameters (this matters for
14448 // format, pass_object_size, ...).
14449 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14450 ParamDecls.push_back(Elt: PD);
14451 ProtoLoc.setParam(i: I, VD: PD);
14452 }
14453
14454 // Set up the new constructor.
14455 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14456 DerivedCtor->setAccess(BaseCtor->getAccess());
14457 DerivedCtor->setParams(ParamDecls);
14458 Derived->addDecl(D: DerivedCtor);
14459
14460 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14461 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14462 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14463
14464 return DerivedCtor;
14465}
14466
14467void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14468 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14469 Ctor->getInheritedConstructor().getShadowDecl());
14470 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14471 ICI: &ICI,
14472 /*Diagnose*/ true);
14473}
14474
14475void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14476 CXXConstructorDecl *Constructor) {
14477 CXXRecordDecl *ClassDecl = Constructor->getParent();
14478 assert(Constructor->getInheritedConstructor() &&
14479 !Constructor->doesThisDeclarationHaveABody() &&
14480 !Constructor->isDeleted());
14481 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14482 return;
14483
14484 // Initializations are performed "as if by a defaulted default constructor",
14485 // so enter the appropriate scope.
14486 SynthesizedFunctionScope Scope(*this, Constructor);
14487
14488 // The exception specification is needed because we are defining the
14489 // function.
14490 ResolveExceptionSpec(Loc: CurrentLocation,
14491 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14492 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14493
14494 // Add a context note for diagnostics produced after this point.
14495 Scope.addContextNote(UseLoc: CurrentLocation);
14496
14497 ConstructorUsingShadowDecl *Shadow =
14498 Constructor->getInheritedConstructor().getShadowDecl();
14499 CXXConstructorDecl *InheritedCtor =
14500 Constructor->getInheritedConstructor().getConstructor();
14501
14502 // [class.inhctor.init]p1:
14503 // initialization proceeds as if a defaulted default constructor is used to
14504 // initialize the D object and each base class subobject from which the
14505 // constructor was inherited
14506
14507 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14508 CXXRecordDecl *RD = Shadow->getParent();
14509 SourceLocation InitLoc = Shadow->getLocation();
14510
14511 // Build explicit initializers for all base classes from which the
14512 // constructor was inherited.
14513 SmallVector<CXXCtorInitializer*, 8> Inits;
14514 for (bool VBase : {false, true}) {
14515 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14516 if (B.isVirtual() != VBase)
14517 continue;
14518
14519 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14520 if (!BaseRD)
14521 continue;
14522
14523 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14524 if (!BaseCtor.first)
14525 continue;
14526
14527 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14528 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14529 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14530
14531 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14532 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14533 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14534 SourceLocation()));
14535 }
14536 }
14537
14538 // We now proceed as if for a defaulted default constructor, with the relevant
14539 // initializers replaced.
14540
14541 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14542 Constructor->setInvalidDecl();
14543 return;
14544 }
14545
14546 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14547 Constructor->markUsed(C&: Context);
14548
14549 if (ASTMutationListener *L = getASTMutationListener()) {
14550 L->CompletedImplicitDefinition(D: Constructor);
14551 }
14552
14553 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14554}
14555
14556CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14557 // C++ [class.dtor]p2:
14558 // If a class has no user-declared destructor, a destructor is
14559 // declared implicitly. An implicitly-declared destructor is an
14560 // inline public member of its class.
14561 assert(ClassDecl->needsImplicitDestructor());
14562
14563 DeclaringSpecialMember DSM(*this, ClassDecl,
14564 CXXSpecialMemberKind::Destructor);
14565 if (DSM.isAlreadyBeingDeclared())
14566 return nullptr;
14567
14568 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14569 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14570
14571 // Create the actual destructor declaration.
14572 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14573 SourceLocation ClassLoc = ClassDecl->getLocation();
14574 DeclarationName Name
14575 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14576 DeclarationNameInfo NameInfo(Name, ClassLoc);
14577 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14578 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14579 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14580 /*isInline=*/true,
14581 /*isImplicitlyDeclared=*/true,
14582 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14583 : ConstexprSpecKind::Unspecified);
14584 Destructor->setAccess(AS_public);
14585 Destructor->setDefaulted();
14586
14587 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14588
14589 if (getLangOpts().CUDA)
14590 CUDA().inferTargetForImplicitSpecialMember(
14591 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14592 /* ConstRHS */ false,
14593 /* Diagnose */ false);
14594
14595 // We don't need to use SpecialMemberIsTrivial here; triviality for
14596 // destructors is easy to compute.
14597 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14598 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14599 ClassDecl->hasTrivialDestructorForCall());
14600
14601 // Note that we have declared this destructor.
14602 ++getASTContext().NumImplicitDestructorsDeclared;
14603
14604 Scope *S = getScopeForContext(Ctx: ClassDecl);
14605 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14606
14607 // We can't check whether an implicit destructor is deleted before we complete
14608 // the definition of the class, because its validity depends on the alignment
14609 // of the class. We'll check this from ActOnFields once the class is complete.
14610 if (ClassDecl->isCompleteDefinition() &&
14611 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14612 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14613
14614 // Introduce this destructor into its scope.
14615 if (S)
14616 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14617 ClassDecl->addDecl(D: Destructor);
14618
14619 return Destructor;
14620}
14621
14622void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14623 CXXDestructorDecl *Destructor) {
14624 assert((Destructor->isDefaulted() &&
14625 !Destructor->doesThisDeclarationHaveABody() &&
14626 !Destructor->isDeleted()) &&
14627 "DefineImplicitDestructor - call it for implicit default dtor");
14628 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14629 return;
14630
14631 CXXRecordDecl *ClassDecl = Destructor->getParent();
14632 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14633
14634 SynthesizedFunctionScope Scope(*this, Destructor);
14635
14636 // The exception specification is needed because we are defining the
14637 // function.
14638 ResolveExceptionSpec(Loc: CurrentLocation,
14639 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14640 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14641
14642 // Add a context note for diagnostics produced after this point.
14643 Scope.addContextNote(UseLoc: CurrentLocation);
14644
14645 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14646 ClassDecl: Destructor->getParent());
14647
14648 if (CheckDestructor(Destructor)) {
14649 Destructor->setInvalidDecl();
14650 return;
14651 }
14652
14653 SourceLocation Loc = Destructor->getEndLoc().isValid()
14654 ? Destructor->getEndLoc()
14655 : Destructor->getLocation();
14656 Destructor->setBody(new (Context) CompoundStmt(Loc));
14657 Destructor->markUsed(C&: Context);
14658
14659 if (ASTMutationListener *L = getASTMutationListener()) {
14660 L->CompletedImplicitDefinition(D: Destructor);
14661 }
14662}
14663
14664void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14665 CXXDestructorDecl *Destructor) {
14666 if (Destructor->isInvalidDecl())
14667 return;
14668
14669 CXXRecordDecl *ClassDecl = Destructor->getParent();
14670 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14671 "implicit complete dtors unneeded outside MS ABI");
14672 assert(ClassDecl->getNumVBases() > 0 &&
14673 "complete dtor only exists for classes with vbases");
14674
14675 SynthesizedFunctionScope Scope(*this, Destructor);
14676
14677 // Add a context note for diagnostics produced after this point.
14678 Scope.addContextNote(UseLoc: CurrentLocation);
14679
14680 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14681}
14682
14683void Sema::ActOnFinishCXXMemberDecls() {
14684 // If the context is an invalid C++ class, just suppress these checks.
14685 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14686 if (Record->isInvalidDecl()) {
14687 DelayedOverridingExceptionSpecChecks.clear();
14688 DelayedEquivalentExceptionSpecChecks.clear();
14689 return;
14690 }
14691 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14692 }
14693}
14694
14695void Sema::ActOnFinishCXXNonNestedClass() {
14696 referenceDLLExportedClassMethods();
14697
14698 if (!DelayedDllExportMemberFunctions.empty()) {
14699 SmallVector<CXXMethodDecl*, 4> WorkList;
14700 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14701 for (CXXMethodDecl *M : WorkList) {
14702 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14703
14704 // Pass the method to the consumer to get emitted. This is not necessary
14705 // for explicit instantiation definitions, as they will get emitted
14706 // anyway.
14707 if (M->getParent()->getTemplateSpecializationKind() !=
14708 TSK_ExplicitInstantiationDefinition)
14709 ActOnFinishInlineFunctionDef(D: M);
14710 }
14711 }
14712}
14713
14714void Sema::referenceDLLExportedClassMethods() {
14715 if (!DelayedDllExportClasses.empty()) {
14716 // Calling ReferenceDllExportedMembers might cause the current function to
14717 // be called again, so use a local copy of DelayedDllExportClasses.
14718 SmallVector<CXXRecordDecl *, 4> WorkList;
14719 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14720 for (CXXRecordDecl *Class : WorkList)
14721 ReferenceDllExportedMembers(S&: *this, Class);
14722 }
14723}
14724
14725void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14726 assert(getLangOpts().CPlusPlus11 &&
14727 "adjusting dtor exception specs was introduced in c++11");
14728
14729 if (Destructor->isDependentContext())
14730 return;
14731
14732 // C++11 [class.dtor]p3:
14733 // A declaration of a destructor that does not have an exception-
14734 // specification is implicitly considered to have the same exception-
14735 // specification as an implicit declaration.
14736 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14737 if (DtorType->hasExceptionSpec())
14738 return;
14739
14740 // Replace the destructor's type, building off the existing one. Fortunately,
14741 // the only thing of interest in the destructor type is its extended info.
14742 // The return and arguments are fixed.
14743 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14744 EPI.ExceptionSpec.Type = EST_Unevaluated;
14745 EPI.ExceptionSpec.SourceDecl = Destructor;
14746 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14747
14748 // FIXME: If the destructor has a body that could throw, and the newly created
14749 // spec doesn't allow exceptions, we should emit a warning, because this
14750 // change in behavior can break conforming C++03 programs at runtime.
14751 // However, we don't have a body or an exception specification yet, so it
14752 // needs to be done somewhere else.
14753}
14754
14755namespace {
14756/// An abstract base class for all helper classes used in building the
14757// copy/move operators. These classes serve as factory functions and help us
14758// avoid using the same Expr* in the AST twice.
14759class ExprBuilder {
14760 ExprBuilder(const ExprBuilder&) = delete;
14761 ExprBuilder &operator=(const ExprBuilder&) = delete;
14762
14763protected:
14764 static Expr *assertNotNull(Expr *E) {
14765 assert(E && "Expression construction must not fail.");
14766 return E;
14767 }
14768
14769public:
14770 ExprBuilder() {}
14771 virtual ~ExprBuilder() {}
14772
14773 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14774};
14775
14776class RefBuilder: public ExprBuilder {
14777 VarDecl *Var;
14778 QualType VarType;
14779
14780public:
14781 Expr *build(Sema &S, SourceLocation Loc) const override {
14782 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14783 }
14784
14785 RefBuilder(VarDecl *Var, QualType VarType)
14786 : Var(Var), VarType(VarType) {}
14787};
14788
14789class ThisBuilder: public ExprBuilder {
14790public:
14791 Expr *build(Sema &S, SourceLocation Loc) const override {
14792 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14793 }
14794};
14795
14796class CastBuilder: public ExprBuilder {
14797 const ExprBuilder &Builder;
14798 QualType Type;
14799 ExprValueKind Kind;
14800 const CXXCastPath &Path;
14801
14802public:
14803 Expr *build(Sema &S, SourceLocation Loc) const override {
14804 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14805 CK: CK_UncheckedDerivedToBase, VK: Kind,
14806 BasePath: &Path).get());
14807 }
14808
14809 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14810 const CXXCastPath &Path)
14811 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14812};
14813
14814class DerefBuilder: public ExprBuilder {
14815 const ExprBuilder &Builder;
14816
14817public:
14818 Expr *build(Sema &S, SourceLocation Loc) const override {
14819 return assertNotNull(
14820 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14821 }
14822
14823 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14824};
14825
14826class MemberBuilder: public ExprBuilder {
14827 const ExprBuilder &Builder;
14828 QualType Type;
14829 CXXScopeSpec SS;
14830 bool IsArrow;
14831 LookupResult &MemberLookup;
14832
14833public:
14834 Expr *build(Sema &S, SourceLocation Loc) const override {
14835 return assertNotNull(E: S.BuildMemberReferenceExpr(
14836 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14837 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14838 }
14839
14840 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14841 LookupResult &MemberLookup)
14842 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14843 MemberLookup(MemberLookup) {}
14844};
14845
14846class MoveCastBuilder: public ExprBuilder {
14847 const ExprBuilder &Builder;
14848
14849public:
14850 Expr *build(Sema &S, SourceLocation Loc) const override {
14851 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14852 }
14853
14854 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14855};
14856
14857class LvalueConvBuilder: public ExprBuilder {
14858 const ExprBuilder &Builder;
14859
14860public:
14861 Expr *build(Sema &S, SourceLocation Loc) const override {
14862 return assertNotNull(
14863 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14864 }
14865
14866 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14867};
14868
14869class SubscriptBuilder: public ExprBuilder {
14870 const ExprBuilder &Base;
14871 const ExprBuilder &Index;
14872
14873public:
14874 Expr *build(Sema &S, SourceLocation Loc) const override {
14875 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14876 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14877 }
14878
14879 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14880 : Base(Base), Index(Index) {}
14881};
14882
14883} // end anonymous namespace
14884
14885/// When generating a defaulted copy or move assignment operator, if a field
14886/// should be copied with __builtin_memcpy rather than via explicit assignments,
14887/// do so. This optimization only applies for arrays of scalars, and for arrays
14888/// of class type where the selected copy/move-assignment operator is trivial.
14889static StmtResult
14890buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14891 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14892 // Compute the size of the memory buffer to be copied.
14893 QualType SizeType = S.Context.getSizeType();
14894 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14895 S.Context.getTypeSizeInChars(T).getQuantity());
14896
14897 // Take the address of the field references for "from" and "to". We
14898 // directly construct UnaryOperators here because semantic analysis
14899 // does not permit us to take the address of an xvalue.
14900 Expr *From = FromB.build(S, Loc);
14901 From = UnaryOperator::Create(
14902 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14903 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14904 Expr *To = ToB.build(S, Loc);
14905 To = UnaryOperator::Create(
14906 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14907 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14908
14909 bool NeedsCollectableMemCpy = false;
14910 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14911 NeedsCollectableMemCpy = RD->hasObjectMember();
14912
14913 // Create a reference to the __builtin_objc_memmove_collectable function
14914 StringRef MemCpyName = NeedsCollectableMemCpy ?
14915 "__builtin_objc_memmove_collectable" :
14916 "__builtin_memcpy";
14917 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14918 Sema::LookupOrdinaryName);
14919 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14920
14921 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14922 if (!MemCpy)
14923 // Something went horribly wrong earlier, and we will have complained
14924 // about it.
14925 return StmtError();
14926
14927 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
14928 VK: VK_PRValue, Loc, SS: nullptr);
14929 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14930
14931 Expr *CallArgs[] = {
14932 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14933 };
14934 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
14935 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
14936
14937 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14938 return Call.getAs<Stmt>();
14939}
14940
14941/// Builds a statement that copies/moves the given entity from \p From to
14942/// \c To.
14943///
14944/// This routine is used to copy/move the members of a class with an
14945/// implicitly-declared copy/move assignment operator. When the entities being
14946/// copied are arrays, this routine builds for loops to copy them.
14947///
14948/// \param S The Sema object used for type-checking.
14949///
14950/// \param Loc The location where the implicit copy/move is being generated.
14951///
14952/// \param T The type of the expressions being copied/moved. Both expressions
14953/// must have this type.
14954///
14955/// \param To The expression we are copying/moving to.
14956///
14957/// \param From The expression we are copying/moving from.
14958///
14959/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
14960/// Otherwise, it's a non-static member subobject.
14961///
14962/// \param Copying Whether we're copying or moving.
14963///
14964/// \param Depth Internal parameter recording the depth of the recursion.
14965///
14966/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
14967/// if a memcpy should be used instead.
14968static StmtResult
14969buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
14970 const ExprBuilder &To, const ExprBuilder &From,
14971 bool CopyingBaseSubobject, bool Copying,
14972 unsigned Depth = 0) {
14973 // C++11 [class.copy]p28:
14974 // Each subobject is assigned in the manner appropriate to its type:
14975 //
14976 // - if the subobject is of class type, as if by a call to operator= with
14977 // the subobject as the object expression and the corresponding
14978 // subobject of x as a single function argument (as if by explicit
14979 // qualification; that is, ignoring any possible virtual overriding
14980 // functions in more derived classes);
14981 //
14982 // C++03 [class.copy]p13:
14983 // - if the subobject is of class type, the copy assignment operator for
14984 // the class is used (as if by explicit qualification; that is,
14985 // ignoring any possible virtual overriding functions in more derived
14986 // classes);
14987 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
14988 // Look for operator=.
14989 DeclarationName Name
14990 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
14991 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
14992 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
14993
14994 // Prior to C++11, filter out any result that isn't a copy/move-assignment
14995 // operator.
14996 if (!S.getLangOpts().CPlusPlus11) {
14997 LookupResult::Filter F = OpLookup.makeFilter();
14998 while (F.hasNext()) {
14999 NamedDecl *D = F.next();
15000 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15001 if (Method->isCopyAssignmentOperator() ||
15002 (!Copying && Method->isMoveAssignmentOperator()))
15003 continue;
15004
15005 F.erase();
15006 }
15007 F.done();
15008 }
15009
15010 // Suppress the protected check (C++ [class.protected]) for each of the
15011 // assignment operators we found. This strange dance is required when
15012 // we're assigning via a base classes's copy-assignment operator. To
15013 // ensure that we're getting the right base class subobject (without
15014 // ambiguities), we need to cast "this" to that subobject type; to
15015 // ensure that we don't go through the virtual call mechanism, we need
15016 // to qualify the operator= name with the base class (see below). However,
15017 // this means that if the base class has a protected copy assignment
15018 // operator, the protected member access check will fail. So, we
15019 // rewrite "protected" access to "public" access in this case, since we
15020 // know by construction that we're calling from a derived class.
15021 if (CopyingBaseSubobject) {
15022 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15023 L != LEnd; ++L) {
15024 if (L.getAccess() == AS_protected)
15025 L.setAccess(AS_public);
15026 }
15027 }
15028
15029 // Create the nested-name-specifier that will be used to qualify the
15030 // reference to operator=; this is required to suppress the virtual
15031 // call mechanism.
15032 CXXScopeSpec SS;
15033 // FIXME: Don't canonicalize this.
15034 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15035 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15036
15037 // Create the reference to operator=.
15038 ExprResult OpEqualRef
15039 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15040 SS, /*TemplateKWLoc=*/SourceLocation(),
15041 /*FirstQualifierInScope=*/nullptr,
15042 R&: OpLookup,
15043 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15044 /*SuppressQualifierCheck=*/true);
15045 if (OpEqualRef.isInvalid())
15046 return StmtError();
15047
15048 // Build the call to the assignment operator.
15049
15050 Expr *FromInst = From.build(S, Loc);
15051 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15052 MemExpr: OpEqualRef.getAs<Expr>(),
15053 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15054 if (Call.isInvalid())
15055 return StmtError();
15056
15057 // If we built a call to a trivial 'operator=' while copying an array,
15058 // bail out. We'll replace the whole shebang with a memcpy.
15059 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15060 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15061 return StmtResult((Stmt*)nullptr);
15062
15063 // Convert to an expression-statement, and clean up any produced
15064 // temporaries.
15065 return S.ActOnExprStmt(Arg: Call);
15066 }
15067
15068 // - if the subobject is of scalar type, the built-in assignment
15069 // operator is used.
15070 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15071 if (!ArrayTy) {
15072 ExprResult Assignment = S.CreateBuiltinBinOp(
15073 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15074 if (Assignment.isInvalid())
15075 return StmtError();
15076 return S.ActOnExprStmt(Arg: Assignment);
15077 }
15078
15079 // - if the subobject is an array, each element is assigned, in the
15080 // manner appropriate to the element type;
15081
15082 // Construct a loop over the array bounds, e.g.,
15083 //
15084 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15085 //
15086 // that will copy each of the array elements.
15087 QualType SizeType = S.Context.getSizeType();
15088
15089 // Create the iteration variable.
15090 IdentifierInfo *IterationVarName = nullptr;
15091 {
15092 SmallString<8> Str;
15093 llvm::raw_svector_ostream OS(Str);
15094 OS << "__i" << Depth;
15095 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15096 }
15097 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15098 Id: IterationVarName, T: SizeType,
15099 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15100 S: SC_None);
15101
15102 // Initialize the iteration variable to zero.
15103 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15104 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15105
15106 // Creates a reference to the iteration variable.
15107 RefBuilder IterationVarRef(IterationVar, SizeType);
15108 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15109
15110 // Create the DeclStmt that holds the iteration variable.
15111 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15112
15113 // Subscript the "from" and "to" expressions with the iteration variable.
15114 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15115 MoveCastBuilder FromIndexMove(FromIndexCopy);
15116 const ExprBuilder *FromIndex;
15117 if (Copying)
15118 FromIndex = &FromIndexCopy;
15119 else
15120 FromIndex = &FromIndexMove;
15121
15122 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15123
15124 // Build the copy/move for an individual element of the array.
15125 StmtResult Copy =
15126 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15127 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15128 Copying, Depth: Depth + 1);
15129 // Bail out if copying fails or if we determined that we should use memcpy.
15130 if (Copy.isInvalid() || !Copy.get())
15131 return Copy;
15132
15133 // Create the comparison against the array bound.
15134 llvm::APInt Upper
15135 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15136 Expr *Comparison = BinaryOperator::Create(
15137 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15138 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15139 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15140 FPFeatures: S.CurFPFeatureOverrides());
15141
15142 // Create the pre-increment of the iteration variable. We can determine
15143 // whether the increment will overflow based on the value of the array
15144 // bound.
15145 Expr *Increment = UnaryOperator::Create(
15146 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15147 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15148
15149 // Construct the loop that copies all elements of this array.
15150 return S.ActOnForStmt(
15151 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15152 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15153 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15154}
15155
15156static StmtResult
15157buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15158 const ExprBuilder &To, const ExprBuilder &From,
15159 bool CopyingBaseSubobject, bool Copying) {
15160 // Maybe we should use a memcpy?
15161 if (T->isArrayType() && !T.isConstQualified() && !T.isVolatileQualified() &&
15162 T.isTriviallyCopyableType(Context: S.Context))
15163 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15164
15165 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15166 CopyingBaseSubobject,
15167 Copying, Depth: 0));
15168
15169 // If we ended up picking a trivial assignment operator for an array of a
15170 // non-trivially-copyable class type, just emit a memcpy.
15171 if (!Result.isInvalid() && !Result.get())
15172 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15173
15174 return Result;
15175}
15176
15177CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15178 // Note: The following rules are largely analoguous to the copy
15179 // constructor rules. Note that virtual bases are not taken into account
15180 // for determining the argument type of the operator. Note also that
15181 // operators taking an object instead of a reference are allowed.
15182 assert(ClassDecl->needsImplicitCopyAssignment());
15183
15184 DeclaringSpecialMember DSM(*this, ClassDecl,
15185 CXXSpecialMemberKind::CopyAssignment);
15186 if (DSM.isAlreadyBeingDeclared())
15187 return nullptr;
15188
15189 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15190 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15191 /*OwnsTag=*/false);
15192 LangAS AS = getDefaultCXXMethodAddrSpace();
15193 if (AS != LangAS::Default)
15194 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15195 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15196 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15197 if (Const)
15198 ArgType = ArgType.withConst();
15199
15200 ArgType = Context.getLValueReferenceType(T: ArgType);
15201
15202 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15203 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15204
15205 // An implicitly-declared copy assignment operator is an inline public
15206 // member of its class.
15207 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15208 SourceLocation ClassLoc = ClassDecl->getLocation();
15209 DeclarationNameInfo NameInfo(Name, ClassLoc);
15210 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15211 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15212 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15213 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15214 /*isInline=*/true,
15215 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15216 EndLocation: SourceLocation());
15217 CopyAssignment->setAccess(AS_public);
15218 CopyAssignment->setDefaulted();
15219 CopyAssignment->setImplicit();
15220
15221 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15222
15223 if (getLangOpts().CUDA)
15224 CUDA().inferTargetForImplicitSpecialMember(
15225 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15226 /* ConstRHS */ Const,
15227 /* Diagnose */ false);
15228
15229 // Add the parameter to the operator.
15230 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15231 StartLoc: ClassLoc, IdLoc: ClassLoc,
15232 /*Id=*/nullptr, T: ArgType,
15233 /*TInfo=*/nullptr, S: SC_None,
15234 DefArg: nullptr);
15235 CopyAssignment->setParams(FromParam);
15236
15237 CopyAssignment->setTrivial(
15238 ClassDecl->needsOverloadResolutionForCopyAssignment()
15239 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15240 CSM: CXXSpecialMemberKind::CopyAssignment)
15241 : ClassDecl->hasTrivialCopyAssignment());
15242
15243 // Note that we have added this copy-assignment operator.
15244 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15245
15246 Scope *S = getScopeForContext(Ctx: ClassDecl);
15247 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15248
15249 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15250 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15251 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15252 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15253 }
15254
15255 if (S)
15256 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15257 ClassDecl->addDecl(D: CopyAssignment);
15258
15259 return CopyAssignment;
15260}
15261
15262/// Diagnose an implicit copy operation for a class which is odr-used, but
15263/// which is deprecated because the class has a user-declared copy constructor,
15264/// copy assignment operator, or destructor.
15265static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15266 assert(CopyOp->isImplicit());
15267
15268 CXXRecordDecl *RD = CopyOp->getParent();
15269 CXXMethodDecl *UserDeclaredOperation = nullptr;
15270
15271 if (RD->hasUserDeclaredDestructor()) {
15272 UserDeclaredOperation = RD->getDestructor();
15273 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15274 RD->hasUserDeclaredCopyConstructor()) {
15275 // Find any user-declared copy constructor.
15276 for (auto *I : RD->ctors()) {
15277 if (I->isCopyConstructor()) {
15278 UserDeclaredOperation = I;
15279 break;
15280 }
15281 }
15282 assert(UserDeclaredOperation);
15283 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15284 RD->hasUserDeclaredCopyAssignment()) {
15285 // Find any user-declared move assignment operator.
15286 for (auto *I : RD->methods()) {
15287 if (I->isCopyAssignmentOperator()) {
15288 UserDeclaredOperation = I;
15289 break;
15290 }
15291 }
15292 assert(UserDeclaredOperation);
15293 }
15294
15295 if (UserDeclaredOperation) {
15296 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15297 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15298 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15299 unsigned DiagID =
15300 (UDOIsUserProvided && UDOIsDestructor)
15301 ? diag::warn_deprecated_copy_with_user_provided_dtor
15302 : (UDOIsUserProvided && !UDOIsDestructor)
15303 ? diag::warn_deprecated_copy_with_user_provided_copy
15304 : (!UDOIsUserProvided && UDOIsDestructor)
15305 ? diag::warn_deprecated_copy_with_dtor
15306 : diag::warn_deprecated_copy;
15307 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15308 << RD << IsCopyAssignment;
15309 }
15310}
15311
15312void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15313 CXXMethodDecl *CopyAssignOperator) {
15314 assert((CopyAssignOperator->isDefaulted() &&
15315 CopyAssignOperator->isOverloadedOperator() &&
15316 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15317 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15318 !CopyAssignOperator->isDeleted()) &&
15319 "DefineImplicitCopyAssignment called for wrong function");
15320 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15321 return;
15322
15323 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15324 if (ClassDecl->isInvalidDecl()) {
15325 CopyAssignOperator->setInvalidDecl();
15326 return;
15327 }
15328
15329 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15330
15331 // The exception specification is needed because we are defining the
15332 // function.
15333 ResolveExceptionSpec(Loc: CurrentLocation,
15334 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15335
15336 // Add a context note for diagnostics produced after this point.
15337 Scope.addContextNote(UseLoc: CurrentLocation);
15338
15339 // C++11 [class.copy]p18:
15340 // The [definition of an implicitly declared copy assignment operator] is
15341 // deprecated if the class has a user-declared copy constructor or a
15342 // user-declared destructor.
15343 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15344 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15345
15346 // C++0x [class.copy]p30:
15347 // The implicitly-defined or explicitly-defaulted copy assignment operator
15348 // for a non-union class X performs memberwise copy assignment of its
15349 // subobjects. The direct base classes of X are assigned first, in the
15350 // order of their declaration in the base-specifier-list, and then the
15351 // immediate non-static data members of X are assigned, in the order in
15352 // which they were declared in the class definition.
15353
15354 // The statements that form the synthesized function body.
15355 SmallVector<Stmt*, 8> Statements;
15356
15357 // The parameter for the "other" object, which we are copying from.
15358 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15359 Qualifiers OtherQuals = Other->getType().getQualifiers();
15360 QualType OtherRefType = Other->getType();
15361 if (OtherRefType->isLValueReferenceType()) {
15362 OtherRefType = OtherRefType->getPointeeType();
15363 OtherQuals = OtherRefType.getQualifiers();
15364 }
15365
15366 // Our location for everything implicitly-generated.
15367 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15368 ? CopyAssignOperator->getEndLoc()
15369 : CopyAssignOperator->getLocation();
15370
15371 // Builds a DeclRefExpr for the "other" object.
15372 RefBuilder OtherRef(Other, OtherRefType);
15373
15374 // Builds the function object parameter.
15375 std::optional<ThisBuilder> This;
15376 std::optional<DerefBuilder> DerefThis;
15377 std::optional<RefBuilder> ExplicitObject;
15378 bool IsArrow = false;
15379 QualType ObjectType;
15380 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15381 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15382 if (ObjectType->isReferenceType())
15383 ObjectType = ObjectType->getPointeeType();
15384 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15385 } else {
15386 ObjectType = getCurrentThisType();
15387 This.emplace();
15388 DerefThis.emplace(args&: *This);
15389 IsArrow = !LangOpts.HLSL;
15390 }
15391 ExprBuilder &ObjectParameter =
15392 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15393 : static_cast<ExprBuilder &>(*This);
15394
15395 // Assign base classes.
15396 bool Invalid = false;
15397 for (auto &Base : ClassDecl->bases()) {
15398 // Form the assignment:
15399 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15400 QualType BaseType = Base.getType().getUnqualifiedType();
15401 if (!BaseType->isRecordType()) {
15402 Invalid = true;
15403 continue;
15404 }
15405
15406 CXXCastPath BasePath;
15407 BasePath.push_back(Elt: &Base);
15408
15409 // Construct the "from" expression, which is an implicit cast to the
15410 // appropriately-qualified base type.
15411 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15412 VK_LValue, BasePath);
15413
15414 // Dereference "this".
15415 CastBuilder To(
15416 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15417 : static_cast<ExprBuilder &>(*DerefThis),
15418 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15419 VK_LValue, BasePath);
15420
15421 // Build the copy.
15422 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15423 To, From,
15424 /*CopyingBaseSubobject=*/true,
15425 /*Copying=*/true);
15426 if (Copy.isInvalid()) {
15427 CopyAssignOperator->setInvalidDecl();
15428 return;
15429 }
15430
15431 // Success! Record the copy.
15432 Statements.push_back(Elt: Copy.getAs<Expr>());
15433 }
15434
15435 // Assign non-static members.
15436 for (auto *Field : ClassDecl->fields()) {
15437 // FIXME: We should form some kind of AST representation for the implied
15438 // memcpy in a union copy operation.
15439 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15440 continue;
15441
15442 if (Field->isInvalidDecl()) {
15443 Invalid = true;
15444 continue;
15445 }
15446
15447 // Check for members of reference type; we can't copy those.
15448 if (Field->getType()->isReferenceType()) {
15449 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15450 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15451 << Field->getDeclName();
15452 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15453 Invalid = true;
15454 continue;
15455 }
15456
15457 // Check for members of const-qualified, non-class type.
15458 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15459 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15460 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15461 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15462 << Field->getDeclName();
15463 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15464 Invalid = true;
15465 continue;
15466 }
15467
15468 // Suppress assigning zero-width bitfields.
15469 if (Field->isZeroLengthBitField())
15470 continue;
15471
15472 QualType FieldType = Field->getType().getNonReferenceType();
15473 if (FieldType->isIncompleteArrayType()) {
15474 assert(ClassDecl->hasFlexibleArrayMember() &&
15475 "Incomplete array type is not valid");
15476 continue;
15477 }
15478
15479 // Build references to the field in the object we're copying from and to.
15480 CXXScopeSpec SS; // Intentionally empty
15481 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15482 LookupMemberName);
15483 MemberLookup.addDecl(D: Field);
15484 MemberLookup.resolveKind();
15485
15486 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15487 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15488 // Build the copy of this field.
15489 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15490 To, From,
15491 /*CopyingBaseSubobject=*/false,
15492 /*Copying=*/true);
15493 if (Copy.isInvalid()) {
15494 CopyAssignOperator->setInvalidDecl();
15495 return;
15496 }
15497
15498 // Success! Record the copy.
15499 Statements.push_back(Elt: Copy.getAs<Stmt>());
15500 }
15501
15502 if (!Invalid) {
15503 // Add a "return *this;"
15504 Expr *ThisExpr =
15505 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15506 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15507 : static_cast<ExprBuilder &>(*DerefThis))
15508 .build(S&: *this, Loc);
15509 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15510 if (Return.isInvalid())
15511 Invalid = true;
15512 else
15513 Statements.push_back(Elt: Return.getAs<Stmt>());
15514 }
15515
15516 if (Invalid) {
15517 CopyAssignOperator->setInvalidDecl();
15518 return;
15519 }
15520
15521 StmtResult Body;
15522 {
15523 CompoundScopeRAII CompoundScope(*this);
15524 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15525 /*isStmtExpr=*/false);
15526 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15527 }
15528 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15529 CopyAssignOperator->markUsed(C&: Context);
15530
15531 if (ASTMutationListener *L = getASTMutationListener()) {
15532 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15533 }
15534}
15535
15536CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15537 assert(ClassDecl->needsImplicitMoveAssignment());
15538
15539 DeclaringSpecialMember DSM(*this, ClassDecl,
15540 CXXSpecialMemberKind::MoveAssignment);
15541 if (DSM.isAlreadyBeingDeclared())
15542 return nullptr;
15543
15544 // Note: The following rules are largely analoguous to the move
15545 // constructor rules.
15546
15547 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15548 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15549 /*OwnsTag=*/false);
15550 LangAS AS = getDefaultCXXMethodAddrSpace();
15551 if (AS != LangAS::Default)
15552 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15553 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15554 ArgType = Context.getRValueReferenceType(T: ArgType);
15555
15556 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15557 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15558
15559 // An implicitly-declared move assignment operator is an inline public
15560 // member of its class.
15561 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15562 SourceLocation ClassLoc = ClassDecl->getLocation();
15563 DeclarationNameInfo NameInfo(Name, ClassLoc);
15564 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15565 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15566 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15567 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15568 /*isInline=*/true,
15569 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15570 EndLocation: SourceLocation());
15571 MoveAssignment->setAccess(AS_public);
15572 MoveAssignment->setDefaulted();
15573 MoveAssignment->setImplicit();
15574
15575 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15576
15577 if (getLangOpts().CUDA)
15578 CUDA().inferTargetForImplicitSpecialMember(
15579 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15580 /* ConstRHS */ false,
15581 /* Diagnose */ false);
15582
15583 // Add the parameter to the operator.
15584 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15585 StartLoc: ClassLoc, IdLoc: ClassLoc,
15586 /*Id=*/nullptr, T: ArgType,
15587 /*TInfo=*/nullptr, S: SC_None,
15588 DefArg: nullptr);
15589 MoveAssignment->setParams(FromParam);
15590
15591 MoveAssignment->setTrivial(
15592 ClassDecl->needsOverloadResolutionForMoveAssignment()
15593 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15594 CSM: CXXSpecialMemberKind::MoveAssignment)
15595 : ClassDecl->hasTrivialMoveAssignment());
15596
15597 // Note that we have added this copy-assignment operator.
15598 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15599
15600 Scope *S = getScopeForContext(Ctx: ClassDecl);
15601 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15602
15603 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15604 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15605 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15606 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15607 }
15608
15609 if (S)
15610 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15611 ClassDecl->addDecl(D: MoveAssignment);
15612
15613 return MoveAssignment;
15614}
15615
15616/// Check if we're implicitly defining a move assignment operator for a class
15617/// with virtual bases. Such a move assignment might move-assign the virtual
15618/// base multiple times.
15619static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15620 SourceLocation CurrentLocation) {
15621 assert(!Class->isDependentContext() && "should not define dependent move");
15622
15623 // Only a virtual base could get implicitly move-assigned multiple times.
15624 // Only a non-trivial move assignment can observe this. We only want to
15625 // diagnose if we implicitly define an assignment operator that assigns
15626 // two base classes, both of which move-assign the same virtual base.
15627 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15628 Class->getNumBases() < 2)
15629 return;
15630
15631 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15632 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15633 VBaseMap VBases;
15634
15635 for (auto &BI : Class->bases()) {
15636 Worklist.push_back(Elt: &BI);
15637 while (!Worklist.empty()) {
15638 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15639 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15640
15641 // If the base has no non-trivial move assignment operators,
15642 // we don't care about moves from it.
15643 if (!Base->hasNonTrivialMoveAssignment())
15644 continue;
15645
15646 // If there's nothing virtual here, skip it.
15647 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15648 continue;
15649
15650 // If we're not actually going to call a move assignment for this base,
15651 // or the selected move assignment is trivial, skip it.
15652 Sema::SpecialMemberOverloadResult SMOR =
15653 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15654 /*ConstArg*/ false, /*VolatileArg*/ false,
15655 /*RValueThis*/ true, /*ConstThis*/ false,
15656 /*VolatileThis*/ false);
15657 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15658 !SMOR.getMethod()->isMoveAssignmentOperator())
15659 continue;
15660
15661 if (BaseSpec->isVirtual()) {
15662 // We're going to move-assign this virtual base, and its move
15663 // assignment operator is not trivial. If this can happen for
15664 // multiple distinct direct bases of Class, diagnose it. (If it
15665 // only happens in one base, we'll diagnose it when synthesizing
15666 // that base class's move assignment operator.)
15667 CXXBaseSpecifier *&Existing =
15668 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15669 .first->second;
15670 if (Existing && Existing != &BI) {
15671 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15672 << Class << Base;
15673 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15674 << (Base->getCanonicalDecl() ==
15675 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15676 << Base << Existing->getType() << Existing->getSourceRange();
15677 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15678 << (Base->getCanonicalDecl() ==
15679 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15680 << Base << BI.getType() << BaseSpec->getSourceRange();
15681
15682 // Only diagnose each vbase once.
15683 Existing = nullptr;
15684 }
15685 } else {
15686 // Only walk over bases that have defaulted move assignment operators.
15687 // We assume that any user-provided move assignment operator handles
15688 // the multiple-moves-of-vbase case itself somehow.
15689 if (!SMOR.getMethod()->isDefaulted())
15690 continue;
15691
15692 // We're going to move the base classes of Base. Add them to the list.
15693 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15694 }
15695 }
15696 }
15697}
15698
15699void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15700 CXXMethodDecl *MoveAssignOperator) {
15701 assert((MoveAssignOperator->isDefaulted() &&
15702 MoveAssignOperator->isOverloadedOperator() &&
15703 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15704 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15705 !MoveAssignOperator->isDeleted()) &&
15706 "DefineImplicitMoveAssignment called for wrong function");
15707 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15708 return;
15709
15710 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15711 if (ClassDecl->isInvalidDecl()) {
15712 MoveAssignOperator->setInvalidDecl();
15713 return;
15714 }
15715
15716 // C++0x [class.copy]p28:
15717 // The implicitly-defined or move assignment operator for a non-union class
15718 // X performs memberwise move assignment of its subobjects. The direct base
15719 // classes of X are assigned first, in the order of their declaration in the
15720 // base-specifier-list, and then the immediate non-static data members of X
15721 // are assigned, in the order in which they were declared in the class
15722 // definition.
15723
15724 // Issue a warning if our implicit move assignment operator will move
15725 // from a virtual base more than once.
15726 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15727
15728 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15729
15730 // The exception specification is needed because we are defining the
15731 // function.
15732 ResolveExceptionSpec(Loc: CurrentLocation,
15733 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15734
15735 // Add a context note for diagnostics produced after this point.
15736 Scope.addContextNote(UseLoc: CurrentLocation);
15737
15738 // The statements that form the synthesized function body.
15739 SmallVector<Stmt*, 8> Statements;
15740
15741 // The parameter for the "other" object, which we are move from.
15742 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15743 QualType OtherRefType =
15744 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15745
15746 // Our location for everything implicitly-generated.
15747 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15748 ? MoveAssignOperator->getEndLoc()
15749 : MoveAssignOperator->getLocation();
15750
15751 // Builds a reference to the "other" object.
15752 RefBuilder OtherRef(Other, OtherRefType);
15753 // Cast to rvalue.
15754 MoveCastBuilder MoveOther(OtherRef);
15755
15756 // Builds the function object parameter.
15757 std::optional<ThisBuilder> This;
15758 std::optional<DerefBuilder> DerefThis;
15759 std::optional<RefBuilder> ExplicitObject;
15760 QualType ObjectType;
15761 bool IsArrow = false;
15762 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15763 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15764 if (ObjectType->isReferenceType())
15765 ObjectType = ObjectType->getPointeeType();
15766 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15767 } else {
15768 ObjectType = getCurrentThisType();
15769 This.emplace();
15770 DerefThis.emplace(args&: *This);
15771 IsArrow = !getLangOpts().HLSL;
15772 }
15773 ExprBuilder &ObjectParameter =
15774 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15775
15776 // Assign base classes.
15777 bool Invalid = false;
15778 for (auto &Base : ClassDecl->bases()) {
15779 // C++11 [class.copy]p28:
15780 // It is unspecified whether subobjects representing virtual base classes
15781 // are assigned more than once by the implicitly-defined copy assignment
15782 // operator.
15783 // FIXME: Do not assign to a vbase that will be assigned by some other base
15784 // class. For a move-assignment, this can result in the vbase being moved
15785 // multiple times.
15786
15787 // Form the assignment:
15788 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15789 QualType BaseType = Base.getType().getUnqualifiedType();
15790 if (!BaseType->isRecordType()) {
15791 Invalid = true;
15792 continue;
15793 }
15794
15795 CXXCastPath BasePath;
15796 BasePath.push_back(Elt: &Base);
15797
15798 // Construct the "from" expression, which is an implicit cast to the
15799 // appropriately-qualified base type.
15800 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15801
15802 // Implicitly cast "this" to the appropriately-qualified base type.
15803 // Dereference "this".
15804 CastBuilder To(
15805 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15806 : static_cast<ExprBuilder &>(*DerefThis),
15807 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15808 VK_LValue, BasePath);
15809
15810 // Build the move.
15811 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15812 To, From,
15813 /*CopyingBaseSubobject=*/true,
15814 /*Copying=*/false);
15815 if (Move.isInvalid()) {
15816 MoveAssignOperator->setInvalidDecl();
15817 return;
15818 }
15819
15820 // Success! Record the move.
15821 Statements.push_back(Elt: Move.getAs<Expr>());
15822 }
15823
15824 // Assign non-static members.
15825 for (auto *Field : ClassDecl->fields()) {
15826 // FIXME: We should form some kind of AST representation for the implied
15827 // memcpy in a union copy operation.
15828 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15829 continue;
15830
15831 if (Field->isInvalidDecl()) {
15832 Invalid = true;
15833 continue;
15834 }
15835
15836 // Check for members of reference type; we can't move those.
15837 if (Field->getType()->isReferenceType()) {
15838 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15839 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15840 << Field->getDeclName();
15841 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15842 Invalid = true;
15843 continue;
15844 }
15845
15846 // Check for members of const-qualified, non-class type.
15847 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15848 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15849 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15850 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15851 << Field->getDeclName();
15852 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15853 Invalid = true;
15854 continue;
15855 }
15856
15857 // Suppress assigning zero-width bitfields.
15858 if (Field->isZeroLengthBitField())
15859 continue;
15860
15861 QualType FieldType = Field->getType().getNonReferenceType();
15862 if (FieldType->isIncompleteArrayType()) {
15863 assert(ClassDecl->hasFlexibleArrayMember() &&
15864 "Incomplete array type is not valid");
15865 continue;
15866 }
15867
15868 // Build references to the field in the object we're copying from and to.
15869 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15870 LookupMemberName);
15871 MemberLookup.addDecl(D: Field);
15872 MemberLookup.resolveKind();
15873 MemberBuilder From(MoveOther, OtherRefType,
15874 /*IsArrow=*/false, MemberLookup);
15875 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15876
15877 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15878 "Member reference with rvalue base must be rvalue except for reference "
15879 "members, which aren't allowed for move assignment.");
15880
15881 // Build the move of this field.
15882 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15883 To, From,
15884 /*CopyingBaseSubobject=*/false,
15885 /*Copying=*/false);
15886 if (Move.isInvalid()) {
15887 MoveAssignOperator->setInvalidDecl();
15888 return;
15889 }
15890
15891 // Success! Record the copy.
15892 Statements.push_back(Elt: Move.getAs<Stmt>());
15893 }
15894
15895 if (!Invalid) {
15896 // Add a "return *this;"
15897 Expr *ThisExpr =
15898 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15899 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15900 : static_cast<ExprBuilder &>(*DerefThis))
15901 .build(S&: *this, Loc);
15902
15903 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15904 if (Return.isInvalid())
15905 Invalid = true;
15906 else
15907 Statements.push_back(Elt: Return.getAs<Stmt>());
15908 }
15909
15910 if (Invalid) {
15911 MoveAssignOperator->setInvalidDecl();
15912 return;
15913 }
15914
15915 StmtResult Body;
15916 {
15917 CompoundScopeRAII CompoundScope(*this);
15918 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15919 /*isStmtExpr=*/false);
15920 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15921 }
15922 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15923 MoveAssignOperator->markUsed(C&: Context);
15924
15925 if (ASTMutationListener *L = getASTMutationListener()) {
15926 L->CompletedImplicitDefinition(D: MoveAssignOperator);
15927 }
15928}
15929
15930CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15931 CXXRecordDecl *ClassDecl) {
15932 // C++ [class.copy]p4:
15933 // If the class definition does not explicitly declare a copy
15934 // constructor, one is declared implicitly.
15935 assert(ClassDecl->needsImplicitCopyConstructor());
15936
15937 DeclaringSpecialMember DSM(*this, ClassDecl,
15938 CXXSpecialMemberKind::CopyConstructor);
15939 if (DSM.isAlreadyBeingDeclared())
15940 return nullptr;
15941
15942 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15943 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15944 /*OwnsTag=*/false);
15945 QualType ArgType = ClassType;
15946 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15947 if (Const)
15948 ArgType = ArgType.withConst();
15949
15950 LangAS AS = getDefaultCXXMethodAddrSpace();
15951 if (AS != LangAS::Default)
15952 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15953
15954 ArgType = Context.getLValueReferenceType(T: ArgType);
15955
15956 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15957 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
15958
15959 DeclarationName Name
15960 = Context.DeclarationNames.getCXXConstructorName(
15961 Ty: Context.getCanonicalType(T: ClassType));
15962 SourceLocation ClassLoc = ClassDecl->getLocation();
15963 DeclarationNameInfo NameInfo(Name, ClassLoc);
15964
15965 // An implicitly-declared copy constructor is an inline public
15966 // member of its class.
15967 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
15968 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
15969 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15970 /*isInline=*/true,
15971 /*isImplicitlyDeclared=*/true,
15972 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
15973 : ConstexprSpecKind::Unspecified);
15974 CopyConstructor->setAccess(AS_public);
15975 CopyConstructor->setDefaulted();
15976
15977 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
15978
15979 if (getLangOpts().CUDA)
15980 CUDA().inferTargetForImplicitSpecialMember(
15981 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
15982 /* ConstRHS */ Const,
15983 /* Diagnose */ false);
15984
15985 // During template instantiation of special member functions we need a
15986 // reliable TypeSourceInfo for the parameter types in order to allow functions
15987 // to be substituted.
15988 TypeSourceInfo *TSI = nullptr;
15989 if (inTemplateInstantiation() && ClassDecl->isLambda())
15990 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
15991
15992 // Add the parameter to the constructor.
15993 ParmVarDecl *FromParam =
15994 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
15995 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
15996 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
15997 CopyConstructor->setParams(FromParam);
15998
15999 CopyConstructor->setTrivial(
16000 ClassDecl->needsOverloadResolutionForCopyConstructor()
16001 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16002 CSM: CXXSpecialMemberKind::CopyConstructor)
16003 : ClassDecl->hasTrivialCopyConstructor());
16004
16005 CopyConstructor->setTrivialForCall(
16006 ClassDecl->hasAttr<TrivialABIAttr>() ||
16007 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16008 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16009 CSM: CXXSpecialMemberKind::CopyConstructor,
16010 TAH: TrivialABIHandling::ConsiderTrivialABI)
16011 : ClassDecl->hasTrivialCopyConstructorForCall()));
16012
16013 // Note that we have declared this constructor.
16014 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16015
16016 Scope *S = getScopeForContext(Ctx: ClassDecl);
16017 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16018
16019 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16020 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16021 ClassDecl->setImplicitCopyConstructorIsDeleted();
16022 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16023 }
16024
16025 if (S)
16026 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16027 ClassDecl->addDecl(D: CopyConstructor);
16028
16029 return CopyConstructor;
16030}
16031
16032void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16033 CXXConstructorDecl *CopyConstructor) {
16034 assert((CopyConstructor->isDefaulted() &&
16035 CopyConstructor->isCopyConstructor() &&
16036 !CopyConstructor->doesThisDeclarationHaveABody() &&
16037 !CopyConstructor->isDeleted()) &&
16038 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16039 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16040 return;
16041
16042 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16043 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16044
16045 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16046
16047 // The exception specification is needed because we are defining the
16048 // function.
16049 ResolveExceptionSpec(Loc: CurrentLocation,
16050 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16051 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16052
16053 // Add a context note for diagnostics produced after this point.
16054 Scope.addContextNote(UseLoc: CurrentLocation);
16055
16056 // C++11 [class.copy]p7:
16057 // The [definition of an implicitly declared copy constructor] is
16058 // deprecated if the class has a user-declared copy assignment operator
16059 // or a user-declared destructor.
16060 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16061 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16062
16063 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16064 CopyConstructor->setInvalidDecl();
16065 } else {
16066 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16067 ? CopyConstructor->getEndLoc()
16068 : CopyConstructor->getLocation();
16069 Sema::CompoundScopeRAII CompoundScope(*this);
16070 CopyConstructor->setBody(
16071 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16072 CopyConstructor->markUsed(C&: Context);
16073 }
16074
16075 if (ASTMutationListener *L = getASTMutationListener()) {
16076 L->CompletedImplicitDefinition(D: CopyConstructor);
16077 }
16078}
16079
16080CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16081 CXXRecordDecl *ClassDecl) {
16082 assert(ClassDecl->needsImplicitMoveConstructor());
16083
16084 DeclaringSpecialMember DSM(*this, ClassDecl,
16085 CXXSpecialMemberKind::MoveConstructor);
16086 if (DSM.isAlreadyBeingDeclared())
16087 return nullptr;
16088
16089 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16090 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16091 /*OwnsTag=*/false);
16092
16093 QualType ArgType = ClassType;
16094 LangAS AS = getDefaultCXXMethodAddrSpace();
16095 if (AS != LangAS::Default)
16096 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16097 ArgType = Context.getRValueReferenceType(T: ArgType);
16098
16099 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16100 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16101
16102 DeclarationName Name
16103 = Context.DeclarationNames.getCXXConstructorName(
16104 Ty: Context.getCanonicalType(T: ClassType));
16105 SourceLocation ClassLoc = ClassDecl->getLocation();
16106 DeclarationNameInfo NameInfo(Name, ClassLoc);
16107
16108 // C++11 [class.copy]p11:
16109 // An implicitly-declared copy/move constructor is an inline public
16110 // member of its class.
16111 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16112 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16113 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16114 /*isInline=*/true,
16115 /*isImplicitlyDeclared=*/true,
16116 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16117 : ConstexprSpecKind::Unspecified);
16118 MoveConstructor->setAccess(AS_public);
16119 MoveConstructor->setDefaulted();
16120
16121 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16122
16123 if (getLangOpts().CUDA)
16124 CUDA().inferTargetForImplicitSpecialMember(
16125 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16126 /* ConstRHS */ false,
16127 /* Diagnose */ false);
16128
16129 // Add the parameter to the constructor.
16130 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16131 StartLoc: ClassLoc, IdLoc: ClassLoc,
16132 /*IdentifierInfo=*/Id: nullptr,
16133 T: ArgType, /*TInfo=*/nullptr,
16134 S: SC_None, DefArg: nullptr);
16135 MoveConstructor->setParams(FromParam);
16136
16137 MoveConstructor->setTrivial(
16138 ClassDecl->needsOverloadResolutionForMoveConstructor()
16139 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16140 CSM: CXXSpecialMemberKind::MoveConstructor)
16141 : ClassDecl->hasTrivialMoveConstructor());
16142
16143 MoveConstructor->setTrivialForCall(
16144 ClassDecl->hasAttr<TrivialABIAttr>() ||
16145 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16146 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16147 CSM: CXXSpecialMemberKind::MoveConstructor,
16148 TAH: TrivialABIHandling::ConsiderTrivialABI)
16149 : ClassDecl->hasTrivialMoveConstructorForCall()));
16150
16151 // Note that we have declared this constructor.
16152 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16153
16154 Scope *S = getScopeForContext(Ctx: ClassDecl);
16155 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16156
16157 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16158 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16159 ClassDecl->setImplicitMoveConstructorIsDeleted();
16160 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16161 }
16162
16163 if (S)
16164 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16165 ClassDecl->addDecl(D: MoveConstructor);
16166
16167 return MoveConstructor;
16168}
16169
16170void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16171 CXXConstructorDecl *MoveConstructor) {
16172 assert((MoveConstructor->isDefaulted() &&
16173 MoveConstructor->isMoveConstructor() &&
16174 !MoveConstructor->doesThisDeclarationHaveABody() &&
16175 !MoveConstructor->isDeleted()) &&
16176 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16177 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16178 return;
16179
16180 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16181 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16182
16183 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16184
16185 // The exception specification is needed because we are defining the
16186 // function.
16187 ResolveExceptionSpec(Loc: CurrentLocation,
16188 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16189 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16190
16191 // Add a context note for diagnostics produced after this point.
16192 Scope.addContextNote(UseLoc: CurrentLocation);
16193
16194 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16195 MoveConstructor->setInvalidDecl();
16196 } else {
16197 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16198 ? MoveConstructor->getEndLoc()
16199 : MoveConstructor->getLocation();
16200 Sema::CompoundScopeRAII CompoundScope(*this);
16201 MoveConstructor->setBody(
16202 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16203 MoveConstructor->markUsed(C&: Context);
16204 }
16205
16206 if (ASTMutationListener *L = getASTMutationListener()) {
16207 L->CompletedImplicitDefinition(D: MoveConstructor);
16208 }
16209}
16210
16211bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16212 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16213}
16214
16215void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16216 SourceLocation CurrentLocation,
16217 CXXConversionDecl *Conv) {
16218 SynthesizedFunctionScope Scope(*this, Conv);
16219 assert(!Conv->getReturnType()->isUndeducedType());
16220
16221 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16222 CallingConv CC =
16223 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16224
16225 CXXRecordDecl *Lambda = Conv->getParent();
16226 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16227 FunctionDecl *Invoker =
16228 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16229 ? CallOp
16230 : Lambda->getLambdaStaticInvoker(CC);
16231
16232 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16233 CallOp = InstantiateFunctionDeclaration(
16234 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16235 if (!CallOp)
16236 return;
16237
16238 if (CallOp != Invoker) {
16239 Invoker = InstantiateFunctionDeclaration(
16240 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16241 Loc: CurrentLocation);
16242 if (!Invoker)
16243 return;
16244 }
16245 }
16246
16247 if (CallOp->isInvalidDecl())
16248 return;
16249
16250 // Mark the call operator referenced (and add to pending instantiations
16251 // if necessary).
16252 // For both the conversion and static-invoker template specializations
16253 // we construct their body's in this function, so no need to add them
16254 // to the PendingInstantiations.
16255 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16256
16257 if (Invoker != CallOp) {
16258 // Fill in the __invoke function with a dummy implementation. IR generation
16259 // will fill in the actual details. Update its type in case it contained
16260 // an 'auto'.
16261 Invoker->markUsed(C&: Context);
16262 Invoker->setReferenced();
16263 Invoker->setType(Conv->getReturnType()->getPointeeType());
16264 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16265 }
16266
16267 // Construct the body of the conversion function { return __invoke; }.
16268 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16269 Loc: Conv->getLocation());
16270 assert(FunctionRef && "Can't refer to __invoke function?");
16271 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16272 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16273 LB: Conv->getLocation(), RB: Conv->getLocation()));
16274 Conv->markUsed(C&: Context);
16275 Conv->setReferenced();
16276
16277 if (ASTMutationListener *L = getASTMutationListener()) {
16278 L->CompletedImplicitDefinition(D: Conv);
16279 if (Invoker != CallOp)
16280 L->CompletedImplicitDefinition(D: Invoker);
16281 }
16282}
16283
16284void Sema::DefineImplicitLambdaToBlockPointerConversion(
16285 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16286 assert(!Conv->getParent()->isGenericLambda());
16287
16288 SynthesizedFunctionScope Scope(*this, Conv);
16289
16290 // Copy-initialize the lambda object as needed to capture it.
16291 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16292 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16293
16294 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16295 ConvLocation: Conv->getLocation(),
16296 Conv, Src: DerefThis);
16297
16298 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16299 // behavior. Note that only the general conversion function does this
16300 // (since it's unusable otherwise); in the case where we inline the
16301 // block literal, it has block literal lifetime semantics.
16302 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16303 BuildBlock = ImplicitCastExpr::Create(
16304 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16305 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16306
16307 if (BuildBlock.isInvalid()) {
16308 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16309 Conv->setInvalidDecl();
16310 return;
16311 }
16312
16313 // Create the return statement that returns the block from the conversion
16314 // function.
16315 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16316 if (Return.isInvalid()) {
16317 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16318 Conv->setInvalidDecl();
16319 return;
16320 }
16321
16322 // Set the body of the conversion function.
16323 Stmt *ReturnS = Return.get();
16324 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16325 LB: Conv->getLocation(), RB: Conv->getLocation()));
16326 Conv->markUsed(C&: Context);
16327
16328 // We're done; notify the mutation listener, if any.
16329 if (ASTMutationListener *L = getASTMutationListener()) {
16330 L->CompletedImplicitDefinition(D: Conv);
16331 }
16332}
16333
16334/// Determine whether the given list arguments contains exactly one
16335/// "real" (non-default) argument.
16336static bool hasOneRealArgument(MultiExprArg Args) {
16337 switch (Args.size()) {
16338 case 0:
16339 return false;
16340
16341 default:
16342 if (!Args[1]->isDefaultArgument())
16343 return false;
16344
16345 [[fallthrough]];
16346 case 1:
16347 return !Args[0]->isDefaultArgument();
16348 }
16349
16350 return false;
16351}
16352
16353ExprResult Sema::BuildCXXConstructExpr(
16354 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16355 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16356 bool HadMultipleCandidates, bool IsListInitialization,
16357 bool IsStdInitListInitialization, bool RequiresZeroInit,
16358 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16359 bool Elidable = false;
16360
16361 // C++0x [class.copy]p34:
16362 // When certain criteria are met, an implementation is allowed to
16363 // omit the copy/move construction of a class object, even if the
16364 // copy/move constructor and/or destructor for the object have
16365 // side effects. [...]
16366 // - when a temporary class object that has not been bound to a
16367 // reference (12.2) would be copied/moved to a class object
16368 // with the same cv-unqualified type, the copy/move operation
16369 // can be omitted by constructing the temporary object
16370 // directly into the target of the omitted copy/move
16371 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16372 // FIXME: Converting constructors should also be accepted.
16373 // But to fix this, the logic that digs down into a CXXConstructExpr
16374 // to find the source object needs to handle it.
16375 // Right now it assumes the source object is passed directly as the
16376 // first argument.
16377 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16378 Expr *SubExpr = ExprArgs[0];
16379 // FIXME: Per above, this is also incorrect if we want to accept
16380 // converting constructors, as isTemporaryObject will
16381 // reject temporaries with different type from the
16382 // CXXRecord itself.
16383 Elidable = SubExpr->isTemporaryObject(
16384 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16385 }
16386
16387 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16388 FoundDecl, Constructor,
16389 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16390 IsListInitialization,
16391 IsStdInitListInitialization, RequiresZeroInit,
16392 ConstructKind, ParenRange);
16393}
16394
16395ExprResult Sema::BuildCXXConstructExpr(
16396 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16397 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16398 bool HadMultipleCandidates, bool IsListInitialization,
16399 bool IsStdInitListInitialization, bool RequiresZeroInit,
16400 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16401 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16402 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16403 // The only way to get here is if we did overload resolution to find the
16404 // shadow decl, so we don't need to worry about re-checking the trailing
16405 // requires clause.
16406 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16407 return ExprError();
16408 }
16409
16410 return BuildCXXConstructExpr(
16411 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16412 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16413 RequiresZeroInit, ConstructKind, ParenRange);
16414}
16415
16416/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16417/// including handling of its default argument expressions.
16418ExprResult Sema::BuildCXXConstructExpr(
16419 SourceLocation ConstructLoc, QualType DeclInitType,
16420 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16421 bool HadMultipleCandidates, bool IsListInitialization,
16422 bool IsStdInitListInitialization, bool RequiresZeroInit,
16423 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16424 assert(declaresSameEntity(
16425 Constructor->getParent(),
16426 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16427 "given constructor for wrong type");
16428 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16429 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16430 return ExprError();
16431
16432 return CheckForImmediateInvocation(
16433 E: CXXConstructExpr::Create(
16434 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16435 HadMultipleCandidates, ListInitialization: IsListInitialization,
16436 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16437 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16438 Decl: Constructor);
16439}
16440
16441void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16442 if (VD->isInvalidDecl()) return;
16443 // If initializing the variable failed, don't also diagnose problems with
16444 // the destructor, they're likely related.
16445 if (VD->getInit() && VD->getInit()->containsErrors())
16446 return;
16447
16448 ClassDecl = ClassDecl->getDefinitionOrSelf();
16449 if (ClassDecl->isInvalidDecl()) return;
16450 if (ClassDecl->hasIrrelevantDestructor()) return;
16451 if (ClassDecl->isDependentContext()) return;
16452
16453 if (VD->isNoDestroy(getASTContext()))
16454 return;
16455
16456 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16457 // The result of `LookupDestructor` might be nullptr if the destructor is
16458 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16459 // will not be selected by `CXXRecordDecl::getDestructor()`.
16460 if (!Destructor)
16461 return;
16462 // If this is an array, we'll require the destructor during initialization, so
16463 // we can skip over this. We still want to emit exit-time destructor warnings
16464 // though.
16465 if (!VD->getType()->isArrayType()) {
16466 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16467 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16468 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16469 << VD->getDeclName() << VD->getType());
16470 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16471 }
16472
16473 if (Destructor->isTrivial()) return;
16474
16475 // If the destructor is constexpr, check whether the variable has constant
16476 // destruction now.
16477 if (Destructor->isConstexpr()) {
16478 bool HasConstantInit = false;
16479 if (VD->getInit() && !VD->getInit()->isValueDependent())
16480 HasConstantInit = VD->evaluateValue();
16481 SmallVector<PartialDiagnosticAt, 8> Notes;
16482 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16483 HasConstantInit) {
16484 Diag(Loc: VD->getLocation(),
16485 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16486 for (const PartialDiagnosticAt &Note : Notes)
16487 Diag(Loc: Note.first, PD: Note.second);
16488 }
16489 }
16490
16491 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16492 return;
16493
16494 // Emit warning for non-trivial dtor in global scope (a real global,
16495 // class-static, function-static).
16496 if (!VD->hasAttr<AlwaysDestroyAttr>())
16497 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16498
16499 // TODO: this should be re-enabled for static locals by !CXAAtExit
16500 if (!VD->isStaticLocal())
16501 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16502}
16503
16504bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16505 QualType DeclInitType, MultiExprArg ArgsPtr,
16506 SourceLocation Loc,
16507 SmallVectorImpl<Expr *> &ConvertedArgs,
16508 bool AllowExplicit,
16509 bool IsListInitialization) {
16510 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16511 unsigned NumArgs = ArgsPtr.size();
16512 Expr **Args = ArgsPtr.data();
16513
16514 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16515 unsigned NumParams = Proto->getNumParams();
16516
16517 // If too few arguments are available, we'll fill in the rest with defaults.
16518 if (NumArgs < NumParams)
16519 ConvertedArgs.reserve(N: NumParams);
16520 else
16521 ConvertedArgs.reserve(N: NumArgs);
16522
16523 VariadicCallType CallType = Proto->isVariadic()
16524 ? VariadicCallType::Constructor
16525 : VariadicCallType::DoesNotApply;
16526 SmallVector<Expr *, 8> AllArgs;
16527 bool Invalid = GatherArgumentsForCall(
16528 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16529 CallType, AllowExplicit, IsListInitialization);
16530 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16531
16532 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16533
16534 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16535 Proto, Loc);
16536
16537 return Invalid;
16538}
16539
16540TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16541 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16542 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16543}
16544
16545FunctionDecl *
16546Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16547 QualType DeallocType, SourceLocation Loc) {
16548 if (DeallocType.isNull())
16549 return nullptr;
16550
16551 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16552 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16553 return nullptr;
16554
16555 if (FnDecl->isVariadic())
16556 return nullptr;
16557
16558 unsigned NumParams = FnDecl->getNumParams();
16559 constexpr unsigned RequiredParameterCount =
16560 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16561 // A usual deallocation function has no placement parameters
16562 if (NumParams != RequiredParameterCount)
16563 return nullptr;
16564
16565 // A type aware allocation is only usual if the only dependent parameter is
16566 // the first parameter.
16567 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16568 P: [](const ParmVarDecl *ParamDecl) {
16569 return ParamDecl->getType()->isDependentType();
16570 }))
16571 return nullptr;
16572
16573 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16574 if (SpecializedTypeIdentity.isNull())
16575 return nullptr;
16576
16577 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16578 ArgTypes.reserve(N: NumParams);
16579
16580 // The first parameter to a type aware operator delete is by definition the
16581 // type-identity argument, so we explicitly set this to the target
16582 // type-identity type, the remaining usual parameters should then simply match
16583 // the type declared in the function template.
16584 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16585 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16586 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16587
16588 FunctionProtoType::ExtProtoInfo EPI;
16589 QualType ExpectedFunctionType =
16590 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16591 sema::TemplateDeductionInfo Info(Loc);
16592 FunctionDecl *Result;
16593 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16594 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16595 return nullptr;
16596 return Result;
16597}
16598
16599static inline bool
16600CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16601 const FunctionDecl *FnDecl) {
16602 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16603 if (isa<NamespaceDecl>(Val: DC)) {
16604 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16605 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16606 << FnDecl->getDeclName();
16607 }
16608
16609 if (isa<TranslationUnitDecl>(Val: DC) &&
16610 FnDecl->getStorageClass() == SC_Static) {
16611 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16612 DiagID: diag::err_operator_new_delete_declared_static)
16613 << FnDecl->getDeclName();
16614 }
16615
16616 return false;
16617}
16618
16619static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16620 const PointerType *PtrTy) {
16621 auto &Ctx = SemaRef.Context;
16622 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16623 PtrQuals.removeAddressSpace();
16624 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16625 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16626}
16627
16628enum class AllocationOperatorKind { New, Delete };
16629
16630static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16631 const FunctionDecl *FD,
16632 bool *WasMalformed) {
16633 const Decl *MalformedDecl = nullptr;
16634 if (FD->getNumParams() > 0 &&
16635 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16636 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16637 return true;
16638
16639 if (!MalformedDecl)
16640 return false;
16641
16642 if (WasMalformed)
16643 *WasMalformed = true;
16644
16645 return true;
16646}
16647
16648static bool isDestroyingDeleteT(QualType Type) {
16649 auto *RD = Type->getAsCXXRecordDecl();
16650 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16651 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16652}
16653
16654static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16655 const FunctionDecl *FD) {
16656 // C++ P0722:
16657 // Within a class C, a single object deallocation function with signature
16658 // (T, std::destroying_delete_t, <more params>)
16659 // is a destroying operator delete.
16660 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16661 SemaRef, FD, /*WasMalformed=*/nullptr);
16662 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16663 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16664 FD->getNumParams() > DestroyingDeleteIdx &&
16665 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16666}
16667
16668static inline bool CheckOperatorNewDeleteTypes(
16669 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16670 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16671 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16672 auto NormalizeType = [&SemaRef](QualType T) {
16673 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16674 // The operator is valid on any address space for OpenCL.
16675 // Drop address space from actual and expected result types.
16676 if (const auto PtrTy = T->template getAs<PointerType>())
16677 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16678 }
16679 return SemaRef.Context.getCanonicalType(T);
16680 };
16681
16682 const unsigned NumParams = FnDecl->getNumParams();
16683 unsigned FirstNonTypeParam = 0;
16684 bool MalformedTypeIdentity = false;
16685 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16686 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16687 unsigned MinimumMandatoryArgumentCount = 1;
16688 unsigned SizeParameterIndex = 0;
16689 if (IsPotentiallyTypeAware) {
16690 // We don't emit this diagnosis for template instantiations as we will
16691 // have already emitted it for the original template declaration.
16692 if (!FnDecl->isTemplateInstantiation())
16693 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16694
16695 if (OperatorKind == AllocationOperatorKind::New) {
16696 SizeParameterIndex = 1;
16697 MinimumMandatoryArgumentCount =
16698 FunctionDecl::RequiredTypeAwareNewParameterCount;
16699 } else {
16700 SizeParameterIndex = 2;
16701 MinimumMandatoryArgumentCount =
16702 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16703 }
16704 FirstNonTypeParam = 1;
16705 }
16706
16707 bool IsPotentiallyDestroyingDelete =
16708 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16709
16710 if (IsPotentiallyDestroyingDelete) {
16711 ++MinimumMandatoryArgumentCount;
16712 ++SizeParameterIndex;
16713 }
16714
16715 if (NumParams < MinimumMandatoryArgumentCount)
16716 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16717 DiagID: diag::err_operator_new_delete_too_few_parameters)
16718 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16719 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16720
16721 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16722 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16723 if (ParamDecl->hasDefaultArg())
16724 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16725 DiagID: diag::err_operator_new_default_arg)
16726 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16727 }
16728
16729 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16730 QualType CanResultType = NormalizeType(FnType->getReturnType());
16731 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16732 QualType CanExpectedSizeOrAddressParamType =
16733 NormalizeType(ExpectedSizeOrAddressParamType);
16734
16735 // Check that the result type is what we expect.
16736 if (CanResultType != CanExpectedResultType) {
16737 // Reject even if the type is dependent; an operator delete function is
16738 // required to have a non-dependent result type.
16739 return SemaRef.Diag(
16740 Loc: FnDecl->getLocation(),
16741 DiagID: CanResultType->isDependentType()
16742 ? diag::err_operator_new_delete_dependent_result_type
16743 : diag::err_operator_new_delete_invalid_result_type)
16744 << FnDecl->getDeclName() << ExpectedResultType;
16745 }
16746
16747 // A function template must have at least 2 parameters.
16748 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16749 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16750 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16751 << FnDecl->getDeclName();
16752
16753 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16754 auto FallbackType) -> bool {
16755 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16756 if (ExpectedType.isNull()) {
16757 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16758 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16759 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16760 << ParamDecl->getSourceRange();
16761 }
16762 CanQualType CanExpectedTy =
16763 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16764 auto ActualParamType =
16765 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16766 if (ActualParamType == CanExpectedTy)
16767 return false;
16768 unsigned Diagnostic = ActualParamType->isDependentType()
16769 ? DependentParamTypeDiag
16770 : InvalidParamTypeDiag;
16771 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16772 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16773 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16774 << FallbackType << ParamDecl->getSourceRange();
16775 };
16776
16777 // Check that the first parameter type is what we expect.
16778 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16779 return true;
16780
16781 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16782
16783 // If the first parameter type is not a type-identity we're done, otherwise
16784 // we need to ensure the size and alignment parameters have the correct type
16785 if (!IsPotentiallyTypeAware)
16786 return false;
16787
16788 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16789 return true;
16790 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16791 CanQualType StdAlignValT =
16792 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16793 : CanQualType();
16794 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16795 return true;
16796
16797 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16798 return MalformedTypeIdentity;
16799}
16800
16801static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16802 // C++ [basic.stc.dynamic.allocation]p1:
16803 // A program is ill-formed if an allocation function is declared in a
16804 // namespace scope other than global scope or declared static in global
16805 // scope.
16806 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16807 return true;
16808
16809 CanQualType SizeTy =
16810 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16811
16812 // C++ [basic.stc.dynamic.allocation]p1:
16813 // The return type shall be void*. The first parameter shall have type
16814 // std::size_t.
16815 return CheckOperatorNewDeleteTypes(
16816 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16817 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16818 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16819}
16820
16821static bool
16822CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16823 // C++ [basic.stc.dynamic.deallocation]p1:
16824 // A program is ill-formed if deallocation functions are declared in a
16825 // namespace scope other than global scope or declared static in global
16826 // scope.
16827 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16828 return true;
16829
16830 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16831 auto ConstructDestroyingDeleteAddressType = [&]() {
16832 assert(MD);
16833 return SemaRef.Context.getPointerType(
16834 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16835 };
16836
16837 // C++ P2719: A destroying operator delete cannot be type aware
16838 // so for QoL we actually check for this explicitly by considering
16839 // an destroying-delete appropriate address type and the presence of
16840 // any parameter of type destroying_delete_t as an erroneous attempt
16841 // to declare a type aware destroying delete, rather than emitting a
16842 // pile of incorrect parameter type errors.
16843 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16844 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16845 QualType AddressParamType =
16846 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16847 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16848 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16849 // The address parameter type implies an author trying to construct a
16850 // type aware destroying delete, so we'll see if we can find a parameter
16851 // of type `std::destroying_delete_t`, and if we find it we'll report
16852 // this as being an attempt at a type aware destroying delete just stop
16853 // here. If we don't do this, the resulting incorrect parameter ordering
16854 // results in a pile mismatched argument type errors that don't explain
16855 // the core problem.
16856 for (auto Param : MD->parameters()) {
16857 if (isDestroyingDeleteT(Type: Param->getType())) {
16858 SemaRef.Diag(Loc: MD->getLocation(),
16859 DiagID: diag::err_type_aware_destroying_operator_delete)
16860 << Param->getSourceRange();
16861 return true;
16862 }
16863 }
16864 }
16865 }
16866
16867 // C++ P0722:
16868 // Within a class C, the first parameter of a destroying operator delete
16869 // shall be of type C *. The first parameter of any other deallocation
16870 // function shall be of type void *.
16871 CanQualType ExpectedAddressParamType =
16872 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16873 ? SemaRef.Context.getPointerType(
16874 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16875 : SemaRef.Context.VoidPtrTy;
16876
16877 // C++ [basic.stc.dynamic.deallocation]p2:
16878 // Each deallocation function shall return void
16879 if (CheckOperatorNewDeleteTypes(
16880 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16881 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16882 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16883 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
16884 return true;
16885
16886 // C++ P0722:
16887 // A destroying operator delete shall be a usual deallocation function.
16888 if (MD && !MD->getParent()->isDependentContext() &&
16889 MD->isDestroyingOperatorDelete()) {
16890 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16891 SemaRef.Diag(Loc: MD->getLocation(),
16892 DiagID: diag::err_destroying_operator_delete_not_usual);
16893 return true;
16894 }
16895 }
16896
16897 return false;
16898}
16899
16900bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16901 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16902 "Expected an overloaded operator declaration");
16903
16904 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16905
16906 // C++ [over.oper]p5:
16907 // The allocation and deallocation functions, operator new,
16908 // operator new[], operator delete and operator delete[], are
16909 // described completely in 3.7.3. The attributes and restrictions
16910 // found in the rest of this subclause do not apply to them unless
16911 // explicitly stated in 3.7.3.
16912 if (Op == OO_Delete || Op == OO_Array_Delete)
16913 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16914
16915 if (Op == OO_New || Op == OO_Array_New)
16916 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16917
16918 // C++ [over.oper]p7:
16919 // An operator function shall either be a member function or
16920 // be a non-member function and have at least one parameter
16921 // whose type is a class, a reference to a class, an enumeration,
16922 // or a reference to an enumeration.
16923 // Note: Before C++23, a member function could not be static. The only member
16924 // function allowed to be static is the call operator function.
16925 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16926 if (MethodDecl->isStatic()) {
16927 if (Op == OO_Call || Op == OO_Subscript)
16928 Diag(Loc: FnDecl->getLocation(),
16929 DiagID: (LangOpts.CPlusPlus23
16930 ? diag::warn_cxx20_compat_operator_overload_static
16931 : diag::ext_operator_overload_static))
16932 << FnDecl;
16933 else
16934 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
16935 << FnDecl;
16936 }
16937 } else {
16938 bool ClassOrEnumParam = false;
16939 for (auto *Param : FnDecl->parameters()) {
16940 QualType ParamType = Param->getType().getNonReferenceType();
16941 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16942 ParamType->isEnumeralType()) {
16943 ClassOrEnumParam = true;
16944 break;
16945 }
16946 }
16947
16948 if (!ClassOrEnumParam)
16949 return Diag(Loc: FnDecl->getLocation(),
16950 DiagID: diag::err_operator_overload_needs_class_or_enum)
16951 << FnDecl->getDeclName();
16952 }
16953
16954 // C++ [over.oper]p8:
16955 // An operator function cannot have default arguments (8.3.6),
16956 // except where explicitly stated below.
16957 //
16958 // Only the function-call operator (C++ [over.call]p1) and the subscript
16959 // operator (CWG2507) allow default arguments.
16960 if (Op != OO_Call) {
16961 ParmVarDecl *FirstDefaultedParam = nullptr;
16962 for (auto *Param : FnDecl->parameters()) {
16963 if (Param->hasDefaultArg()) {
16964 FirstDefaultedParam = Param;
16965 break;
16966 }
16967 }
16968 if (FirstDefaultedParam) {
16969 if (Op == OO_Subscript) {
16970 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
16971 ? diag::ext_subscript_overload
16972 : diag::error_subscript_overload)
16973 << FnDecl->getDeclName() << 1
16974 << FirstDefaultedParam->getDefaultArgRange();
16975 } else {
16976 return Diag(Loc: FirstDefaultedParam->getLocation(),
16977 DiagID: diag::err_operator_overload_default_arg)
16978 << FnDecl->getDeclName()
16979 << FirstDefaultedParam->getDefaultArgRange();
16980 }
16981 }
16982 }
16983
16984 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
16985 { false, false, false }
16986#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
16987 , { Unary, Binary, MemberOnly }
16988#include "clang/Basic/OperatorKinds.def"
16989 };
16990
16991 bool CanBeUnaryOperator = OperatorUses[Op][0];
16992 bool CanBeBinaryOperator = OperatorUses[Op][1];
16993 bool MustBeMemberOperator = OperatorUses[Op][2];
16994
16995 // C++ [over.oper]p8:
16996 // [...] Operator functions cannot have more or fewer parameters
16997 // than the number required for the corresponding operator, as
16998 // described in the rest of this subclause.
16999 unsigned NumParams = FnDecl->getNumParams() +
17000 (isa<CXXMethodDecl>(Val: FnDecl) &&
17001 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17002 ? 1
17003 : 0);
17004 if (Op != OO_Call && Op != OO_Subscript &&
17005 ((NumParams == 1 && !CanBeUnaryOperator) ||
17006 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17007 (NumParams > 2))) {
17008 // We have the wrong number of parameters.
17009 unsigned ErrorKind;
17010 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17011 ErrorKind = 2; // 2 -> unary or binary.
17012 } else if (CanBeUnaryOperator) {
17013 ErrorKind = 0; // 0 -> unary
17014 } else {
17015 assert(CanBeBinaryOperator &&
17016 "All non-call overloaded operators are unary or binary!");
17017 ErrorKind = 1; // 1 -> binary
17018 }
17019 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17020 << FnDecl->getDeclName() << NumParams << ErrorKind;
17021 }
17022
17023 if (Op == OO_Subscript && NumParams != 2) {
17024 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17025 ? diag::ext_subscript_overload
17026 : diag::error_subscript_overload)
17027 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17028 }
17029
17030 // Overloaded operators other than operator() and operator[] cannot be
17031 // variadic.
17032 if (Op != OO_Call &&
17033 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17034 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17035 << FnDecl->getDeclName();
17036 }
17037
17038 // Some operators must be member functions.
17039 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17040 return Diag(Loc: FnDecl->getLocation(),
17041 DiagID: diag::err_operator_overload_must_be_member)
17042 << FnDecl->getDeclName();
17043 }
17044
17045 // C++ [over.inc]p1:
17046 // The user-defined function called operator++ implements the
17047 // prefix and postfix ++ operator. If this function is a member
17048 // function with no parameters, or a non-member function with one
17049 // parameter of class or enumeration type, it defines the prefix
17050 // increment operator ++ for objects of that type. If the function
17051 // is a member function with one parameter (which shall be of type
17052 // int) or a non-member function with two parameters (the second
17053 // of which shall be of type int), it defines the postfix
17054 // increment operator ++ for objects of that type.
17055 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17056 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17057 QualType ParamType = LastParam->getType();
17058
17059 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17060 !ParamType->isDependentType())
17061 return Diag(Loc: LastParam->getLocation(),
17062 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17063 << LastParam->getType() << (Op == OO_MinusMinus);
17064 }
17065
17066 return false;
17067}
17068
17069static bool
17070checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17071 FunctionTemplateDecl *TpDecl) {
17072 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17073
17074 // Must have one or two template parameters.
17075 if (TemplateParams->size() == 1) {
17076 NonTypeTemplateParmDecl *PmDecl =
17077 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17078
17079 // The template parameter must be a char parameter pack.
17080 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17081 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17082 return false;
17083
17084 // C++20 [over.literal]p5:
17085 // A string literal operator template is a literal operator template
17086 // whose template-parameter-list comprises a single non-type
17087 // template-parameter of class type.
17088 //
17089 // As a DR resolution, we also allow placeholders for deduced class
17090 // template specializations.
17091 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17092 !PmDecl->isTemplateParameterPack() &&
17093 (PmDecl->getType()->isRecordType() ||
17094 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17095 return false;
17096 } else if (TemplateParams->size() == 2) {
17097 TemplateTypeParmDecl *PmType =
17098 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17099 NonTypeTemplateParmDecl *PmArgs =
17100 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17101
17102 // The second template parameter must be a parameter pack with the
17103 // first template parameter as its type.
17104 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17105 PmArgs->isTemplateParameterPack()) {
17106 if (const auto *TArgs =
17107 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17108 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17109 TArgs->getIndex() == PmType->getIndex()) {
17110 if (!SemaRef.inTemplateInstantiation())
17111 SemaRef.Diag(Loc: TpDecl->getLocation(),
17112 DiagID: diag::ext_string_literal_operator_template);
17113 return false;
17114 }
17115 }
17116 }
17117
17118 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17119 DiagID: diag::err_literal_operator_template)
17120 << TpDecl->getTemplateParameters()->getSourceRange();
17121 return true;
17122}
17123
17124bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17125 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17126 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17127 << FnDecl->getDeclName();
17128 return true;
17129 }
17130
17131 if (FnDecl->isExternC()) {
17132 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17133 if (const LinkageSpecDecl *LSD =
17134 FnDecl->getDeclContext()->getExternCContext())
17135 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17136 return true;
17137 }
17138
17139 // This might be the definition of a literal operator template.
17140 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17141
17142 // This might be a specialization of a literal operator template.
17143 if (!TpDecl)
17144 TpDecl = FnDecl->getPrimaryTemplate();
17145
17146 // template <char...> type operator "" name() and
17147 // template <class T, T...> type operator "" name() are the only valid
17148 // template signatures, and the only valid signatures with no parameters.
17149 //
17150 // C++20 also allows template <SomeClass T> type operator "" name().
17151 if (TpDecl) {
17152 if (FnDecl->param_size() != 0) {
17153 Diag(Loc: FnDecl->getLocation(),
17154 DiagID: diag::err_literal_operator_template_with_params);
17155 return true;
17156 }
17157
17158 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17159 return true;
17160
17161 } else if (FnDecl->param_size() == 1) {
17162 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17163
17164 QualType ParamType = Param->getType().getUnqualifiedType();
17165
17166 // Only unsigned long long int, long double, any character type, and const
17167 // char * are allowed as the only parameters.
17168 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17169 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17170 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17171 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17172 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17173 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17174 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17175 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17176 QualType InnerType = Ptr->getPointeeType();
17177
17178 // Pointer parameter must be a const char *.
17179 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17180 T2: Context.CharTy) &&
17181 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17182 Diag(Loc: Param->getSourceRange().getBegin(),
17183 DiagID: diag::err_literal_operator_param)
17184 << ParamType << "'const char *'" << Param->getSourceRange();
17185 return true;
17186 }
17187
17188 } else if (ParamType->isRealFloatingType()) {
17189 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17190 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17191 return true;
17192
17193 } else if (ParamType->isIntegerType()) {
17194 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17195 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17196 return true;
17197
17198 } else {
17199 Diag(Loc: Param->getSourceRange().getBegin(),
17200 DiagID: diag::err_literal_operator_invalid_param)
17201 << ParamType << Param->getSourceRange();
17202 return true;
17203 }
17204
17205 } else if (FnDecl->param_size() == 2) {
17206 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17207
17208 // First, verify that the first parameter is correct.
17209
17210 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17211
17212 // Two parameter function must have a pointer to const as a
17213 // first parameter; let's strip those qualifiers.
17214 const PointerType *PT = FirstParamType->getAs<PointerType>();
17215
17216 if (!PT) {
17217 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17218 DiagID: diag::err_literal_operator_param)
17219 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17220 return true;
17221 }
17222
17223 QualType PointeeType = PT->getPointeeType();
17224 // First parameter must be const
17225 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17226 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17227 DiagID: diag::err_literal_operator_param)
17228 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17229 return true;
17230 }
17231
17232 QualType InnerType = PointeeType.getUnqualifiedType();
17233 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17234 // const char32_t* are allowed as the first parameter to a two-parameter
17235 // function
17236 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17237 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17238 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17239 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17240 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17241 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17242 DiagID: diag::err_literal_operator_param)
17243 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17244 return true;
17245 }
17246
17247 // Move on to the second and final parameter.
17248 ++Param;
17249
17250 // The second parameter must be a std::size_t.
17251 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17252 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17253 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17254 DiagID: diag::err_literal_operator_param)
17255 << SecondParamType << Context.getSizeType()
17256 << (*Param)->getSourceRange();
17257 return true;
17258 }
17259 } else {
17260 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17261 return true;
17262 }
17263
17264 // Parameters are good.
17265
17266 // A parameter-declaration-clause containing a default argument is not
17267 // equivalent to any of the permitted forms.
17268 for (auto *Param : FnDecl->parameters()) {
17269 if (Param->hasDefaultArg()) {
17270 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17271 DiagID: diag::err_literal_operator_default_argument)
17272 << Param->getDefaultArgRange();
17273 break;
17274 }
17275 }
17276
17277 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17278 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17279 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17280 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17281 // C++23 [usrlit.suffix]p1:
17282 // Literal suffix identifiers that do not start with an underscore are
17283 // reserved for future standardization. Literal suffix identifiers that
17284 // contain a double underscore __ are reserved for use by C++
17285 // implementations.
17286 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17287 << static_cast<int>(Status)
17288 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17289 }
17290
17291 return false;
17292}
17293
17294Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17295 Expr *LangStr,
17296 SourceLocation LBraceLoc) {
17297 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17298 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17299
17300 StringRef Lang = Lit->getString();
17301 LinkageSpecLanguageIDs Language;
17302 if (Lang == "C")
17303 Language = LinkageSpecLanguageIDs::C;
17304 else if (Lang == "C++")
17305 Language = LinkageSpecLanguageIDs::CXX;
17306 else {
17307 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17308 << LangStr->getSourceRange();
17309 return nullptr;
17310 }
17311
17312 // FIXME: Add all the various semantics of linkage specifications
17313
17314 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17315 LangLoc: LangStr->getExprLoc(), Lang: Language,
17316 HasBraces: LBraceLoc.isValid());
17317
17318 /// C++ [module.unit]p7.2.3
17319 /// - Otherwise, if the declaration
17320 /// - ...
17321 /// - ...
17322 /// - appears within a linkage-specification,
17323 /// it is attached to the global module.
17324 ///
17325 /// If the declaration is already in global module fragment, we don't
17326 /// need to attach it again.
17327 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17328 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17329 D->setLocalOwningModule(GlobalModule);
17330 }
17331
17332 CurContext->addDecl(D);
17333 PushDeclContext(S, DC: D);
17334 return D;
17335}
17336
17337Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17338 Decl *LinkageSpec,
17339 SourceLocation RBraceLoc) {
17340 if (RBraceLoc.isValid()) {
17341 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17342 LSDecl->setRBraceLoc(RBraceLoc);
17343 }
17344
17345 // If the current module doesn't has Parent, it implies that the
17346 // LinkageSpec isn't in the module created by itself. So we don't
17347 // need to pop it.
17348 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17349 getCurrentModule()->isImplicitGlobalModule() &&
17350 getCurrentModule()->Parent)
17351 PopImplicitGlobalModuleFragment();
17352
17353 PopDeclContext();
17354 return LinkageSpec;
17355}
17356
17357Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17358 const ParsedAttributesView &AttrList,
17359 SourceLocation SemiLoc) {
17360 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17361 // Attribute declarations appertain to empty declaration so we handle
17362 // them here.
17363 ProcessDeclAttributeList(S, D: ED, AttrList);
17364
17365 CurContext->addDecl(D: ED);
17366 return ED;
17367}
17368
17369VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17370 SourceLocation StartLoc,
17371 SourceLocation Loc,
17372 const IdentifierInfo *Name) {
17373 bool Invalid = false;
17374 QualType ExDeclType = TInfo->getType();
17375
17376 // Arrays and functions decay.
17377 if (ExDeclType->isArrayType())
17378 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17379 else if (ExDeclType->isFunctionType())
17380 ExDeclType = Context.getPointerType(T: ExDeclType);
17381
17382 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17383 // The exception-declaration shall not denote a pointer or reference to an
17384 // incomplete type, other than [cv] void*.
17385 // N2844 forbids rvalue references.
17386 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17387 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17388 Invalid = true;
17389 }
17390
17391 if (ExDeclType->isVariablyModifiedType()) {
17392 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17393 Invalid = true;
17394 }
17395
17396 QualType BaseType = ExDeclType;
17397 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17398 unsigned DK = diag::err_catch_incomplete;
17399 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17400 BaseType = Ptr->getPointeeType();
17401 Mode = 1;
17402 DK = diag::err_catch_incomplete_ptr;
17403 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17404 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17405 BaseType = Ref->getPointeeType();
17406 Mode = 2;
17407 DK = diag::err_catch_incomplete_ref;
17408 }
17409 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17410 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17411 Invalid = true;
17412
17413 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17414 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17415 Invalid = true;
17416 }
17417
17418 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17419 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17420 Invalid = true;
17421 }
17422
17423 if (!Invalid && !ExDeclType->isDependentType() &&
17424 RequireNonAbstractType(Loc, T: ExDeclType,
17425 DiagID: diag::err_abstract_type_in_decl,
17426 Args: AbstractVariableType))
17427 Invalid = true;
17428
17429 // Only the non-fragile NeXT runtime currently supports C++ catches
17430 // of ObjC types, and no runtime supports catching ObjC types by value.
17431 if (!Invalid && getLangOpts().ObjC) {
17432 QualType T = ExDeclType;
17433 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17434 T = RT->getPointeeType();
17435
17436 if (T->isObjCObjectType()) {
17437 Diag(Loc, DiagID: diag::err_objc_object_catch);
17438 Invalid = true;
17439 } else if (T->isObjCObjectPointerType()) {
17440 // FIXME: should this be a test for macosx-fragile specifically?
17441 if (getLangOpts().ObjCRuntime.isFragile())
17442 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17443 }
17444 }
17445
17446 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17447 T: ExDeclType, TInfo, S: SC_None);
17448 ExDecl->setExceptionVariable(true);
17449
17450 // In ARC, infer 'retaining' for variables of retainable type.
17451 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17452 Invalid = true;
17453
17454 if (!Invalid && !ExDeclType->isDependentType()) {
17455 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17456 // Insulate this from anything else we might currently be parsing.
17457 EnterExpressionEvaluationContext scope(
17458 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17459
17460 // C++ [except.handle]p16:
17461 // The object declared in an exception-declaration or, if the
17462 // exception-declaration does not specify a name, a temporary (12.2) is
17463 // copy-initialized (8.5) from the exception object. [...]
17464 // The object is destroyed when the handler exits, after the destruction
17465 // of any automatic objects initialized within the handler.
17466 //
17467 // We just pretend to initialize the object with itself, then make sure
17468 // it can be destroyed later.
17469 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17470
17471 InitializedEntity entity =
17472 InitializedEntity::InitializeVariable(Var: ExDecl);
17473 InitializationKind initKind =
17474 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17475
17476 Expr *opaqueValue =
17477 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17478 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17479 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17480 if (result.isInvalid())
17481 Invalid = true;
17482 else {
17483 // If the constructor used was non-trivial, set this as the
17484 // "initializer".
17485 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17486 if (!construct->getConstructor()->isTrivial()) {
17487 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17488 ExDecl->setInit(init);
17489 }
17490
17491 // And make sure it's destructable.
17492 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17493 }
17494 }
17495 }
17496
17497 if (Invalid)
17498 ExDecl->setInvalidDecl();
17499
17500 return ExDecl;
17501}
17502
17503Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17504 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17505 bool Invalid = D.isInvalidType();
17506
17507 // Check for unexpanded parameter packs.
17508 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17509 UPPC: UPPC_ExceptionType)) {
17510 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17511 Loc: D.getIdentifierLoc());
17512 Invalid = true;
17513 }
17514
17515 const IdentifierInfo *II = D.getIdentifier();
17516 if (NamedDecl *PrevDecl =
17517 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17518 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17519 // The scope should be freshly made just for us. There is just no way
17520 // it contains any previous declaration, except for function parameters in
17521 // a function-try-block's catch statement.
17522 assert(!S->isDeclScope(PrevDecl));
17523 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17524 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17525 << D.getIdentifier();
17526 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17527 Invalid = true;
17528 } else if (PrevDecl->isTemplateParameter())
17529 // Maybe we will complain about the shadowed template parameter.
17530 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17531 }
17532
17533 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17534 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17535 << D.getCXXScopeSpec().getRange();
17536 Invalid = true;
17537 }
17538
17539 VarDecl *ExDecl = BuildExceptionDeclaration(
17540 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17541 if (Invalid)
17542 ExDecl->setInvalidDecl();
17543
17544 // Add the exception declaration into this scope.
17545 if (II)
17546 PushOnScopeChains(D: ExDecl, S);
17547 else
17548 CurContext->addDecl(D: ExDecl);
17549
17550 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17551 return ExDecl;
17552}
17553
17554Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17555 Expr *AssertExpr,
17556 Expr *AssertMessageExpr,
17557 SourceLocation RParenLoc) {
17558 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17559 return nullptr;
17560
17561 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17562 AssertMessageExpr, RParenLoc, Failed: false);
17563}
17564
17565static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17566 switch (BTK) {
17567 case BuiltinType::Char_S:
17568 case BuiltinType::Char_U:
17569 break;
17570 case BuiltinType::Char8:
17571 OS << "u8";
17572 break;
17573 case BuiltinType::Char16:
17574 OS << 'u';
17575 break;
17576 case BuiltinType::Char32:
17577 OS << 'U';
17578 break;
17579 case BuiltinType::WChar_S:
17580 case BuiltinType::WChar_U:
17581 OS << 'L';
17582 break;
17583 default:
17584 llvm_unreachable("Non-character type");
17585 }
17586}
17587
17588/// Convert character's value, interpreted as a code unit, to a string.
17589/// The value needs to be zero-extended to 32-bits.
17590/// FIXME: This assumes Unicode literal encodings
17591static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17592 unsigned TyWidth,
17593 SmallVectorImpl<char> &Str) {
17594 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17595 char *Ptr = Arr;
17596 BuiltinType::Kind K = BTy->getKind();
17597 llvm::raw_svector_ostream OS(Str);
17598
17599 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17600 // other types.
17601 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17602 K == BuiltinType::Char8 || Value <= 0x7F) {
17603 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17604 if (!Escaped.empty())
17605 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17606 else
17607 OS << static_cast<char>(Value);
17608 return;
17609 }
17610
17611 switch (K) {
17612 case BuiltinType::Char16:
17613 case BuiltinType::Char32:
17614 case BuiltinType::WChar_S:
17615 case BuiltinType::WChar_U: {
17616 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17617 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17618 else
17619 OS << "\\x"
17620 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17621 break;
17622 }
17623 default:
17624 llvm_unreachable("Non-character type is passed");
17625 }
17626}
17627
17628/// Convert \V to a string we can present to the user in a diagnostic
17629/// \T is the type of the expression that has been evaluated into \V
17630static bool ConvertAPValueToString(const APValue &V, QualType T,
17631 SmallVectorImpl<char> &Str,
17632 ASTContext &Context) {
17633 if (!V.hasValue())
17634 return false;
17635
17636 switch (V.getKind()) {
17637 case APValue::ValueKind::Int:
17638 if (T->isBooleanType()) {
17639 // Bools are reduced to ints during evaluation, but for
17640 // diagnostic purposes we want to print them as
17641 // true or false.
17642 int64_t BoolValue = V.getInt().getExtValue();
17643 assert((BoolValue == 0 || BoolValue == 1) &&
17644 "Bool type, but value is not 0 or 1");
17645 llvm::raw_svector_ostream OS(Str);
17646 OS << (BoolValue ? "true" : "false");
17647 } else {
17648 llvm::raw_svector_ostream OS(Str);
17649 // Same is true for chars.
17650 // We want to print the character representation for textual types
17651 const auto *BTy = T->getAs<BuiltinType>();
17652 if (BTy) {
17653 switch (BTy->getKind()) {
17654 case BuiltinType::Char_S:
17655 case BuiltinType::Char_U:
17656 case BuiltinType::Char8:
17657 case BuiltinType::Char16:
17658 case BuiltinType::Char32:
17659 case BuiltinType::WChar_S:
17660 case BuiltinType::WChar_U: {
17661 unsigned TyWidth = Context.getIntWidth(T);
17662 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17663 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17664 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17665 OS << '\'';
17666 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17667 OS << "' (0x"
17668 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17669 /*Upper=*/true)
17670 << ", " << V.getInt() << ')';
17671 return true;
17672 }
17673 default:
17674 break;
17675 }
17676 }
17677 V.getInt().toString(Str);
17678 }
17679
17680 break;
17681
17682 case APValue::ValueKind::Float:
17683 V.getFloat().toString(Str);
17684 break;
17685
17686 case APValue::ValueKind::LValue:
17687 if (V.isNullPointer()) {
17688 llvm::raw_svector_ostream OS(Str);
17689 OS << "nullptr";
17690 } else
17691 return false;
17692 break;
17693
17694 case APValue::ValueKind::ComplexFloat: {
17695 llvm::raw_svector_ostream OS(Str);
17696 OS << '(';
17697 V.getComplexFloatReal().toString(Str);
17698 OS << " + ";
17699 V.getComplexFloatImag().toString(Str);
17700 OS << "i)";
17701 } break;
17702
17703 case APValue::ValueKind::ComplexInt: {
17704 llvm::raw_svector_ostream OS(Str);
17705 OS << '(';
17706 V.getComplexIntReal().toString(Str);
17707 OS << " + ";
17708 V.getComplexIntImag().toString(Str);
17709 OS << "i)";
17710 } break;
17711
17712 default:
17713 return false;
17714 }
17715
17716 return true;
17717}
17718
17719/// Some Expression types are not useful to print notes about,
17720/// e.g. literals and values that have already been expanded
17721/// before such as int-valued template parameters.
17722static bool UsefulToPrintExpr(const Expr *E) {
17723 E = E->IgnoreParenImpCasts();
17724 // Literals are pretty easy for humans to understand.
17725 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17726 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17727 return false;
17728
17729 // These have been substituted from template parameters
17730 // and appear as literals in the static assert error.
17731 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17732 return false;
17733
17734 // -5 is also simple to understand.
17735 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17736 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17737
17738 // Only print nested arithmetic operators.
17739 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17740 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17741 BO->isBitwiseOp());
17742
17743 return true;
17744}
17745
17746void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17747 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17748 Op && Op->getOpcode() != BO_LOr) {
17749 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17750 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17751
17752 // Ignore comparisons of boolean expressions with a boolean literal.
17753 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17754 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17755 return;
17756
17757 // Don't print obvious expressions.
17758 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17759 return;
17760
17761 struct {
17762 const clang::Expr *Cond;
17763 Expr::EvalResult Result;
17764 SmallString<12> ValueString;
17765 bool Print;
17766 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17767 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17768 for (auto &DiagSide : DiagSides) {
17769 const Expr *Side = DiagSide.Cond;
17770
17771 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17772
17773 DiagSide.Print = ConvertAPValueToString(
17774 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17775 }
17776 if (DiagSides[0].Print && DiagSides[1].Print) {
17777 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17778 << DiagSides[0].ValueString << Op->getOpcodeStr()
17779 << DiagSides[1].ValueString << Op->getSourceRange();
17780 }
17781 } else {
17782 DiagnoseTypeTraitDetails(E);
17783 }
17784}
17785
17786template <typename ResultType>
17787static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17788 ResultType &Result, ASTContext &Ctx,
17789 Sema::StringEvaluationContext EvalContext,
17790 bool ErrorOnInvalidMessage) {
17791
17792 assert(Message);
17793 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17794 "can't evaluate a dependant static assert message");
17795
17796 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17797 assert(SL->isUnevaluated() && "expected an unevaluated string");
17798 if constexpr (std::is_same_v<APValue, ResultType>) {
17799 Result =
17800 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17801 const ConstantArrayType *CAT =
17802 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17803 assert(CAT && "string literal isn't an array");
17804 QualType CharType = CAT->getElementType();
17805 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17806 CharType->isUnsignedIntegerType());
17807 for (unsigned I = 0; I < SL->getLength(); I++) {
17808 Value = SL->getCodeUnit(i: I);
17809 Result.getArrayInitializedElt(I) = APValue(Value);
17810 }
17811 } else {
17812 Result.assign(SL->getString().begin(), SL->getString().end());
17813 }
17814 return true;
17815 }
17816
17817 SourceLocation Loc = Message->getBeginLoc();
17818 QualType T = Message->getType().getNonReferenceType();
17819 auto *RD = T->getAsCXXRecordDecl();
17820 if (!RD) {
17821 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17822 return false;
17823 }
17824
17825 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17826 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17827 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17828 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17829 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17830 OverloadCandidateSet::CSK_Normal);
17831 if (MemberLookup.empty())
17832 return std::nullopt;
17833 return std::move(MemberLookup);
17834 };
17835
17836 std::optional<LookupResult> SizeMember = FindMember("size");
17837 std::optional<LookupResult> DataMember = FindMember("data");
17838 if (!SizeMember || !DataMember) {
17839 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17840 << EvalContext
17841 << ((!SizeMember && !DataMember) ? 2
17842 : !SizeMember ? 0
17843 : 1);
17844 return false;
17845 }
17846
17847 auto BuildExpr = [&](LookupResult &LR) {
17848 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17849 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17850 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17851 if (Res.isInvalid())
17852 return ExprError();
17853 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17854 IsExecConfig: false, AllowRecovery: true);
17855 if (Res.isInvalid())
17856 return ExprError();
17857 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17858 return ExprError();
17859 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17860 };
17861
17862 ExprResult SizeE = BuildExpr(*SizeMember);
17863 ExprResult DataE = BuildExpr(*DataMember);
17864
17865 QualType SizeT = SemaRef.Context.getSizeType();
17866 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17867 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17868
17869 ExprResult EvaluatedSize =
17870 SizeE.isInvalid()
17871 ? ExprError()
17872 : SemaRef.BuildConvertedConstantExpression(
17873 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17874 if (EvaluatedSize.isInvalid()) {
17875 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17876 << EvalContext << /*size*/ 0;
17877 return false;
17878 }
17879
17880 ExprResult EvaluatedData =
17881 DataE.isInvalid()
17882 ? ExprError()
17883 : SemaRef.BuildConvertedConstantExpression(
17884 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17885 if (EvaluatedData.isInvalid()) {
17886 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17887 << EvalContext << /*data*/ 1;
17888 return false;
17889 }
17890
17891 if (!ErrorOnInvalidMessage &&
17892 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
17893 return true;
17894
17895 Expr::EvalResult Status;
17896 SmallVector<PartialDiagnosticAt, 8> Notes;
17897 Status.Diag = &Notes;
17898 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17899 EvaluatedData.get(), Ctx, Status) ||
17900 !Notes.empty()) {
17901 SemaRef.Diag(Loc: Message->getBeginLoc(),
17902 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17903 : diag::warn_user_defined_msg_constexpr)
17904 << EvalContext;
17905 for (const auto &Note : Notes)
17906 SemaRef.Diag(Loc: Note.first, PD: Note.second);
17907 return !ErrorOnInvalidMessage;
17908 }
17909 return true;
17910}
17911
17912bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17913 StringEvaluationContext EvalContext,
17914 bool ErrorOnInvalidMessage) {
17915 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17916 ErrorOnInvalidMessage);
17917}
17918
17919bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17920 StringEvaluationContext EvalContext,
17921 bool ErrorOnInvalidMessage) {
17922 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17923 ErrorOnInvalidMessage);
17924}
17925
17926Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17927 Expr *AssertExpr, Expr *AssertMessage,
17928 SourceLocation RParenLoc,
17929 bool Failed) {
17930 assert(AssertExpr != nullptr && "Expected non-null condition");
17931 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17932 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17933 !AssertMessage->isValueDependent())) &&
17934 !Failed) {
17935 // In a static_assert-declaration, the constant-expression shall be a
17936 // constant expression that can be contextually converted to bool.
17937 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
17938 if (Converted.isInvalid())
17939 Failed = true;
17940
17941 ExprResult FullAssertExpr =
17942 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
17943 /*DiscardedValue*/ false,
17944 /*IsConstexpr*/ true);
17945 if (FullAssertExpr.isInvalid())
17946 Failed = true;
17947 else
17948 AssertExpr = FullAssertExpr.get();
17949
17950 llvm::APSInt Cond;
17951 Expr *BaseExpr = AssertExpr;
17952 AllowFoldKind FoldKind = AllowFoldKind::No;
17953
17954 if (!getLangOpts().CPlusPlus) {
17955 // In C mode, allow folding as an extension for better compatibility with
17956 // C++ in terms of expressions like static_assert("test") or
17957 // static_assert(nullptr).
17958 FoldKind = AllowFoldKind::Allow;
17959 }
17960
17961 if (!Failed && VerifyIntegerConstantExpression(
17962 E: BaseExpr, Result: &Cond,
17963 DiagID: diag::err_static_assert_expression_is_not_constant,
17964 CanFold: FoldKind).isInvalid())
17965 Failed = true;
17966
17967 // If the static_assert passes, only verify that
17968 // the message is grammatically valid without evaluating it.
17969 if (!Failed && AssertMessage && Cond.getBoolValue()) {
17970 std::string Str;
17971 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17972 EvalContext: StringEvaluationContext::StaticAssert,
17973 /*ErrorOnInvalidMessage=*/false);
17974 }
17975
17976 // CWG2518
17977 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
17978 // template definition, the declaration has no effect.
17979 bool InTemplateDefinition =
17980 getLangOpts().CPlusPlus && CurContext->isDependentContext();
17981
17982 if (!Failed && !Cond && !InTemplateDefinition) {
17983 SmallString<256> MsgBuffer;
17984 llvm::raw_svector_ostream Msg(MsgBuffer);
17985 bool HasMessage = AssertMessage;
17986 if (AssertMessage) {
17987 std::string Str;
17988 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
17989 EvalContext: StringEvaluationContext::StaticAssert,
17990 /*ErrorOnInvalidMessage=*/true) ||
17991 !Str.empty();
17992 Msg << Str;
17993 }
17994 Expr *InnerCond = nullptr;
17995 std::string InnerCondDescription;
17996 std::tie(args&: InnerCond, args&: InnerCondDescription) =
17997 findFailedBooleanCondition(Cond: Converted.get());
17998 if (const auto *ConceptIDExpr =
17999 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18000 const ASTConstraintSatisfaction &Satisfaction =
18001 ConceptIDExpr->getSatisfaction();
18002 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18003 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18004 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18005 // Drill down into concept specialization expressions to see why they
18006 // weren't satisfied.
18007 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18008 }
18009 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18010 !isa<IntegerLiteral>(Val: InnerCond)) {
18011 Diag(Loc: InnerCond->getBeginLoc(),
18012 DiagID: diag::err_static_assert_requirement_failed)
18013 << InnerCondDescription << !HasMessage << Msg.str()
18014 << InnerCond->getSourceRange();
18015 DiagnoseStaticAssertDetails(E: InnerCond);
18016 } else {
18017 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18018 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18019 PrintContextStack();
18020 }
18021 Failed = true;
18022 }
18023 } else {
18024 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18025 /*DiscardedValue*/false,
18026 /*IsConstexpr*/true);
18027 if (FullAssertExpr.isInvalid())
18028 Failed = true;
18029 else
18030 AssertExpr = FullAssertExpr.get();
18031 }
18032
18033 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18034 AssertExpr, Message: AssertMessage, RParenLoc,
18035 Failed);
18036
18037 CurContext->addDecl(D: Decl);
18038 return Decl;
18039}
18040
18041DeclResult Sema::ActOnTemplatedFriendTag(
18042 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18043 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18044 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18045 MultiTemplateParamsArg TempParamLists) {
18046 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18047
18048 bool IsMemberSpecialization = false;
18049 bool Invalid = false;
18050
18051 if (TemplateParameterList *TemplateParams =
18052 MatchTemplateParametersToScopeSpecifier(
18053 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18054 IsMemberSpecialization, Invalid)) {
18055 if (TemplateParams->size() > 0) {
18056 // This is a declaration of a class template.
18057 if (Invalid)
18058 return true;
18059
18060 return CheckClassTemplate(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS,
18061 Name, NameLoc, Attr, TemplateParams, AS: AS_public,
18062 /*ModulePrivateLoc=*/SourceLocation(),
18063 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
18064 OuterTemplateParamLists: TempParamLists.data())
18065 .get();
18066 } else {
18067 // The "template<>" header is extraneous.
18068 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18069 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18070 IsMemberSpecialization = true;
18071 }
18072 }
18073
18074 if (Invalid) return true;
18075
18076 bool isAllExplicitSpecializations =
18077 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18078 return List->size() == 0;
18079 });
18080
18081 // FIXME: don't ignore attributes.
18082
18083 // If it's explicit specializations all the way down, just forget
18084 // about the template header and build an appropriate non-templated
18085 // friend. TODO: for source fidelity, remember the headers.
18086 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18087 if (isAllExplicitSpecializations) {
18088 if (SS.isEmpty()) {
18089 bool Owned = false;
18090 bool IsDependent = false;
18091 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18092 Attr, AS: AS_public,
18093 /*ModulePrivateLoc=*/SourceLocation(),
18094 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18095 /*ScopedEnumKWLoc=*/SourceLocation(),
18096 /*ScopedEnumUsesClassTag=*/false,
18097 /*UnderlyingType=*/TypeResult(),
18098 /*IsTypeSpecifier=*/false,
18099 /*IsTemplateParamOrArg=*/false,
18100 /*OOK=*/OffsetOfKind::Outside);
18101 }
18102
18103 TypeSourceInfo *TSI = nullptr;
18104 ElaboratedTypeKeyword Keyword
18105 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18106 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18107 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18108 if (T.isNull())
18109 return true;
18110
18111 FriendDecl *Friend =
18112 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18113 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18114 Friend->setAccess(AS_public);
18115 CurContext->addDecl(D: Friend);
18116 return Friend;
18117 }
18118
18119 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18120
18121 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18122 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18123 // shall not have been introduced by the template-declaration.
18124 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18125 collectUnexpandedParameterPacks(NNS: QualifierLoc, Unexpanded);
18126 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18127 for (UnexpandedParameterPack &U : Unexpanded) {
18128 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(UPP: U);
18129 DI && DI->first >= FriendDeclDepth) {
18130 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18131 if (!ND)
18132 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18133 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18134 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18135 return true;
18136 }
18137 }
18138
18139 // Handle the case of a templated-scope friend class. e.g.
18140 // template <class T> class A<T>::B;
18141 // FIXME: we don't support these right now.
18142 Diag(Loc: NameLoc, DiagID: diag::warn_template_qualified_friend_unsupported)
18143 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(Val: CurContext);
18144 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18145 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18146 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18147 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18148 TL.setElaboratedKeywordLoc(TagLoc);
18149 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18150 TL.setNameLoc(NameLoc);
18151
18152 FriendDecl *Friend =
18153 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18154 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18155 Friend->setAccess(AS_public);
18156 Friend->setUnsupportedFriend(true);
18157 CurContext->addDecl(D: Friend);
18158 return Friend;
18159}
18160
18161Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18162 MultiTemplateParamsArg TempParams,
18163 SourceLocation EllipsisLoc) {
18164 SourceLocation Loc = DS.getBeginLoc();
18165 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18166
18167 assert(DS.isFriendSpecified());
18168 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18169
18170 // C++ [class.friend]p3:
18171 // A friend declaration that does not declare a function shall have one of
18172 // the following forms:
18173 // friend elaborated-type-specifier ;
18174 // friend simple-type-specifier ;
18175 // friend typename-specifier ;
18176 //
18177 // If the friend keyword isn't first, or if the declarations has any type
18178 // qualifiers, then the declaration doesn't have that form.
18179 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18180 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18181 if (DS.getTypeQualifiers()) {
18182 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18183 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18184 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18185 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18186 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18187 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18188 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18189 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18190 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18191 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18192 }
18193
18194 // Try to convert the decl specifier to a type. This works for
18195 // friend templates because ActOnTag never produces a ClassTemplateDecl
18196 // for a TagUseKind::Friend.
18197 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18198 DeclaratorContext::Member);
18199 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18200 QualType T = TSI->getType();
18201 if (TheDeclarator.isInvalidType())
18202 return nullptr;
18203
18204 // If '...' is present, the type must contain an unexpanded parameter
18205 // pack, and vice versa.
18206 bool Invalid = false;
18207 if (EllipsisLoc.isInvalid() &&
18208 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18209 return nullptr;
18210 if (EllipsisLoc.isValid() &&
18211 !TSI->getType()->containsUnexpandedParameterPack()) {
18212 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18213 << TSI->getTypeLoc().getSourceRange();
18214 Invalid = true;
18215 }
18216
18217 if (!T->isElaboratedTypeSpecifier()) {
18218 if (TempParams.size()) {
18219 // C++23 [dcl.pre]p5:
18220 // In a simple-declaration, the optional init-declarator-list can be
18221 // omitted only when declaring a class or enumeration, that is, when
18222 // the decl-specifier-seq contains either a class-specifier, an
18223 // elaborated-type-specifier with a class-key, or an enum-specifier.
18224 //
18225 // The declaration of a template-declaration or explicit-specialization
18226 // is never a member-declaration, so this must be a simple-declaration
18227 // with no init-declarator-list. Therefore, this is ill-formed.
18228 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18229 return nullptr;
18230 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18231 SmallString<16> InsertionText(" ");
18232 InsertionText += RD->getKindName();
18233
18234 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18235 ? diag::warn_cxx98_compat_unelaborated_friend_type
18236 : diag::ext_unelaborated_friend_type)
18237 << (unsigned)RD->getTagKind() << T
18238 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18239 Code: InsertionText);
18240 } else {
18241 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18242 << T << DS.getSourceRange();
18243 }
18244 }
18245
18246 // C++98 [class.friend]p1: A friend of a class is a function
18247 // or class that is not a member of the class . . .
18248 // This is fixed in DR77, which just barely didn't make the C++03
18249 // deadline. It's also a very silly restriction that seriously
18250 // affects inner classes and which nobody else seems to implement;
18251 // thus we never diagnose it, not even in -pedantic.
18252 //
18253 // But note that we could warn about it: it's always useless to
18254 // friend one of your own members (it's not, however, worthless to
18255 // friend a member of an arbitrary specialization of your template).
18256
18257 Decl *D;
18258 if (!TempParams.empty())
18259 // TODO: Support variadic friend template decls?
18260 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
18261 FriendLoc);
18262 else
18263 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18264 Friend_: TSI, FriendL: FriendLoc, EllipsisLoc);
18265
18266 if (!D)
18267 return nullptr;
18268
18269 D->setAccess(AS_public);
18270 CurContext->addDecl(D);
18271
18272 if (Invalid)
18273 D->setInvalidDecl();
18274
18275 return D;
18276}
18277
18278NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18279 MultiTemplateParamsArg TemplateParams) {
18280 const DeclSpec &DS = D.getDeclSpec();
18281
18282 assert(DS.isFriendSpecified());
18283 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18284
18285 SourceLocation Loc = D.getIdentifierLoc();
18286 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18287
18288 // C++ [class.friend]p1
18289 // A friend of a class is a function or class....
18290 // Note that this sees through typedefs, which is intended.
18291 // It *doesn't* see through dependent types, which is correct
18292 // according to [temp.arg.type]p3:
18293 // If a declaration acquires a function type through a
18294 // type dependent on a template-parameter and this causes
18295 // a declaration that does not use the syntactic form of a
18296 // function declarator to have a function type, the program
18297 // is ill-formed.
18298 if (!TInfo->getType()->isFunctionType()) {
18299 Diag(Loc, DiagID: diag::err_unexpected_friend);
18300
18301 // It might be worthwhile to try to recover by creating an
18302 // appropriate declaration.
18303 return nullptr;
18304 }
18305
18306 // C++ [namespace.memdef]p3
18307 // - If a friend declaration in a non-local class first declares a
18308 // class or function, the friend class or function is a member
18309 // of the innermost enclosing namespace.
18310 // - The name of the friend is not found by simple name lookup
18311 // until a matching declaration is provided in that namespace
18312 // scope (either before or after the class declaration granting
18313 // friendship).
18314 // - If a friend function is called, its name may be found by the
18315 // name lookup that considers functions from namespaces and
18316 // classes associated with the types of the function arguments.
18317 // - When looking for a prior declaration of a class or a function
18318 // declared as a friend, scopes outside the innermost enclosing
18319 // namespace scope are not considered.
18320
18321 CXXScopeSpec &SS = D.getCXXScopeSpec();
18322 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18323 assert(NameInfo.getName());
18324
18325 // Check for unexpanded parameter packs.
18326 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18327 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18328 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18329 return nullptr;
18330
18331 // The context we found the declaration in, or in which we should
18332 // create the declaration.
18333 DeclContext *DC;
18334 Scope *DCScope = S;
18335 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18336 RedeclarationKind::ForExternalRedeclaration);
18337
18338 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18339
18340 // There are five cases here.
18341 // - There's no scope specifier and we're in a local class. Only look
18342 // for functions declared in the immediately-enclosing block scope.
18343 // We recover from invalid scope qualifiers as if they just weren't there.
18344 FunctionDecl *FunctionContainingLocalClass = nullptr;
18345 if ((SS.isInvalid() || !SS.isSet()) &&
18346 (FunctionContainingLocalClass =
18347 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18348 // C++11 [class.friend]p11:
18349 // If a friend declaration appears in a local class and the name
18350 // specified is an unqualified name, a prior declaration is
18351 // looked up without considering scopes that are outside the
18352 // innermost enclosing non-class scope. For a friend function
18353 // declaration, if there is no prior declaration, the program is
18354 // ill-formed.
18355
18356 // Find the innermost enclosing non-class scope. This is the block
18357 // scope containing the local class definition (or for a nested class,
18358 // the outer local class).
18359 DCScope = S->getFnParent();
18360
18361 // Look up the function name in the scope.
18362 Previous.clear(Kind: LookupLocalFriendName);
18363 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18364
18365 if (!Previous.empty()) {
18366 // All possible previous declarations must have the same context:
18367 // either they were declared at block scope or they are members of
18368 // one of the enclosing local classes.
18369 DC = Previous.getRepresentativeDecl()->getDeclContext();
18370 } else {
18371 // This is ill-formed, but provide the context that we would have
18372 // declared the function in, if we were permitted to, for error recovery.
18373 DC = FunctionContainingLocalClass;
18374 }
18375 adjustContextForLocalExternDecl(DC);
18376
18377 // - There's no scope specifier, in which case we just go to the
18378 // appropriate scope and look for a function or function template
18379 // there as appropriate.
18380 } else if (SS.isInvalid() || !SS.isSet()) {
18381 // C++11 [namespace.memdef]p3:
18382 // If the name in a friend declaration is neither qualified nor
18383 // a template-id and the declaration is a function or an
18384 // elaborated-type-specifier, the lookup to determine whether
18385 // the entity has been previously declared shall not consider
18386 // any scopes outside the innermost enclosing namespace.
18387
18388 // Find the appropriate context according to the above.
18389 DC = CurContext;
18390
18391 // Skip class contexts. If someone can cite chapter and verse
18392 // for this behavior, that would be nice --- it's what GCC and
18393 // EDG do, and it seems like a reasonable intent, but the spec
18394 // really only says that checks for unqualified existing
18395 // declarations should stop at the nearest enclosing namespace,
18396 // not that they should only consider the nearest enclosing
18397 // namespace.
18398 while (DC->isRecord())
18399 DC = DC->getParent();
18400
18401 DeclContext *LookupDC = DC->getNonTransparentContext();
18402 while (true) {
18403 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18404
18405 if (!Previous.empty()) {
18406 DC = LookupDC;
18407 break;
18408 }
18409
18410 if (isTemplateId) {
18411 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18412 } else {
18413 if (LookupDC->isFileContext()) break;
18414 }
18415 LookupDC = LookupDC->getParent();
18416 }
18417
18418 DCScope = getScopeForDeclContext(S, DC);
18419
18420 // - There's a non-dependent scope specifier, in which case we
18421 // compute it and do a previous lookup there for a function
18422 // or function template.
18423 } else if (!SS.getScopeRep().isDependent()) {
18424 DC = computeDeclContext(SS);
18425 if (!DC) return nullptr;
18426
18427 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18428
18429 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18430
18431 // C++ [class.friend]p1: A friend of a class is a function or
18432 // class that is not a member of the class . . .
18433 if (DC->Equals(DC: CurContext))
18434 Diag(Loc: DS.getFriendSpecLoc(),
18435 DiagID: getLangOpts().CPlusPlus11 ?
18436 diag::warn_cxx98_compat_friend_is_member :
18437 diag::err_friend_is_member);
18438
18439 // - There's a scope specifier that does not match any template
18440 // parameter lists, in which case we use some arbitrary context,
18441 // create a method or method template, and wait for instantiation.
18442 // - There's a scope specifier that does match some template
18443 // parameter lists, which we don't handle right now.
18444 } else {
18445 DC = CurContext;
18446 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18447 }
18448
18449 if (!DC->isRecord()) {
18450 int DiagArg = -1;
18451 switch (D.getName().getKind()) {
18452 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18453 case UnqualifiedIdKind::IK_ConstructorName:
18454 DiagArg = 0;
18455 break;
18456 case UnqualifiedIdKind::IK_DestructorName:
18457 DiagArg = 1;
18458 break;
18459 case UnqualifiedIdKind::IK_ConversionFunctionId:
18460 DiagArg = 2;
18461 break;
18462 case UnqualifiedIdKind::IK_DeductionGuideName:
18463 DiagArg = 3;
18464 break;
18465 case UnqualifiedIdKind::IK_Identifier:
18466 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18467 case UnqualifiedIdKind::IK_LiteralOperatorId:
18468 case UnqualifiedIdKind::IK_OperatorFunctionId:
18469 case UnqualifiedIdKind::IK_TemplateId:
18470 break;
18471 }
18472 // This implies that it has to be an operator or function.
18473 if (DiagArg >= 0) {
18474 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18475 return nullptr;
18476 }
18477 }
18478
18479 // FIXME: This is an egregious hack to cope with cases where the scope stack
18480 // does not contain the declaration context, i.e., in an out-of-line
18481 // definition of a class.
18482 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18483 if (!DCScope) {
18484 FakeDCScope.setEntity(DC);
18485 DCScope = &FakeDCScope;
18486 }
18487
18488 bool AddToScope = true;
18489 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18490 TemplateParamLists: TemplateParams, AddToScope);
18491 if (!ND) return nullptr;
18492
18493 assert(ND->getLexicalDeclContext() == CurContext);
18494
18495 // If we performed typo correction, we might have added a scope specifier
18496 // and changed the decl context.
18497 DC = ND->getDeclContext();
18498
18499 // Add the function declaration to the appropriate lookup tables,
18500 // adjusting the redeclarations list as necessary. We don't
18501 // want to do this yet if the friending class is dependent.
18502 //
18503 // Also update the scope-based lookup if the target context's
18504 // lookup context is in lexical scope.
18505 if (!CurContext->isDependentContext()) {
18506 DC = DC->getRedeclContext();
18507 DC->makeDeclVisibleInContext(D: ND);
18508 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18509 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18510 }
18511
18512 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18513 L: D.getIdentifierLoc(), Friend_: ND,
18514 FriendL: DS.getFriendSpecLoc());
18515 FrD->setAccess(AS_public);
18516 CurContext->addDecl(D: FrD);
18517
18518 if (ND->isInvalidDecl()) {
18519 FrD->setInvalidDecl();
18520 } else {
18521 if (DC->isRecord()) CheckFriendAccess(D: ND);
18522
18523 FunctionDecl *FD;
18524 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18525 FD = FTD->getTemplatedDecl();
18526 else
18527 FD = cast<FunctionDecl>(Val: ND);
18528
18529 // C++ [class.friend]p6:
18530 // A function may be defined in a friend declaration of a class if and
18531 // only if the class is a non-local class, and the function name is
18532 // unqualified.
18533 if (D.isFunctionDefinition()) {
18534 // Qualified friend function definition.
18535 if (SS.isNotEmpty()) {
18536 // FIXME: We should only do this if the scope specifier names the
18537 // innermost enclosing namespace; otherwise the fixit changes the
18538 // meaning of the code.
18539 SemaDiagnosticBuilder DB =
18540 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18541
18542 DB << SS.getScopeRep();
18543 if (DC->isFileContext())
18544 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18545
18546 // Friend function defined in a local class.
18547 } else if (FunctionContainingLocalClass) {
18548 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18549
18550 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18551 // a template-id, the function name is not unqualified because these is
18552 // no name. While the wording requires some reading in-between the
18553 // lines, GCC, MSVC, and EDG all consider a friend function
18554 // specialization definitions to be de facto explicit specialization
18555 // and diagnose them as such.
18556 } else if (isTemplateId) {
18557 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18558 }
18559 }
18560
18561 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18562 // default argument expression, that declaration shall be a definition
18563 // and shall be the only declaration of the function or function
18564 // template in the translation unit.
18565 if (functionDeclHasDefaultArgument(FD)) {
18566 // We can't look at FD->getPreviousDecl() because it may not have been set
18567 // if we're in a dependent context. If the function is known to be a
18568 // redeclaration, we will have narrowed Previous down to the right decl.
18569 if (D.isRedeclaration()) {
18570 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18571 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18572 DiagID: diag::note_previous_declaration);
18573 } else if (!D.isFunctionDefinition())
18574 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18575 }
18576
18577 // Mark templated-scope function declarations as unsupported.
18578 if (FD->getNumTemplateParameterLists() && SS.isValid()) {
18579 Diag(Loc: FD->getLocation(), DiagID: diag::warn_template_qualified_friend_unsupported)
18580 << SS.getScopeRep() << SS.getRange()
18581 << cast<CXXRecordDecl>(Val: CurContext);
18582 FrD->setUnsupportedFriend(true);
18583 }
18584 }
18585
18586 warnOnReservedIdentifier(D: ND);
18587
18588 return ND;
18589}
18590
18591void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18592 StringLiteral *Message) {
18593 AdjustDeclIfTemplate(Decl&: Dcl);
18594
18595 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18596 if (!Fn) {
18597 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18598 return;
18599 }
18600
18601 // Deleted function does not have a body.
18602 Fn->setWillHaveBody(false);
18603
18604 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18605 // Don't consider the implicit declaration we generate for explicit
18606 // specializations. FIXME: Do not generate these implicit declarations.
18607 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18608 Prev->getPreviousDecl()) &&
18609 !Prev->isDefined()) {
18610 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18611 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18612 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18613 : diag::note_previous_declaration);
18614 // We can't recover from this; the declaration might have already
18615 // been used.
18616 Fn->setInvalidDecl();
18617 return;
18618 }
18619
18620 // To maintain the invariant that functions are only deleted on their first
18621 // declaration, mark the implicitly-instantiated declaration of the
18622 // explicitly-specialized function as deleted instead of marking the
18623 // instantiated redeclaration.
18624 Fn = Fn->getCanonicalDecl();
18625 }
18626
18627 // dllimport/dllexport cannot be deleted.
18628 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18629 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18630 Fn->setInvalidDecl();
18631 }
18632
18633 // C++11 [basic.start.main]p3:
18634 // A program that defines main as deleted [...] is ill-formed.
18635 if (Fn->isMain())
18636 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18637
18638 // C++11 [dcl.fct.def.delete]p4:
18639 // A deleted function is implicitly inline.
18640 Fn->setImplicitlyInline();
18641 Fn->setDeletedAsWritten(D: true, Message);
18642}
18643
18644void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18645 if (!Dcl || Dcl->isInvalidDecl())
18646 return;
18647
18648 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18649 if (!FD) {
18650 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18651 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18652 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18653 return;
18654 }
18655 }
18656
18657 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18658 << getLangOpts().CPlusPlus20;
18659 return;
18660 }
18661
18662 // Reject if this can't possibly be a defaultable function.
18663 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18664 if (!DefKind &&
18665 // A dependent function that doesn't locally look defaultable can
18666 // still instantiate to a defaultable function if it's a constructor
18667 // or assignment operator.
18668 (!FD->isDependentContext() ||
18669 (!isa<CXXConstructorDecl>(Val: FD) &&
18670 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18671 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18672 << getLangOpts().CPlusPlus20;
18673 return;
18674 }
18675
18676 // Issue compatibility warning. We already warned if the operator is
18677 // 'operator<=>' when parsing the '<=>' token.
18678 if (DefKind.isComparison() &&
18679 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18680 Diag(Loc: DefaultLoc, DiagID: getLangOpts().CPlusPlus20
18681 ? diag::warn_cxx17_compat_defaulted_comparison
18682 : diag::ext_defaulted_comparison);
18683 }
18684
18685 FD->setDefaulted();
18686 FD->setExplicitlyDefaulted();
18687 FD->setDefaultLoc(DefaultLoc);
18688
18689 // Defer checking functions that are defaulted in a dependent context.
18690 if (FD->isDependentContext())
18691 return;
18692
18693 // Unset that we will have a body for this function. We might not,
18694 // if it turns out to be trivial, and we don't need this marking now
18695 // that we've marked it as defaulted.
18696 FD->setWillHaveBody(false);
18697
18698 if (DefKind.isComparison()) {
18699 // If this comparison's defaulting occurs within the definition of its
18700 // lexical class context, we have to do the checking when complete.
18701 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
18702 if (!RD->isCompleteDefinition())
18703 return;
18704 }
18705
18706 // If this member fn was defaulted on its first declaration, we will have
18707 // already performed the checking in CheckCompletedCXXClass. Such a
18708 // declaration doesn't trigger an implicit definition.
18709 if (isa<CXXMethodDecl>(Val: FD)) {
18710 const FunctionDecl *Primary = FD;
18711 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18712 // Ask the template instantiation pattern that actually had the
18713 // '= default' on it.
18714 Primary = Pattern;
18715 if (Primary->getCanonicalDecl()->isDefaulted())
18716 return;
18717 }
18718
18719 if (DefKind.isComparison()) {
18720 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18721 FD->setInvalidDecl();
18722 else
18723 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18724 } else {
18725 auto *MD = cast<CXXMethodDecl>(Val: FD);
18726
18727 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18728 DefaultLoc))
18729 MD->setInvalidDecl();
18730 else
18731 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
18732 }
18733}
18734
18735static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18736 for (Stmt *SubStmt : S->children()) {
18737 if (!SubStmt)
18738 continue;
18739 if (isa<ReturnStmt>(Val: SubStmt))
18740 Self.Diag(Loc: SubStmt->getBeginLoc(),
18741 DiagID: diag::err_return_in_constructor_handler);
18742 if (!isa<Expr>(Val: SubStmt))
18743 SearchForReturnInStmt(Self, S: SubStmt);
18744 }
18745}
18746
18747void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18748 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18749 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18750 SearchForReturnInStmt(Self&: *this, S: Handler);
18751 }
18752}
18753
18754void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18755 StringLiteral *DeletedMessage) {
18756 switch (BodyKind) {
18757 case FnBodyKind::Delete:
18758 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
18759 break;
18760 case FnBodyKind::Default:
18761 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18762 break;
18763 case FnBodyKind::Other:
18764 llvm_unreachable(
18765 "Parsed function body should be '= delete;' or '= default;'");
18766 }
18767}
18768
18769bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18770 const CXXMethodDecl *Old) {
18771 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18772 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18773
18774 if (OldFT->hasExtParameterInfos()) {
18775 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18776 // A parameter of the overriding method should be annotated with noescape
18777 // if the corresponding parameter of the overridden method is annotated.
18778 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18779 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18780 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
18781 DiagID: diag::warn_overriding_method_missing_noescape);
18782 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
18783 DiagID: diag::note_overridden_marked_noescape);
18784 }
18785 }
18786
18787 // SME attributes must match when overriding a function declaration.
18788 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18789 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
18790 << New << New->getType() << Old->getType();
18791 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18792 return true;
18793 }
18794
18795 // Virtual overrides must have the same code_seg.
18796 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18797 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18798 if ((NewCSA || OldCSA) &&
18799 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18800 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
18801 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
18802 return true;
18803 }
18804
18805 // Virtual overrides: check for matching effects.
18806 if (Context.hasAnyFunctionEffects()) {
18807 const auto OldFX = Old->getFunctionEffects();
18808 const auto NewFXOrig = New->getFunctionEffects();
18809
18810 if (OldFX != NewFXOrig) {
18811 FunctionEffectSet NewFX(NewFXOrig);
18812 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18813 FunctionEffectSet::Conflicts Errs;
18814 for (const auto &Diff : Diffs) {
18815 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
18816 case FunctionEffectDiff::OverrideResult::NoAction:
18817 break;
18818 case FunctionEffectDiff::OverrideResult::Warn:
18819 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
18820 << Diff.effectName();
18821 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18822 << Old->getReturnTypeSourceRange();
18823 break;
18824 case FunctionEffectDiff::OverrideResult::Merge: {
18825 NewFX.insert(NewEC: Diff.Old.value(), Errs);
18826 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18827 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18828 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18829 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
18830 Args: NewFT->getParamTypes(), EPI);
18831 New->setType(ModQT);
18832 if (Errs.empty()) {
18833 // A warning here is somewhat pedantic. Skip this if there was
18834 // already a merge conflict, which is more serious.
18835 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
18836 << Diff.effectName();
18837 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18838 << Old->getReturnTypeSourceRange();
18839 }
18840 break;
18841 }
18842 }
18843 }
18844 if (!Errs.empty())
18845 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
18846 OldLoc: Old->getLocation());
18847 }
18848 }
18849
18850 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18851
18852 // If the calling conventions match, everything is fine
18853 if (NewCC == OldCC)
18854 return false;
18855
18856 // If the calling conventions mismatch because the new function is static,
18857 // suppress the calling convention mismatch error; the error about static
18858 // function override (err_static_overrides_virtual from
18859 // Sema::CheckFunctionDeclaration) is more clear.
18860 if (New->getStorageClass() == SC_Static)
18861 return false;
18862
18863 Diag(Loc: New->getLocation(),
18864 DiagID: diag::err_conflicting_overriding_cc_attributes)
18865 << New->getDeclName() << New->getType() << Old->getType();
18866 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18867 return true;
18868}
18869
18870bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18871 const CXXMethodDecl *Old) {
18872 // CWG2553
18873 // A virtual function shall not be an explicit object member function.
18874 if (!New->isExplicitObjectMemberFunction())
18875 return true;
18876 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
18877 DiagID: diag::err_explicit_object_parameter_nonmember)
18878 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18879 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18880 New->setInvalidDecl();
18881 return false;
18882}
18883
18884bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18885 const CXXMethodDecl *Old) {
18886 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18887 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18888
18889 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18890 NewTy->isDependentType() || OldTy->isDependentType())
18891 return false;
18892
18893 // Check if the return types are covariant
18894 QualType NewClassTy, OldClassTy;
18895
18896 /// Both types must be pointers or references to classes.
18897 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18898 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18899 NewClassTy = NewPT->getPointeeType();
18900 OldClassTy = OldPT->getPointeeType();
18901 }
18902 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18903 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18904 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18905 NewClassTy = NewRT->getPointeeType();
18906 OldClassTy = OldRT->getPointeeType();
18907 }
18908 }
18909 }
18910
18911 // The return types aren't either both pointers or references to a class type.
18912 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18913 Diag(Loc: New->getLocation(),
18914 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
18915 << New->getDeclName() << NewTy << OldTy
18916 << New->getReturnTypeSourceRange();
18917 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18918 << Old->getReturnTypeSourceRange();
18919
18920 return true;
18921 }
18922
18923 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
18924 // C++14 [class.virtual]p8:
18925 // If the class type in the covariant return type of D::f differs from
18926 // that of B::f, the class type in the return type of D::f shall be
18927 // complete at the point of declaration of D::f or shall be the class
18928 // type D.
18929 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18930 if (!RD->isBeingDefined() &&
18931 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
18932 DiagID: diag::err_covariant_return_incomplete,
18933 Args: New->getDeclName()))
18934 return true;
18935 }
18936
18937 // Check if the new class derives from the old class.
18938 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
18939 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
18940 << New->getDeclName() << NewTy << OldTy
18941 << New->getReturnTypeSourceRange();
18942 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18943 << Old->getReturnTypeSourceRange();
18944 return true;
18945 }
18946
18947 // Check if we the conversion from derived to base is valid.
18948 if (CheckDerivedToBaseConversion(
18949 Derived: NewClassTy, Base: OldClassTy,
18950 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
18951 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
18952 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
18953 Name: New->getDeclName(), BasePath: nullptr)) {
18954 // FIXME: this note won't trigger for delayed access control
18955 // diagnostics, and it's impossible to get an undelayed error
18956 // here from access control during the original parse because
18957 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
18958 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18959 << Old->getReturnTypeSourceRange();
18960 return true;
18961 }
18962 }
18963
18964 // The qualifiers of the return types must be the same.
18965 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
18966 Diag(Loc: New->getLocation(),
18967 DiagID: diag::err_covariant_return_type_different_qualifications)
18968 << New->getDeclName() << NewTy << OldTy
18969 << New->getReturnTypeSourceRange();
18970 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18971 << Old->getReturnTypeSourceRange();
18972 return true;
18973 }
18974
18975
18976 // The new class type must have the same or less qualifiers as the old type.
18977 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
18978 Diag(Loc: New->getLocation(),
18979 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
18980 << New->getDeclName() << NewTy << OldTy
18981 << New->getReturnTypeSourceRange();
18982 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18983 << Old->getReturnTypeSourceRange();
18984 return true;
18985 }
18986
18987 return false;
18988}
18989
18990bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
18991 SourceLocation EndLoc = InitRange.getEnd();
18992 if (EndLoc.isValid())
18993 Method->setRangeEnd(EndLoc);
18994
18995 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
18996 Method->setIsPureVirtual();
18997 return false;
18998 }
18999
19000 if (!Method->isInvalidDecl())
19001 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19002 << Method->getDeclName() << InitRange;
19003 return true;
19004}
19005
19006void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19007 if (D->getFriendObjectKind())
19008 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19009 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19010 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19011 else
19012 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19013}
19014
19015/// Invoked when we are about to parse an initializer for the declaration
19016/// 'Dcl'.
19017///
19018/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19019/// static data member of class X, names should be looked up in the scope of
19020/// class X. If the declaration had a scope specifier, a scope will have
19021/// been created and passed in for this purpose. Otherwise, S will be null.
19022void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19023 assert(D && !D->isInvalidDecl());
19024
19025 // We will always have a nested name specifier here, but this declaration
19026 // might not be out of line if the specifier names the current namespace:
19027 // extern int n;
19028 // int ::n = 0;
19029 if (S && D->isOutOfLine())
19030 EnterDeclaratorContext(S, DC: D->getDeclContext());
19031
19032 PushExpressionEvaluationContext(
19033 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19034 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19035}
19036
19037void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19038 assert(D);
19039
19040 if (S && D->isOutOfLine())
19041 ExitDeclaratorContext(S);
19042
19043 PopExpressionEvaluationContext();
19044}
19045
19046DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19047 // C++ 6.4p2:
19048 // The declarator shall not specify a function or an array.
19049 // The type-specifier-seq shall not contain typedef and shall not declare a
19050 // new class or enumeration.
19051 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19052 "Parser allowed 'typedef' as storage class of condition decl.");
19053
19054 Decl *Dcl = ActOnDeclarator(S, D);
19055 if (!Dcl)
19056 return true;
19057
19058 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19059 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19060 << D.getSourceRange();
19061 return true;
19062 }
19063
19064 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19065 VD->setCXXCondDecl();
19066
19067 return Dcl;
19068}
19069
19070void Sema::LoadExternalVTableUses() {
19071 if (!ExternalSource)
19072 return;
19073
19074 SmallVector<ExternalVTableUse, 4> VTables;
19075 ExternalSource->ReadUsedVTables(VTables);
19076 SmallVector<VTableUse, 4> NewUses;
19077 for (const ExternalVTableUse &VTable : VTables) {
19078 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19079 VTablesUsed.find(Val: VTable.Record);
19080 // Even if a definition wasn't required before, it may be required now.
19081 if (Pos != VTablesUsed.end()) {
19082 if (!Pos->second && VTable.DefinitionRequired)
19083 Pos->second = true;
19084 continue;
19085 }
19086
19087 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19088 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19089 }
19090
19091 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19092}
19093
19094void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19095 bool DefinitionRequired) {
19096 // Ignore any vtable uses in unevaluated operands or for classes that do
19097 // not have a vtable.
19098 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19099 CurContext->isDependentContext() || isUnevaluatedContext())
19100 return;
19101 // Do not mark as used if compiling for the device outside of the target
19102 // region.
19103 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19104 !OpenMP().isInOpenMPDeclareTargetContext() &&
19105 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19106 if (!DefinitionRequired)
19107 MarkVirtualMembersReferenced(Loc, RD: Class);
19108 return;
19109 }
19110
19111 // Try to insert this class into the map.
19112 LoadExternalVTableUses();
19113 Class = Class->getCanonicalDecl();
19114 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19115 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19116 if (!Pos.second) {
19117 // If we already had an entry, check to see if we are promoting this vtable
19118 // to require a definition. If so, we need to reappend to the VTableUses
19119 // list, since we may have already processed the first entry.
19120 if (DefinitionRequired && !Pos.first->second) {
19121 Pos.first->second = true;
19122 } else {
19123 // Otherwise, we can early exit.
19124 return;
19125 }
19126 } else {
19127 // The Microsoft ABI requires that we perform the destructor body
19128 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19129 // the deleting destructor is emitted with the vtable, not with the
19130 // destructor definition as in the Itanium ABI.
19131 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19132 CXXDestructorDecl *DD = Class->getDestructor();
19133 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19134 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19135 // If this is an out-of-line declaration, marking it referenced will
19136 // not do anything. Manually call CheckDestructor to look up operator
19137 // delete().
19138 ContextRAII SavedContext(*this, DD);
19139 CheckDestructor(Destructor: DD);
19140 if (!DD->getOperatorDelete())
19141 DD->setInvalidDecl();
19142 } else {
19143 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19144 }
19145 }
19146 }
19147 }
19148
19149 // Local classes need to have their virtual members marked
19150 // immediately. For all other classes, we mark their virtual members
19151 // at the end of the translation unit.
19152 if (Class->isLocalClass())
19153 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19154 else
19155 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19156}
19157
19158bool Sema::DefineUsedVTables() {
19159 LoadExternalVTableUses();
19160 if (VTableUses.empty())
19161 return false;
19162
19163 // Note: The VTableUses vector could grow as a result of marking
19164 // the members of a class as "used", so we check the size each
19165 // time through the loop and prefer indices (which are stable) to
19166 // iterators (which are not).
19167 bool DefinedAnything = false;
19168 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19169 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19170 if (!Class)
19171 continue;
19172 TemplateSpecializationKind ClassTSK =
19173 Class->getTemplateSpecializationKind();
19174
19175 SourceLocation Loc = VTableUses[I].second;
19176
19177 bool DefineVTable = true;
19178
19179 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19180 // V-tables for non-template classes with an owning module are always
19181 // uniquely emitted in that module.
19182 if (Class->isInCurrentModuleUnit()) {
19183 DefineVTable = true;
19184 } else if (KeyFunction && !KeyFunction->hasBody()) {
19185 // If this class has a key function, but that key function is
19186 // defined in another translation unit, we don't need to emit the
19187 // vtable even though we're using it.
19188 // The key function is in another translation unit.
19189 DefineVTable = false;
19190 TemplateSpecializationKind TSK =
19191 KeyFunction->getTemplateSpecializationKind();
19192 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19193 TSK != TSK_ImplicitInstantiation &&
19194 "Instantiations don't have key functions");
19195 (void)TSK;
19196 } else if (!KeyFunction) {
19197 // If we have a class with no key function that is the subject
19198 // of an explicit instantiation declaration, suppress the
19199 // vtable; it will live with the explicit instantiation
19200 // definition.
19201 bool IsExplicitInstantiationDeclaration =
19202 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19203 for (auto *R : Class->redecls()) {
19204 TemplateSpecializationKind TSK
19205 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19206 if (TSK == TSK_ExplicitInstantiationDeclaration)
19207 IsExplicitInstantiationDeclaration = true;
19208 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19209 IsExplicitInstantiationDeclaration = false;
19210 break;
19211 }
19212 }
19213
19214 if (IsExplicitInstantiationDeclaration) {
19215 const bool HasExcludeFromExplicitInstantiation =
19216 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19217 // If the class has a member function declared with
19218 // `__attribute__((exclude_from_explicit_instantiation))`, the
19219 // explicit instantiation declaration should not suppress emitting
19220 // the vtable, since the corresponding explicit instantiation
19221 // definition might not emit the vtable if a triggering method is
19222 // excluded.
19223 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19224 });
19225 if (!HasExcludeFromExplicitInstantiation)
19226 DefineVTable = false;
19227 }
19228 }
19229
19230 // The exception specifications for all virtual members may be needed even
19231 // if we are not providing an authoritative form of the vtable in this TU.
19232 // We may choose to emit it available_externally anyway.
19233 if (!DefineVTable) {
19234 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19235 continue;
19236 }
19237
19238 // Mark all of the virtual members of this class as referenced, so
19239 // that we can build a vtable. Then, tell the AST consumer that a
19240 // vtable for this class is required.
19241 DefinedAnything = true;
19242 MarkVirtualMembersReferenced(Loc, RD: Class);
19243 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19244 if (VTablesUsed[Canonical] && !Class->shouldEmitInExternalSource())
19245 Consumer.HandleVTable(RD: Class);
19246
19247 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19248 // no key function or the key function is inlined. Don't warn in C++ ABIs
19249 // that lack key functions, since the user won't be able to make one.
19250 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19251 Class->isExternallyVisible() && ClassTSK != TSK_ImplicitInstantiation &&
19252 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19253 const FunctionDecl *KeyFunctionDef = nullptr;
19254 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19255 KeyFunctionDef->isInlined()))
19256 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19257 }
19258 }
19259 VTableUses.clear();
19260
19261 return DefinedAnything;
19262}
19263
19264void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19265 const CXXRecordDecl *RD) {
19266 for (const auto *I : RD->methods())
19267 if (I->isVirtual() && !I->isPureVirtual())
19268 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19269}
19270
19271void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19272 const CXXRecordDecl *RD,
19273 bool ConstexprOnly) {
19274 // Mark all functions which will appear in RD's vtable as used.
19275 CXXFinalOverriderMap FinalOverriders;
19276 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19277 for (const auto &FinalOverrider : FinalOverriders) {
19278 for (const auto &OverridingMethod : FinalOverrider.second) {
19279 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19280 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19281
19282 // C++ [basic.def.odr]p2:
19283 // [...] A virtual member function is used if it is not pure. [...]
19284 if (!Overrider->isPureVirtual() &&
19285 (!ConstexprOnly || Overrider->isConstexpr()))
19286 MarkFunctionReferenced(Loc, Func: Overrider);
19287 }
19288 }
19289
19290 // Only classes that have virtual bases need a VTT.
19291 if (RD->getNumVBases() == 0)
19292 return;
19293
19294 for (const auto &I : RD->bases()) {
19295 const auto *Base = I.getType()->castAsCXXRecordDecl();
19296 if (Base->getNumVBases() == 0)
19297 continue;
19298 MarkVirtualMembersReferenced(Loc, RD: Base);
19299 }
19300}
19301
19302static
19303void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19304 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19305 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19306 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19307 Sema &S) {
19308 if (Ctor->isInvalidDecl())
19309 return;
19310
19311 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19312
19313 // Target may not be determinable yet, for instance if this is a dependent
19314 // call in an uninstantiated template.
19315 if (Target) {
19316 const FunctionDecl *FNTarget = nullptr;
19317 (void)Target->hasBody(Definition&: FNTarget);
19318 Target = const_cast<CXXConstructorDecl*>(
19319 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19320 }
19321
19322 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19323 // Avoid dereferencing a null pointer here.
19324 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19325
19326 if (!Current.insert(Ptr: Canonical).second)
19327 return;
19328
19329 // We know that beyond here, we aren't chaining into a cycle.
19330 if (!Target || !Target->isDelegatingConstructor() ||
19331 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19332 Valid.insert_range(R&: Current);
19333 Current.clear();
19334 // We've hit a cycle.
19335 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19336 Current.count(Ptr: TCanonical)) {
19337 // If we haven't diagnosed this cycle yet, do so now.
19338 if (!Invalid.count(Ptr: TCanonical)) {
19339 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19340 DiagID: diag::warn_delegating_ctor_cycle)
19341 << Ctor;
19342
19343 // Don't add a note for a function delegating directly to itself.
19344 if (TCanonical != Canonical)
19345 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19346
19347 CXXConstructorDecl *C = Target;
19348 while (C->getCanonicalDecl() != Canonical) {
19349 const FunctionDecl *FNTarget = nullptr;
19350 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19351 assert(FNTarget && "Ctor cycle through bodiless function");
19352
19353 C = const_cast<CXXConstructorDecl*>(
19354 cast<CXXConstructorDecl>(Val: FNTarget));
19355 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19356 }
19357 }
19358
19359 Invalid.insert_range(R&: Current);
19360 Current.clear();
19361 } else {
19362 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19363 }
19364}
19365
19366
19367void Sema::CheckDelegatingCtorCycles() {
19368 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19369
19370 for (DelegatingCtorDeclsType::iterator
19371 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19372 E = DelegatingCtorDecls.end();
19373 I != E; ++I)
19374 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19375
19376 for (CXXConstructorDecl *CI : Invalid)
19377 CI->setInvalidDecl();
19378}
19379
19380namespace {
19381 /// AST visitor that finds references to the 'this' expression.
19382class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19383 Sema &S;
19384
19385public:
19386 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19387
19388 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19389 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19390 << E->isImplicit();
19391 return false;
19392 }
19393};
19394}
19395
19396bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19397 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19398 if (!TSInfo)
19399 return false;
19400
19401 TypeLoc TL = TSInfo->getTypeLoc();
19402 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19403 if (!ProtoTL)
19404 return false;
19405
19406 // C++11 [expr.prim.general]p3:
19407 // [The expression this] shall not appear before the optional
19408 // cv-qualifier-seq and it shall not appear within the declaration of a
19409 // static member function (although its type and value category are defined
19410 // within a static member function as they are within a non-static member
19411 // function). [ Note: this is because declaration matching does not occur
19412 // until the complete declarator is known. - end note ]
19413 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19414 FindCXXThisExpr Finder(*this);
19415
19416 // If the return type came after the cv-qualifier-seq, check it now.
19417 if (Proto->hasTrailingReturn() &&
19418 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19419 return true;
19420
19421 // Check the exception specification.
19422 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19423 return true;
19424
19425 // Check the trailing requires clause
19426 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19427 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19428 return true;
19429
19430 return checkThisInStaticMemberFunctionAttributes(Method);
19431}
19432
19433bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19434 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19435 if (!TSInfo)
19436 return false;
19437
19438 TypeLoc TL = TSInfo->getTypeLoc();
19439 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19440 if (!ProtoTL)
19441 return false;
19442
19443 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19444 FindCXXThisExpr Finder(*this);
19445
19446 switch (Proto->getExceptionSpecType()) {
19447 case EST_Unparsed:
19448 case EST_Uninstantiated:
19449 case EST_Unevaluated:
19450 case EST_BasicNoexcept:
19451 case EST_NoThrow:
19452 case EST_DynamicNone:
19453 case EST_MSAny:
19454 case EST_None:
19455 break;
19456
19457 case EST_DependentNoexcept:
19458 case EST_NoexceptFalse:
19459 case EST_NoexceptTrue:
19460 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19461 return true;
19462 [[fallthrough]];
19463
19464 case EST_Dynamic:
19465 for (const auto &E : Proto->exceptions()) {
19466 if (!Finder.TraverseType(T: E))
19467 return true;
19468 }
19469 break;
19470 }
19471
19472 return false;
19473}
19474
19475bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19476 FindCXXThisExpr Finder(*this);
19477
19478 // Check attributes.
19479 for (const auto *A : Method->attrs()) {
19480 // FIXME: This should be emitted by tblgen.
19481 Expr *Arg = nullptr;
19482 ArrayRef<Expr *> Args;
19483 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19484 Arg = G->getArg();
19485 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19486 Arg = G->getArg();
19487 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19488 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19489 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19490 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19491 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19492 Arg = LR->getArg();
19493 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19494 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19495 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19496 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19497 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19498 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19499 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19500 Arg = AC->getSuccessValue();
19501 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19502 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19503 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19504
19505 if (Arg && !Finder.TraverseStmt(S: Arg))
19506 return true;
19507
19508 for (Expr *A : Args) {
19509 if (!Finder.TraverseStmt(S: A))
19510 return true;
19511 }
19512 }
19513
19514 return false;
19515}
19516
19517void Sema::checkExceptionSpecification(
19518 bool IsTopLevel, ExceptionSpecificationType EST,
19519 ArrayRef<ParsedType> DynamicExceptions,
19520 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19521 SmallVectorImpl<QualType> &Exceptions,
19522 FunctionProtoType::ExceptionSpecInfo &ESI) {
19523 Exceptions.clear();
19524 ESI.Type = EST;
19525 if (EST == EST_Dynamic) {
19526 Exceptions.reserve(N: DynamicExceptions.size());
19527 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19528 // FIXME: Preserve type source info.
19529 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19530
19531 if (IsTopLevel) {
19532 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19533 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19534 if (!Unexpanded.empty()) {
19535 DiagnoseUnexpandedParameterPacks(
19536 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19537 Unexpanded);
19538 continue;
19539 }
19540 }
19541
19542 // Check that the type is valid for an exception spec, and
19543 // drop it if not.
19544 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19545 Exceptions.push_back(Elt: ET);
19546 }
19547 ESI.Exceptions = Exceptions;
19548 return;
19549 }
19550
19551 if (isComputedNoexcept(ESpecType: EST)) {
19552 assert((NoexceptExpr->isTypeDependent() ||
19553 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19554 Context.BoolTy) &&
19555 "Parser should have made sure that the expression is boolean");
19556 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19557 ESI.Type = EST_BasicNoexcept;
19558 return;
19559 }
19560
19561 ESI.NoexceptExpr = NoexceptExpr;
19562 return;
19563 }
19564}
19565
19566void Sema::actOnDelayedExceptionSpecification(
19567 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19568 ArrayRef<ParsedType> DynamicExceptions,
19569 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19570 if (!D)
19571 return;
19572
19573 // Dig out the function we're referring to.
19574 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19575 D = FTD->getTemplatedDecl();
19576
19577 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19578 if (!FD)
19579 return;
19580
19581 // Check the exception specification.
19582 llvm::SmallVector<QualType, 4> Exceptions;
19583 FunctionProtoType::ExceptionSpecInfo ESI;
19584 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19585 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19586 ESI);
19587
19588 // Update the exception specification on the function type.
19589 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19590
19591 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19592 if (MD->isStatic())
19593 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19594
19595 if (MD->isVirtual()) {
19596 // Check overrides, which we previously had to delay.
19597 for (const CXXMethodDecl *O : MD->overridden_methods())
19598 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19599 }
19600 }
19601}
19602
19603/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19604///
19605MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19606 SourceLocation DeclStart, Declarator &D,
19607 Expr *BitWidth,
19608 InClassInitStyle InitStyle,
19609 AccessSpecifier AS,
19610 const ParsedAttr &MSPropertyAttr) {
19611 const IdentifierInfo *II = D.getIdentifier();
19612 if (!II) {
19613 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19614 return nullptr;
19615 }
19616 SourceLocation Loc = D.getIdentifierLoc();
19617
19618 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19619 QualType T = TInfo->getType();
19620 if (getLangOpts().CPlusPlus) {
19621 CheckExtraCXXDefaultArguments(D);
19622
19623 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19624 UPPC: UPPC_DataMemberType)) {
19625 D.setInvalidType();
19626 T = Context.IntTy;
19627 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19628 }
19629 }
19630
19631 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19632
19633 if (D.getDeclSpec().isInlineSpecified())
19634 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19635 << getLangOpts().CPlusPlus17;
19636 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19637 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19638 DiagID: diag::err_invalid_thread)
19639 << DeclSpec::getSpecifierName(S: TSCS);
19640
19641 // Check to see if this name was declared as a member previously
19642 NamedDecl *PrevDecl = nullptr;
19643 LookupResult Previous(*this, II, Loc, LookupMemberName,
19644 RedeclarationKind::ForVisibleRedeclaration);
19645 LookupName(R&: Previous, S);
19646 switch (Previous.getResultKind()) {
19647 case LookupResultKind::Found:
19648 case LookupResultKind::FoundUnresolvedValue:
19649 PrevDecl = Previous.getAsSingle<NamedDecl>();
19650 break;
19651
19652 case LookupResultKind::FoundOverloaded:
19653 PrevDecl = Previous.getRepresentativeDecl();
19654 break;
19655
19656 case LookupResultKind::NotFound:
19657 case LookupResultKind::NotFoundInCurrentInstantiation:
19658 case LookupResultKind::Ambiguous:
19659 break;
19660 }
19661
19662 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19663 // Maybe we will complain about the shadowed template parameter.
19664 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19665 // Just pretend that we didn't see the previous declaration.
19666 PrevDecl = nullptr;
19667 }
19668
19669 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19670 PrevDecl = nullptr;
19671
19672 SourceLocation TSSL = D.getBeginLoc();
19673 MSPropertyDecl *NewPD =
19674 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
19675 Getter: MSPropertyAttr.getPropertyDataGetter(),
19676 Setter: MSPropertyAttr.getPropertyDataSetter());
19677 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
19678 NewPD->setAccess(AS);
19679
19680 if (NewPD->isInvalidDecl())
19681 Record->setInvalidDecl();
19682
19683 if (D.getDeclSpec().isModulePrivateSpecified())
19684 NewPD->setModulePrivate();
19685
19686 if (NewPD->isInvalidDecl() && PrevDecl) {
19687 // Don't introduce NewFD into scope; there's already something
19688 // with the same name in the same scope.
19689 } else if (II) {
19690 PushOnScopeChains(D: NewPD, S);
19691 } else
19692 Record->addDecl(D: NewPD);
19693
19694 return NewPD;
19695}
19696
19697void Sema::ActOnStartFunctionDeclarationDeclarator(
19698 Declarator &Declarator, unsigned TemplateParameterDepth) {
19699 auto &Info = InventedParameterInfos.emplace_back();
19700 TemplateParameterList *ExplicitParams = nullptr;
19701 ArrayRef<TemplateParameterList *> ExplicitLists =
19702 Declarator.getTemplateParameterLists();
19703 if (!ExplicitLists.empty()) {
19704 bool IsMemberSpecialization, IsInvalid;
19705 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19706 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19707 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19708 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19709 /*SuppressDiagnostic=*/true);
19710 }
19711 // C++23 [dcl.fct]p23:
19712 // An abbreviated function template can have a template-head. The invented
19713 // template-parameters are appended to the template-parameter-list after
19714 // the explicitly declared template-parameters.
19715 //
19716 // A template-head must have one or more template-parameters (read:
19717 // 'template<>' is *not* a template-head). Only append the invented
19718 // template parameters if we matched the nested-name-specifier to a non-empty
19719 // TemplateParameterList.
19720 if (ExplicitParams && !ExplicitParams->empty()) {
19721 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19722 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19723 Info.NumExplicitTemplateParams = ExplicitParams->size();
19724 } else {
19725 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19726 Info.NumExplicitTemplateParams = 0;
19727 }
19728}
19729
19730void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19731 auto &FSI = InventedParameterInfos.back();
19732 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19733 if (FSI.NumExplicitTemplateParams != 0) {
19734 TemplateParameterList *ExplicitParams =
19735 Declarator.getTemplateParameterLists().back();
19736 Declarator.setInventedTemplateParameterList(
19737 TemplateParameterList::Create(
19738 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19739 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19740 RAngleLoc: ExplicitParams->getRAngleLoc(),
19741 RequiresClause: ExplicitParams->getRequiresClause()));
19742 } else {
19743 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
19744 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
19745 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
19746 /*RequiresClause=*/nullptr));
19747 }
19748 }
19749 InventedParameterInfos.pop_back();
19750}
19751