1//===------ SemaDeclCXX.cpp - Semantic Analysis for C++ Declarations ------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements semantic analysis for C++ declarations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "TypeLocBuilder.h"
14#include "clang/AST/ASTConsumer.h"
15#include "clang/AST/ASTContext.h"
16#include "clang/AST/ASTMutationListener.h"
17#include "clang/AST/CXXInheritance.h"
18#include "clang/AST/CharUnits.h"
19#include "clang/AST/ComparisonCategories.h"
20#include "clang/AST/DeclCXX.h"
21#include "clang/AST/DeclTemplate.h"
22#include "clang/AST/DynamicRecursiveASTVisitor.h"
23#include "clang/AST/EvaluatedExprVisitor.h"
24#include "clang/AST/Expr.h"
25#include "clang/AST/ExprCXX.h"
26#include "clang/AST/RecordLayout.h"
27#include "clang/AST/StmtVisitor.h"
28#include "clang/AST/TypeLoc.h"
29#include "clang/AST/TypeOrdering.h"
30#include "clang/Basic/AttributeCommonInfo.h"
31#include "clang/Basic/PartialDiagnostic.h"
32#include "clang/Basic/Specifiers.h"
33#include "clang/Basic/TargetInfo.h"
34#include "clang/Lex/LiteralSupport.h"
35#include "clang/Lex/Preprocessor.h"
36#include "clang/Sema/CXXFieldCollector.h"
37#include "clang/Sema/DeclSpec.h"
38#include "clang/Sema/EnterExpressionEvaluationContext.h"
39#include "clang/Sema/Initialization.h"
40#include "clang/Sema/Lookup.h"
41#include "clang/Sema/Ownership.h"
42#include "clang/Sema/ParsedTemplate.h"
43#include "clang/Sema/Scope.h"
44#include "clang/Sema/ScopeInfo.h"
45#include "clang/Sema/SemaCUDA.h"
46#include "clang/Sema/SemaInternal.h"
47#include "clang/Sema/SemaObjC.h"
48#include "clang/Sema/SemaOpenMP.h"
49#include "clang/Sema/Template.h"
50#include "clang/Sema/TemplateDeduction.h"
51#include "llvm/ADT/ArrayRef.h"
52#include "llvm/ADT/STLExtras.h"
53#include "llvm/ADT/StringExtras.h"
54#include "llvm/Support/ConvertUTF.h"
55#include "llvm/Support/SaveAndRestore.h"
56#include <map>
57#include <optional>
58#include <set>
59
60using namespace clang;
61
62//===----------------------------------------------------------------------===//
63// CheckDefaultArgumentVisitor
64//===----------------------------------------------------------------------===//
65
66namespace {
67/// CheckDefaultArgumentVisitor - C++ [dcl.fct.default] Traverses
68/// the default argument of a parameter to determine whether it
69/// contains any ill-formed subexpressions. For example, this will
70/// diagnose the use of local variables or parameters within the
71/// default argument expression.
72class CheckDefaultArgumentVisitor
73 : public ConstStmtVisitor<CheckDefaultArgumentVisitor, bool> {
74 Sema &S;
75 const Expr *DefaultArg;
76
77public:
78 CheckDefaultArgumentVisitor(Sema &S, const Expr *DefaultArg)
79 : S(S), DefaultArg(DefaultArg) {}
80
81 bool VisitExpr(const Expr *Node);
82 bool VisitDeclRefExpr(const DeclRefExpr *DRE);
83 bool VisitCXXThisExpr(const CXXThisExpr *ThisE);
84 bool VisitLambdaExpr(const LambdaExpr *Lambda);
85 bool VisitPseudoObjectExpr(const PseudoObjectExpr *POE);
86 bool VisitCoawaitExpr(const CoawaitExpr *E);
87 bool VisitCoyieldExpr(const CoyieldExpr *E);
88};
89
90/// VisitExpr - Visit all of the children of this expression.
91bool CheckDefaultArgumentVisitor::VisitExpr(const Expr *Node) {
92 bool IsInvalid = false;
93 for (const Stmt *SubStmt : Node->children())
94 if (SubStmt)
95 IsInvalid |= Visit(S: SubStmt);
96 return IsInvalid;
97}
98
99/// VisitDeclRefExpr - Visit a reference to a declaration, to
100/// determine whether this declaration can be used in the default
101/// argument expression.
102bool CheckDefaultArgumentVisitor::VisitDeclRefExpr(const DeclRefExpr *DRE) {
103 const ValueDecl *Decl = DRE->getDecl();
104
105 if (!isa<VarDecl, BindingDecl>(Val: Decl))
106 return false;
107
108 if (const auto *Param = dyn_cast<ParmVarDecl>(Val: Decl)) {
109 // C++ [dcl.fct.default]p9:
110 // [...] parameters of a function shall not be used in default
111 // argument expressions, even if they are not evaluated. [...]
112 //
113 // C++17 [dcl.fct.default]p9 (by CWG 2082):
114 // [...] A parameter shall not appear as a potentially-evaluated
115 // expression in a default argument. [...]
116 //
117 if (DRE->isNonOdrUse() != NOUR_Unevaluated)
118 return S.Diag(Loc: DRE->getBeginLoc(),
119 DiagID: diag::err_param_default_argument_references_param)
120 << Param->getDeclName() << DefaultArg->getSourceRange();
121 } else if (auto *VD = Decl->getPotentiallyDecomposedVarDecl()) {
122 // C++ [dcl.fct.default]p7:
123 // Local variables shall not be used in default argument
124 // expressions.
125 //
126 // C++17 [dcl.fct.default]p7 (by CWG 2082):
127 // A local variable shall not appear as a potentially-evaluated
128 // expression in a default argument.
129 //
130 // C++20 [dcl.fct.default]p7 (DR as part of P0588R1, see also CWG 2346):
131 // Note: A local variable cannot be odr-used (6.3) in a default
132 // argument.
133 //
134 if (VD->isLocalVarDecl() && !DRE->isNonOdrUse())
135 return S.Diag(Loc: DRE->getBeginLoc(),
136 DiagID: diag::err_param_default_argument_references_local)
137 << Decl << DefaultArg->getSourceRange();
138 }
139 return false;
140}
141
142/// VisitCXXThisExpr - Visit a C++ "this" expression.
143bool CheckDefaultArgumentVisitor::VisitCXXThisExpr(const CXXThisExpr *ThisE) {
144 // C++ [dcl.fct.default]p8:
145 // The keyword this shall not be used in a default argument of a
146 // member function.
147 return S.Diag(Loc: ThisE->getBeginLoc(),
148 DiagID: diag::err_param_default_argument_references_this)
149 << ThisE->getSourceRange();
150}
151
152bool CheckDefaultArgumentVisitor::VisitPseudoObjectExpr(
153 const PseudoObjectExpr *POE) {
154 bool Invalid = false;
155 for (const Expr *E : POE->semantics()) {
156 // Look through bindings.
157 if (const auto *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
158 E = OVE->getSourceExpr();
159 assert(E && "pseudo-object binding without source expression?");
160 }
161
162 Invalid |= Visit(S: E);
163 }
164 return Invalid;
165}
166
167bool CheckDefaultArgumentVisitor::VisitLambdaExpr(const LambdaExpr *Lambda) {
168 // [expr.prim.lambda.capture]p9
169 // a lambda-expression appearing in a default argument cannot implicitly or
170 // explicitly capture any local entity. Such a lambda-expression can still
171 // have an init-capture if any full-expression in its initializer satisfies
172 // the constraints of an expression appearing in a default argument.
173 bool Invalid = false;
174 for (const LambdaCapture &LC : Lambda->captures()) {
175 if (!Lambda->isInitCapture(Capture: &LC))
176 return S.Diag(Loc: LC.getLocation(), DiagID: diag::err_lambda_capture_default_arg);
177 // Init captures are always VarDecl.
178 auto *D = cast<VarDecl>(Val: LC.getCapturedVar());
179 Invalid |= Visit(S: D->getInit());
180 }
181 return Invalid;
182}
183
184bool CheckDefaultArgumentVisitor::VisitCoawaitExpr(const CoawaitExpr *E) {
185 // [expr.await] An await-expression shall not appear in a default argument.
186 // Note that this is generally diagnosed by isValidCoroutineContext,
187 // however isValidCoroutineContext misses default argument in nested
188 // function declarations.
189 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
190 << "co_await" << E->getSourceRange();
191 return true;
192}
193
194bool CheckDefaultArgumentVisitor::VisitCoyieldExpr(const CoyieldExpr *E) {
195 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_coroutine_outside_function)
196 << "co_yield" << E->getSourceRange();
197 return true;
198}
199
200} // namespace
201
202void
203Sema::ImplicitExceptionSpecification::CalledDecl(SourceLocation CallLoc,
204 const CXXMethodDecl *Method) {
205 // If we have an MSAny spec already, don't bother.
206 if (!Method || ComputedEST == EST_MSAny)
207 return;
208
209 const FunctionProtoType *Proto
210 = Method->getType()->getAs<FunctionProtoType>();
211 Proto = Self->ResolveExceptionSpec(Loc: CallLoc, FPT: Proto);
212 if (!Proto)
213 return;
214
215 ExceptionSpecificationType EST = Proto->getExceptionSpecType();
216
217 // If we have a throw-all spec at this point, ignore the function.
218 if (ComputedEST == EST_None)
219 return;
220
221 if (EST == EST_None && Method->hasAttr<NoThrowAttr>())
222 EST = EST_BasicNoexcept;
223
224 switch (EST) {
225 case EST_Unparsed:
226 case EST_Uninstantiated:
227 case EST_Unevaluated:
228 llvm_unreachable("should not see unresolved exception specs here");
229
230 // If this function can throw any exceptions, make a note of that.
231 case EST_MSAny:
232 case EST_None:
233 // FIXME: Whichever we see last of MSAny and None determines our result.
234 // We should make a consistent, order-independent choice here.
235 ClearExceptions();
236 ComputedEST = EST;
237 return;
238 case EST_NoexceptFalse:
239 ClearExceptions();
240 ComputedEST = EST_None;
241 return;
242 // FIXME: If the call to this decl is using any of its default arguments, we
243 // need to search them for potentially-throwing calls.
244 // If this function has a basic noexcept, it doesn't affect the outcome.
245 case EST_BasicNoexcept:
246 case EST_NoexceptTrue:
247 case EST_NoThrow:
248 return;
249 // If we're still at noexcept(true) and there's a throw() callee,
250 // change to that specification.
251 case EST_DynamicNone:
252 if (ComputedEST == EST_BasicNoexcept)
253 ComputedEST = EST_DynamicNone;
254 return;
255 case EST_DependentNoexcept:
256 llvm_unreachable(
257 "should not generate implicit declarations for dependent cases");
258 case EST_Dynamic:
259 break;
260 }
261 assert(EST == EST_Dynamic && "EST case not considered earlier.");
262 assert(ComputedEST != EST_None &&
263 "Shouldn't collect exceptions when throw-all is guaranteed.");
264 ComputedEST = EST_Dynamic;
265 // Record the exceptions in this function's exception specification.
266 for (const auto &E : Proto->exceptions())
267 if (ExceptionsSeen.insert(Ptr: Self->Context.getCanonicalType(T: E)).second)
268 Exceptions.push_back(Elt: E);
269}
270
271void Sema::ImplicitExceptionSpecification::CalledStmt(Stmt *S) {
272 if (!S || ComputedEST == EST_MSAny)
273 return;
274
275 // FIXME:
276 //
277 // C++0x [except.spec]p14:
278 // [An] implicit exception-specification specifies the type-id T if and
279 // only if T is allowed by the exception-specification of a function directly
280 // invoked by f's implicit definition; f shall allow all exceptions if any
281 // function it directly invokes allows all exceptions, and f shall allow no
282 // exceptions if every function it directly invokes allows no exceptions.
283 //
284 // Note in particular that if an implicit exception-specification is generated
285 // for a function containing a throw-expression, that specification can still
286 // be noexcept(true).
287 //
288 // Note also that 'directly invoked' is not defined in the standard, and there
289 // is no indication that we should only consider potentially-evaluated calls.
290 //
291 // Ultimately we should implement the intent of the standard: the exception
292 // specification should be the set of exceptions which can be thrown by the
293 // implicit definition. For now, we assume that any non-nothrow expression can
294 // throw any exception.
295
296 if (Self->canThrow(E: S))
297 ComputedEST = EST_None;
298}
299
300ExprResult Sema::ConvertParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
301 SourceLocation EqualLoc) {
302 if (RequireCompleteType(Loc: Param->getLocation(), T: Param->getType(),
303 DiagID: diag::err_typecheck_decl_incomplete_type))
304 return true;
305
306 // C++ [dcl.fct.default]p5
307 // A default argument expression is implicitly converted (clause
308 // 4) to the parameter type. The default argument expression has
309 // the same semantic constraints as the initializer expression in
310 // a declaration of a variable of the parameter type, using the
311 // copy-initialization semantics (8.5).
312 InitializedEntity Entity = InitializedEntity::InitializeParameter(Context,
313 Parm: Param);
314 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Param->getLocation(),
315 EqualLoc);
316 InitializationSequence InitSeq(*this, Entity, Kind, Arg);
317 ExprResult Result = InitSeq.Perform(S&: *this, Entity, Kind, Args: Arg);
318 if (Result.isInvalid())
319 return true;
320 Arg = Result.getAs<Expr>();
321
322 CheckCompletedExpr(E: Arg, CheckLoc: EqualLoc);
323 Arg = MaybeCreateExprWithCleanups(SubExpr: Arg);
324
325 return Arg;
326}
327
328void Sema::SetParamDefaultArgument(ParmVarDecl *Param, Expr *Arg,
329 SourceLocation EqualLoc) {
330 // Add the default argument to the parameter
331 Param->setDefaultArg(Arg);
332
333 // We have already instantiated this parameter; provide each of the
334 // instantiations with the uninstantiated default argument.
335 UnparsedDefaultArgInstantiationsMap::iterator InstPos
336 = UnparsedDefaultArgInstantiations.find(Val: Param);
337 if (InstPos != UnparsedDefaultArgInstantiations.end()) {
338 for (auto &Instantiation : InstPos->second)
339 Instantiation->setUninstantiatedDefaultArg(Arg);
340
341 // We're done tracking this parameter's instantiations.
342 UnparsedDefaultArgInstantiations.erase(I: InstPos);
343 }
344}
345
346void
347Sema::ActOnParamDefaultArgument(Decl *param, SourceLocation EqualLoc,
348 Expr *DefaultArg) {
349 if (!param || !DefaultArg)
350 return;
351
352 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
353 UnparsedDefaultArgLocs.erase(Val: Param);
354
355 // Default arguments are only permitted in C++
356 if (!getLangOpts().CPlusPlus) {
357 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument)
358 << DefaultArg->getSourceRange();
359 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
360 }
361
362 // Check for unexpanded parameter packs.
363 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
364 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
365
366 // C++11 [dcl.fct.default]p3
367 // A default argument expression [...] shall not be specified for a
368 // parameter pack.
369 if (Param->isParameterPack()) {
370 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
371 << DefaultArg->getSourceRange();
372 // Recover by discarding the default argument.
373 Param->setDefaultArg(nullptr);
374 return;
375 }
376
377 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
378 if (Result.isInvalid())
379 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
380
381 DefaultArg = Result.getAs<Expr>();
382
383 // Check that the default argument is well-formed
384 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
385 if (DefaultArgChecker.Visit(S: DefaultArg))
386 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
387
388 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
389}
390
391void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
392 SourceLocation EqualLoc,
393 SourceLocation ArgLoc) {
394 if (!param)
395 return;
396
397 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
398 Param->setUnparsedDefaultArg();
399 UnparsedDefaultArgLocs[Param] = ArgLoc;
400}
401
402void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
403 Expr *DefaultArg) {
404 if (!param)
405 return;
406
407 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
408 Param->setInvalidDecl();
409 UnparsedDefaultArgLocs.erase(Val: Param);
410 ExprResult RE;
411 if (DefaultArg) {
412 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
413 T: Param->getType().getNonReferenceType());
414 } else {
415 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
416 T: Param->getType().getNonReferenceType());
417 }
418 Param->setDefaultArg(RE.get());
419}
420
421void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
422 // C++ [dcl.fct.default]p3
423 // A default argument expression shall be specified only in the
424 // parameter-declaration-clause of a function declaration or in a
425 // template-parameter (14.1). It shall not be specified for a
426 // parameter pack. If it is specified in a
427 // parameter-declaration-clause, it shall not occur within a
428 // declarator or abstract-declarator of a parameter-declaration.
429 bool MightBeFunction = D.isFunctionDeclarationContext();
430 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
431 DeclaratorChunk &chunk = D.getTypeObject(i);
432 if (chunk.Kind == DeclaratorChunk::Function) {
433 if (MightBeFunction) {
434 // This is a function declaration. It can have default arguments, but
435 // keep looking in case its return type is a function type with default
436 // arguments.
437 MightBeFunction = false;
438 continue;
439 }
440 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
441 ++argIdx) {
442 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
443 if (Param->hasUnparsedDefaultArg()) {
444 std::unique_ptr<CachedTokens> Toks =
445 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
446 SourceRange SR;
447 if (Toks->size() > 1)
448 SR = SourceRange((*Toks)[1].getLocation(),
449 Toks->back().getLocation());
450 else
451 SR = UnparsedDefaultArgLocs[Param];
452 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
453 << SR;
454 } else if (Param->getDefaultArg()) {
455 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
456 << Param->getDefaultArg()->getSourceRange();
457 Param->setDefaultArg(nullptr);
458 }
459 }
460 } else if (chunk.Kind != DeclaratorChunk::Paren) {
461 MightBeFunction = false;
462 }
463 }
464}
465
466static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
467 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
468 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
469 });
470}
471
472bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
473 Scope *S) {
474 bool Invalid = false;
475
476 // The declaration context corresponding to the scope is the semantic
477 // parent, unless this is a local function declaration, in which case
478 // it is that surrounding function.
479 DeclContext *ScopeDC = New->isLocalExternDecl()
480 ? New->getLexicalDeclContext()
481 : New->getDeclContext();
482
483 // Find the previous declaration for the purpose of default arguments.
484 FunctionDecl *PrevForDefaultArgs = Old;
485 for (/**/; PrevForDefaultArgs;
486 // Don't bother looking back past the latest decl if this is a local
487 // extern declaration; nothing else could work.
488 PrevForDefaultArgs = New->isLocalExternDecl()
489 ? nullptr
490 : PrevForDefaultArgs->getPreviousDecl()) {
491 // Ignore hidden declarations.
492 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
493 continue;
494
495 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
496 !New->isCXXClassMember()) {
497 // Ignore default arguments of old decl if they are not in
498 // the same scope and this is not an out-of-line definition of
499 // a member function.
500 continue;
501 }
502
503 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
504 // If only one of these is a local function declaration, then they are
505 // declared in different scopes, even though isDeclInScope may think
506 // they're in the same scope. (If both are local, the scope check is
507 // sufficient, and if neither is local, then they are in the same scope.)
508 continue;
509 }
510
511 // We found the right previous declaration.
512 break;
513 }
514
515 // C++ [dcl.fct.default]p4:
516 // For non-template functions, default arguments can be added in
517 // later declarations of a function in the same
518 // scope. Declarations in different scopes have completely
519 // distinct sets of default arguments. That is, declarations in
520 // inner scopes do not acquire default arguments from
521 // declarations in outer scopes, and vice versa. In a given
522 // function declaration, all parameters subsequent to a
523 // parameter with a default argument shall have default
524 // arguments supplied in this or previous declarations. A
525 // default argument shall not be redefined by a later
526 // declaration (not even to the same value).
527 //
528 // C++ [dcl.fct.default]p6:
529 // Except for member functions of class templates, the default arguments
530 // in a member function definition that appears outside of the class
531 // definition are added to the set of default arguments provided by the
532 // member function declaration in the class definition.
533 for (unsigned p = 0, NumParams = PrevForDefaultArgs
534 ? PrevForDefaultArgs->getNumParams()
535 : 0;
536 p < NumParams; ++p) {
537 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
538 ParmVarDecl *NewParam = New->getParamDecl(i: p);
539
540 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
541 bool NewParamHasDfl = NewParam->hasDefaultArg();
542
543 if (OldParamHasDfl && NewParamHasDfl) {
544 unsigned DiagDefaultParamID =
545 diag::err_param_default_argument_redefinition;
546
547 // MSVC accepts that default parameters be redefined for member functions
548 // of template class. The new default parameter's value is ignored.
549 Invalid = true;
550 if (getLangOpts().MicrosoftExt) {
551 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
552 if (MD && MD->getParent()->getDescribedClassTemplate()) {
553 // Merge the old default argument into the new parameter.
554 NewParam->setHasInheritedDefaultArg();
555 if (OldParam->hasUninstantiatedDefaultArg())
556 NewParam->setUninstantiatedDefaultArg(
557 OldParam->getUninstantiatedDefaultArg());
558 else
559 NewParam->setDefaultArg(OldParam->getInit());
560 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
561 Invalid = false;
562 }
563 }
564
565 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
566 // hint here. Alternatively, we could walk the type-source information
567 // for NewParam to find the last source location in the type... but it
568 // isn't worth the effort right now. This is the kind of test case that
569 // is hard to get right:
570 // int f(int);
571 // void g(int (*fp)(int) = f);
572 // void g(int (*fp)(int) = &f);
573 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
574 << NewParam->getDefaultArgRange();
575
576 // Look for the function declaration where the default argument was
577 // actually written, which may be a declaration prior to Old.
578 for (auto Older = PrevForDefaultArgs;
579 OldParam->hasInheritedDefaultArg(); /**/) {
580 Older = Older->getPreviousDecl();
581 OldParam = Older->getParamDecl(i: p);
582 }
583
584 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
585 << OldParam->getDefaultArgRange();
586 } else if (OldParamHasDfl) {
587 // Merge the old default argument into the new parameter unless the new
588 // function is a friend declaration in a template class. In the latter
589 // case the default arguments will be inherited when the friend
590 // declaration will be instantiated.
591 if (New->getFriendObjectKind() == Decl::FOK_None ||
592 !New->getLexicalDeclContext()->isDependentContext()) {
593 // It's important to use getInit() here; getDefaultArg()
594 // strips off any top-level ExprWithCleanups.
595 NewParam->setHasInheritedDefaultArg();
596 if (OldParam->hasUnparsedDefaultArg())
597 NewParam->setUnparsedDefaultArg();
598 else if (OldParam->hasUninstantiatedDefaultArg())
599 NewParam->setUninstantiatedDefaultArg(
600 OldParam->getUninstantiatedDefaultArg());
601 else
602 NewParam->setDefaultArg(OldParam->getInit());
603 }
604 } else if (NewParamHasDfl) {
605 if (New->getDescribedFunctionTemplate()) {
606 // Paragraph 4, quoted above, only applies to non-template functions.
607 Diag(Loc: NewParam->getLocation(),
608 DiagID: diag::err_param_default_argument_template_redecl)
609 << NewParam->getDefaultArgRange();
610 Diag(Loc: PrevForDefaultArgs->getLocation(),
611 DiagID: diag::note_template_prev_declaration)
612 << false;
613 } else if (New->getTemplateSpecializationKind()
614 != TSK_ImplicitInstantiation &&
615 New->getTemplateSpecializationKind() != TSK_Undeclared) {
616 // C++ [temp.expr.spec]p21:
617 // Default function arguments shall not be specified in a declaration
618 // or a definition for one of the following explicit specializations:
619 // - the explicit specialization of a function template;
620 // - the explicit specialization of a member function template;
621 // - the explicit specialization of a member function of a class
622 // template where the class template specialization to which the
623 // member function specialization belongs is implicitly
624 // instantiated.
625 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
626 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
627 << New->getDeclName()
628 << NewParam->getDefaultArgRange();
629 } else if (New->getDeclContext()->isDependentContext()) {
630 // C++ [dcl.fct.default]p6 (DR217):
631 // Default arguments for a member function of a class template shall
632 // be specified on the initial declaration of the member function
633 // within the class template.
634 //
635 // Reading the tea leaves a bit in DR217 and its reference to DR205
636 // leads me to the conclusion that one cannot add default function
637 // arguments for an out-of-line definition of a member function of a
638 // dependent type.
639 int WhichKind = 2;
640 if (CXXRecordDecl *Record
641 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
642 if (Record->getDescribedClassTemplate())
643 WhichKind = 0;
644 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
645 WhichKind = 1;
646 else
647 WhichKind = 2;
648 }
649
650 Diag(Loc: NewParam->getLocation(),
651 DiagID: diag::err_param_default_argument_member_template_redecl)
652 << WhichKind
653 << NewParam->getDefaultArgRange();
654 }
655 }
656 }
657
658 // DR1344: If a default argument is added outside a class definition and that
659 // default argument makes the function a special member function, the program
660 // is ill-formed. This can only happen for constructors.
661 if (isa<CXXConstructorDecl>(Val: New) &&
662 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
663 CXXSpecialMemberKind NewSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: New)),
664 OldSM = getSpecialMember(MD: cast<CXXMethodDecl>(Val: Old));
665 if (NewSM != OldSM) {
666 ParmVarDecl *NewParam = New->getParamDecl(i: New->getMinRequiredArguments());
667 assert(NewParam->hasDefaultArg());
668 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
669 << NewParam->getDefaultArgRange() << NewSM;
670 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
671 }
672 }
673
674 const FunctionDecl *Def;
675 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
676 // template has a constexpr specifier then all its declarations shall
677 // contain the constexpr specifier.
678 if (New->getConstexprKind() != Old->getConstexprKind()) {
679 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
680 << New << static_cast<int>(New->getConstexprKind())
681 << static_cast<int>(Old->getConstexprKind());
682 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
683 Invalid = true;
684 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
685 Old->isDefined(Definition&: Def) &&
686 // If a friend function is inlined but does not have 'inline'
687 // specifier, it is a definition. Do not report attribute conflict
688 // in this case, redefinition will be diagnosed later.
689 (New->isInlineSpecified() ||
690 New->getFriendObjectKind() == Decl::FOK_None)) {
691 // C++11 [dcl.fcn.spec]p4:
692 // If the definition of a function appears in a translation unit before its
693 // first declaration as inline, the program is ill-formed.
694 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
695 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
696 Invalid = true;
697 }
698
699 // C++17 [temp.deduct.guide]p3:
700 // Two deduction guide declarations in the same translation unit
701 // for the same class template shall not have equivalent
702 // parameter-declaration-clauses.
703 if (isa<CXXDeductionGuideDecl>(Val: New) &&
704 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
705 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
706 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
707 }
708
709 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
710 // argument expression, that declaration shall be a definition and shall be
711 // the only declaration of the function or function template in the
712 // translation unit.
713 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
714 functionDeclHasDefaultArgument(FD: Old)) {
715 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
716 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
717 Invalid = true;
718 }
719
720 // C++11 [temp.friend]p4 (DR329):
721 // When a function is defined in a friend function declaration in a class
722 // template, the function is instantiated when the function is odr-used.
723 // The same restrictions on multiple declarations and definitions that
724 // apply to non-template function declarations and definitions also apply
725 // to these implicit definitions.
726 const FunctionDecl *OldDefinition = nullptr;
727 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
728 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
729 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
730
731 return Invalid;
732}
733
734void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
735 Diag(Loc, DiagID: getLangOpts().CPlusPlus26
736 ? diag::warn_cxx23_placeholder_var_definition
737 : diag::ext_placeholder_var_definition);
738}
739
740NamedDecl *
741Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
742 MultiTemplateParamsArg TemplateParamLists) {
743 assert(D.isDecompositionDeclarator());
744 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
745
746 // The syntax only allows a decomposition declarator as a simple-declaration,
747 // a for-range-declaration, or a condition in Clang, but we parse it in more
748 // cases than that.
749 if (!D.mayHaveDecompositionDeclarator()) {
750 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
751 << Decomp.getSourceRange();
752 return nullptr;
753 }
754
755 if (!TemplateParamLists.empty()) {
756 // C++17 [temp]/1:
757 // A template defines a family of class, functions, or variables, or an
758 // alias for a family of types.
759 //
760 // Structured bindings are not included.
761 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
762 DiagID: diag::err_decomp_decl_template);
763 return nullptr;
764 }
765
766 unsigned DiagID;
767 if (!getLangOpts().CPlusPlus17)
768 DiagID = diag::compat_pre_cxx17_decomp_decl;
769 else if (D.getContext() == DeclaratorContext::Condition)
770 DiagID = getLangOpts().CPlusPlus26
771 ? diag::compat_cxx26_decomp_decl_cond
772 : diag::compat_pre_cxx26_decomp_decl_cond;
773 else
774 DiagID = diag::compat_cxx17_decomp_decl;
775
776 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
777
778 // The semantic context is always just the current context.
779 DeclContext *const DC = CurContext;
780
781 // C++17 [dcl.dcl]/8:
782 // The decl-specifier-seq shall contain only the type-specifier auto
783 // and cv-qualifiers.
784 // C++20 [dcl.dcl]/8:
785 // If decl-specifier-seq contains any decl-specifier other than static,
786 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
787 // C++23 [dcl.pre]/6:
788 // Each decl-specifier in the decl-specifier-seq shall be static,
789 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
790 // C++23 [dcl.pre]/7:
791 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
792 // constinit, static, thread_local, auto, or a cv-qualifier
793 auto &DS = D.getDeclSpec();
794 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
795 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
796 };
797
798 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
799 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
800 };
801
802 if (auto SCS = DS.getStorageClassSpec()) {
803 if (SCS == DeclSpec::SCS_static)
804 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
805 DS.getStorageClassSpecLoc());
806 else
807 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
808 DS.getStorageClassSpecLoc());
809 }
810 if (auto TSCS = DS.getThreadStorageClassSpec())
811 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
812 DS.getThreadStorageClassSpecLoc());
813
814 if (DS.isInlineSpecified())
815 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
816
817 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
818 ConstexprSpec != ConstexprSpecKind::Unspecified) {
819 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
820 !getLangOpts().CPlusPlus26)
821 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
822 DS.getConstexprSpecLoc());
823 }
824
825 // We can't recover from it being declared as a typedef.
826 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
827 return nullptr;
828
829 // C++2a [dcl.struct.bind]p1:
830 // A cv that includes volatile is deprecated
831 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
832 getLangOpts().CPlusPlus20)
833 Diag(Loc: DS.getVolatileSpecLoc(),
834 DiagID: diag::warn_deprecated_volatile_structured_binding);
835
836 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
837 QualType R = TInfo->getType();
838
839 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
840 UPPC: UPPC_DeclarationType))
841 D.setInvalidType();
842
843 // The syntax only allows a single ref-qualifier prior to the decomposition
844 // declarator. No other declarator chunks are permitted. Also check the type
845 // specifier here.
846 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
847 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
848 (D.getNumTypeObjects() == 1 &&
849 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
850 Diag(Loc: Decomp.getLSquareLoc(),
851 DiagID: (D.hasGroupingParens() ||
852 (D.getNumTypeObjects() &&
853 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
854 ? diag::err_decomp_decl_parens
855 : diag::err_decomp_decl_type)
856 << R;
857
858 // In most cases, there's no actual problem with an explicitly-specified
859 // type, but a function type won't work here, and ActOnVariableDeclarator
860 // shouldn't be called for such a type.
861 if (R->isFunctionType())
862 D.setInvalidType();
863 }
864
865 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
866 if (DS.isConstrainedAuto()) {
867 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
868 assert(TemplRep->Kind == TNK_Concept_template &&
869 "No other template kind should be possible for a constrained auto");
870
871 SourceRange TemplRange{TemplRep->TemplateNameLoc,
872 TemplRep->RAngleLoc.isValid()
873 ? TemplRep->RAngleLoc
874 : TemplRep->TemplateNameLoc};
875 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
876 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
877 }
878
879 // Build the BindingDecls.
880 SmallVector<BindingDecl*, 8> Bindings;
881
882 // Build the BindingDecls.
883 for (auto &B : D.getDecompositionDeclarator().bindings()) {
884 // Check for name conflicts.
885 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
886 IdentifierInfo *VarName = B.Name;
887 assert(VarName && "Cannot have an unnamed binding declaration");
888
889 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
890 RedeclarationKind::ForVisibleRedeclaration);
891 LookupName(R&: Previous, S,
892 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
893
894 // It's not permitted to shadow a template parameter name.
895 if (Previous.isSingleResult() &&
896 Previous.getFoundDecl()->isTemplateParameter()) {
897 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
898 Previous.clear();
899 }
900
901 QualType QT;
902 if (B.EllipsisLoc.isValid()) {
903 if (!cast<Decl>(Val: DC)->isTemplated())
904 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
905 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
906 /*ExpectsPackInType=*/ExpectPackInType: false);
907 }
908
909 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
910
911 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
912
913 // Find the shadowed declaration before filtering for scope.
914 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
915 ? getShadowedDeclaration(D: BD, R: Previous)
916 : nullptr;
917
918 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
919 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
920 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
921 /*AllowInlineNamespace*/false);
922
923 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
924 DC->isFunctionOrMethod() && VarName->isPlaceholder();
925 if (!Previous.empty()) {
926 if (IsPlaceholder) {
927 bool sameDC = (Previous.end() - 1)
928 ->getDeclContext()
929 ->getRedeclContext()
930 ->Equals(DC: DC->getRedeclContext());
931 if (sameDC &&
932 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
933 Previous.clear();
934 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
935 }
936 } else {
937 auto *Old = Previous.getRepresentativeDecl();
938 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
939 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
940 }
941 } else if (ShadowedDecl && !D.isRedeclaration()) {
942 CheckShadow(D: BD, ShadowedDecl, R: Previous);
943 }
944 PushOnScopeChains(D: BD, S, AddToContext: true);
945 Bindings.push_back(Elt: BD);
946 ParsingInitForAutoVars.insert(Ptr: BD);
947 }
948
949 // There are no prior lookup results for the variable itself, because it
950 // is unnamed.
951 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
952 Decomp.getLSquareLoc());
953 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
954 RedeclarationKind::ForVisibleRedeclaration);
955
956 // Build the variable that holds the non-decomposed object.
957 bool AddToScope = true;
958 NamedDecl *New =
959 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
960 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
961 if (AddToScope) {
962 S->AddDecl(D: New);
963 CurContext->addHiddenDecl(D: New);
964 }
965
966 if (OpenMP().isInOpenMPDeclareTargetContext())
967 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
968
969 return New;
970}
971
972// Check the arity of the structured bindings.
973// Create the resolved pack expr if needed.
974static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
975 QualType DecompType,
976 ArrayRef<BindingDecl *> Bindings,
977 unsigned MemberCount) {
978 auto BindingWithPackItr = llvm::find_if(
979 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
980 bool HasPack = BindingWithPackItr != Bindings.end();
981 bool IsValid;
982 if (!HasPack) {
983 IsValid = Bindings.size() == MemberCount;
984 } else {
985 // There may not be more members than non-pack bindings.
986 IsValid = MemberCount >= Bindings.size() - 1;
987 }
988
989 if (IsValid && HasPack) {
990 // Create the pack expr and assign it to the binding.
991 unsigned PackSize = MemberCount - Bindings.size() + 1;
992
993 BindingDecl *BPack = *BindingWithPackItr;
994 BPack->setDecomposedDecl(DD);
995 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
996 // Create the nested BindingDecls.
997 for (unsigned I = 0; I < PackSize; ++I) {
998 BindingDecl *NestedBD = BindingDecl::Create(
999 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
1000 Id: BPack->getIdentifier(), T: QualType());
1001 NestedBD->setDecomposedDecl(DD);
1002 NestedBDs[I] = NestedBD;
1003 }
1004
1005 QualType PackType = S.Context.getPackExpansionType(
1006 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
1007 auto *PackExpr = FunctionParmPackExpr::Create(
1008 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
1009 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
1010 }
1011
1012 if (IsValid)
1013 return false;
1014
1015 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
1016 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1017 << (MemberCount < Bindings.size());
1018 return true;
1019}
1020
1021static bool checkSimpleDecomposition(
1022 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1023 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1024 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1025 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1026 auto *DD = cast<DecompositionDecl>(Val: Src);
1027
1028 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1029 return true;
1030
1031 unsigned I = 0;
1032 for (auto *B : DD->flat_bindings()) {
1033 SourceLocation Loc = B->getLocation();
1034 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1035 if (E.isInvalid())
1036 return true;
1037 E = GetInit(Loc, E.get(), I++);
1038 if (E.isInvalid())
1039 return true;
1040 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1041 }
1042
1043 return false;
1044}
1045
1046static bool checkArrayLikeDecomposition(Sema &S,
1047 ArrayRef<BindingDecl *> Bindings,
1048 ValueDecl *Src, QualType DecompType,
1049 const llvm::APSInt &NumElems,
1050 QualType ElemType) {
1051 return checkSimpleDecomposition(
1052 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1053 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1054 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1055 if (E.isInvalid())
1056 return ExprError();
1057 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1058 });
1059}
1060
1061static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1062 ValueDecl *Src, QualType DecompType,
1063 const ConstantArrayType *CAT) {
1064 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1065 NumElems: llvm::APSInt(CAT->getSize()),
1066 ElemType: CAT->getElementType());
1067}
1068
1069static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1070 ValueDecl *Src, QualType DecompType,
1071 const VectorType *VT) {
1072 return checkArrayLikeDecomposition(
1073 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1074 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1075 Qs: DecompType.getQualifiers()));
1076}
1077
1078static bool checkComplexDecomposition(Sema &S,
1079 ArrayRef<BindingDecl *> Bindings,
1080 ValueDecl *Src, QualType DecompType,
1081 const ComplexType *CT) {
1082 return checkSimpleDecomposition(
1083 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1084 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1085 Qs: DecompType.getQualifiers()),
1086 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1087 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1088 });
1089}
1090
1091static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1092 TemplateArgumentListInfo &Args,
1093 const TemplateParameterList *Params) {
1094 SmallString<128> SS;
1095 llvm::raw_svector_ostream OS(SS);
1096 bool First = true;
1097 unsigned I = 0;
1098 for (auto &Arg : Args.arguments()) {
1099 if (!First)
1100 OS << ", ";
1101 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1102 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1103 Policy: PrintingPolicy, TPL: Params, Idx: I));
1104 First = false;
1105 I++;
1106 }
1107 return std::string(OS.str());
1108}
1109
1110static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1111 TemplateArgumentListInfo &Args, unsigned DiagID) {
1112 auto DiagnoseMissing = [&] {
1113 if (DiagID)
1114 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1115 Args, /*Params*/ nullptr);
1116 return QualType();
1117 };
1118
1119 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1120 NamespaceDecl *Std = S.getStdNamespace();
1121 if (!Std)
1122 return DiagnoseMissing();
1123
1124 // Look up the trait itself, within namespace std. We can diagnose various
1125 // problems with this lookup even if we've been asked to not diagnose a
1126 // missing specialization, because this can only fail if the user has been
1127 // declaring their own names in namespace std or we don't support the
1128 // standard library implementation in use.
1129 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1130 Sema::LookupOrdinaryName);
1131 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1132 return DiagnoseMissing();
1133 if (Result.isAmbiguous())
1134 return QualType();
1135
1136 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1137 if (!TraitTD) {
1138 Result.suppressDiagnostics();
1139 NamedDecl *Found = *Result.begin();
1140 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1141 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1142 return QualType();
1143 }
1144
1145 // Build the template-id.
1146 QualType TraitTy = S.CheckTemplateIdType(
1147 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1148 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1149 if (TraitTy.isNull())
1150 return QualType();
1151
1152 if (!S.isCompleteType(Loc, T: TraitTy)) {
1153 if (DiagID)
1154 S.RequireCompleteType(
1155 Loc, T: TraitTy, DiagID,
1156 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1157 Params: TraitTD->getTemplateParameters()));
1158 return QualType();
1159 }
1160 return TraitTy;
1161}
1162
1163static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1164 LookupResult &MemberLookup) {
1165 assert(RD && "specialization of class template is not a class?");
1166 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1167 return MemberLookup.isAmbiguous();
1168}
1169
1170static TemplateArgumentLoc
1171getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1172 uint64_t I) {
1173 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1174 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1175}
1176
1177static TemplateArgumentLoc
1178getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1179 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1180}
1181
1182namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1183
1184static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1185 unsigned &OutSize) {
1186 EnterExpressionEvaluationContext ContextRAII(
1187 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1188
1189 // Form template argument list for tuple_size<T>.
1190 TemplateArgumentListInfo Args(Loc, Loc);
1191 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1192
1193 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1194 if (TraitTy.isNull())
1195 return IsTupleLike::NotTupleLike;
1196
1197 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1198 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1199
1200 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1201 // it's not tuple-like.
1202 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1203 return IsTupleLike::NotTupleLike;
1204
1205 // If we get this far, we've committed to the tuple interpretation, but
1206 // we can still fail if there actually isn't a usable ::value.
1207
1208 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1209 LookupResult &R;
1210 TemplateArgumentListInfo &Args;
1211 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1212 : R(R), Args(Args) {}
1213 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1214 SourceLocation Loc) override {
1215 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1216 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1217 /*Params*/ nullptr);
1218 }
1219 } Diagnoser(R, Args);
1220
1221 ExprResult E =
1222 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1223 if (E.isInvalid())
1224 return IsTupleLike::Error;
1225
1226 llvm::APSInt Size;
1227 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1228 if (E.isInvalid())
1229 return IsTupleLike::Error;
1230
1231 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1232 // an UnsignedOrNone.
1233 if (Size < 0 || Size >= UINT_MAX) {
1234 llvm::SmallVector<char, 16> Str;
1235 Size.toString(Str);
1236 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1237 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1238 /*Params=*/nullptr)
1239 << StringRef(Str.data(), Str.size());
1240 return IsTupleLike::Error;
1241 }
1242
1243 OutSize = Size.getExtValue();
1244 return IsTupleLike::TupleLike;
1245}
1246
1247/// \return std::tuple_element<I, T>::type.
1248static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1249 unsigned I, QualType T) {
1250 // Form template argument list for tuple_element<I, T>.
1251 TemplateArgumentListInfo Args(Loc, Loc);
1252 Args.addArgument(
1253 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1254 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1255
1256 QualType TraitTy =
1257 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1258 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1259 if (TraitTy.isNull())
1260 return QualType();
1261
1262 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1263 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1264 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1265 return QualType();
1266
1267 auto *TD = R.getAsSingle<TypeDecl>();
1268 if (!TD) {
1269 R.suppressDiagnostics();
1270 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1271 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1272 /*Params*/ nullptr);
1273 if (!R.empty())
1274 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1275 return QualType();
1276 }
1277
1278 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1279 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1280}
1281
1282namespace {
1283struct InitializingBinding {
1284 Sema &S;
1285 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1286 Sema::CodeSynthesisContext Ctx;
1287 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1288 Ctx.PointOfInstantiation = BD->getLocation();
1289 Ctx.Entity = BD;
1290 S.pushCodeSynthesisContext(Ctx);
1291 }
1292 ~InitializingBinding() {
1293 S.popCodeSynthesisContext();
1294 }
1295};
1296}
1297
1298static bool checkTupleLikeDecomposition(Sema &S,
1299 ArrayRef<BindingDecl *> Bindings,
1300 VarDecl *Src, QualType DecompType,
1301 unsigned NumElems) {
1302 auto *DD = cast<DecompositionDecl>(Val: Src);
1303 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1304 return true;
1305
1306 if (Bindings.empty())
1307 return false;
1308
1309 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1310
1311 // [dcl.decomp]p3:
1312 // The unqualified-id get is looked up in the scope of E by class member
1313 // access lookup ...
1314 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1315 bool UseMemberGet = false;
1316 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1317 if (auto *RD = DecompType->getAsCXXRecordDecl())
1318 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1319 if (MemberGet.isAmbiguous())
1320 return true;
1321 // ... and if that finds at least one declaration that is a function
1322 // template whose first template parameter is a non-type parameter ...
1323 for (NamedDecl *D : MemberGet) {
1324 if (FunctionTemplateDecl *FTD =
1325 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1326 TemplateParameterList *TPL = FTD->getTemplateParameters();
1327 if (TPL->size() != 0 &&
1328 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1329 // ... the initializer is e.get<i>().
1330 UseMemberGet = true;
1331 break;
1332 }
1333 }
1334 }
1335 }
1336
1337 unsigned I = 0;
1338 for (auto *B : DD->flat_bindings()) {
1339 InitializingBinding InitContext(S, B);
1340 SourceLocation Loc = B->getLocation();
1341
1342 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1343 if (E.isInvalid())
1344 return true;
1345
1346 // e is an lvalue if the type of the entity is an lvalue reference and
1347 // an xvalue otherwise
1348 if (!Src->getType()->isLValueReferenceType())
1349 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1350 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1351 FPO: FPOptionsOverride());
1352
1353 TemplateArgumentListInfo Args(Loc, Loc);
1354 Args.addArgument(
1355 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1356
1357 if (UseMemberGet) {
1358 // if [lookup of member get] finds at least one declaration, the
1359 // initializer is e.get<i-1>().
1360 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1361 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1362 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1363 if (E.isInvalid())
1364 return true;
1365
1366 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1367 } else {
1368 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1369 // in the associated namespaces.
1370 Expr *Get = UnresolvedLookupExpr::Create(
1371 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1372 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1373 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1374 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1375
1376 Expr *Arg = E.get();
1377 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1378 }
1379 if (E.isInvalid())
1380 return true;
1381 Expr *Init = E.get();
1382
1383 // Given the type T designated by std::tuple_element<i - 1, E>::type
1384 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1385 if (T.isNull())
1386 return true;
1387
1388 // C++26 [dcl.struct.bind]p7:
1389 // and the type Ui, defined as Ti if the initializer is a prvalue,
1390 // as "lvalue reference to Ti" if the initializer is an lvalue,
1391 // or as "rvalue reference to Ti" otherwise
1392 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1393 QualType U = E.get()->isPRValue()
1394 ? T
1395 : S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc,
1396 Entity: B->getDeclName());
1397 if (U.isNull())
1398 return true;
1399
1400 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1401 // entity and this type was never written in source code.
1402 auto *BindingVD =
1403 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1404 Id: B->getDeclName().getAsIdentifierInfo(), T: U,
1405 /*TInfo=*/nullptr, S: Src->getStorageClass());
1406 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1407 BindingVD->setTSCSpec(Src->getTSCSpec());
1408 BindingVD->setConstexpr(Src->isConstexpr());
1409 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1410 BindingVD->addAttr(A: CIAttr->clone(C&: S.Context));
1411 BindingVD->setImplicit();
1412 if (Src->isInlineSpecified())
1413 BindingVD->setInlineSpecified();
1414 BindingVD->getLexicalDeclContext()->addHiddenDecl(D: BindingVD);
1415
1416 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: BindingVD);
1417 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1418 InitializationSequence Seq(S, Entity, Kind, Init);
1419 E = Seq.Perform(S, Entity, Kind, Args: Init);
1420 if (E.isInvalid())
1421 return true;
1422 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1423 if (E.isInvalid())
1424 return true;
1425 BindingVD->setInit(E.get());
1426 S.CheckCompleteVariableDeclaration(VD: BindingVD);
1427
1428 E = S.BuildDeclarationNameExpr(
1429 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(B->getDeclName(), Loc), D: BindingVD);
1430 if (E.isInvalid())
1431 return true;
1432
1433 B->setBinding(DeclaredType: T, Binding: E.get());
1434 I++;
1435 }
1436
1437 return false;
1438}
1439
1440/// Find the base class to decompose in a built-in decomposition of a class type.
1441/// This base class search is, unfortunately, not quite like any other that we
1442/// perform anywhere else in C++.
1443static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1444 const CXXRecordDecl *RD,
1445 CXXCastPath &BasePath) {
1446 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1447 CXXBasePath &Path) {
1448 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1449 };
1450
1451 const CXXRecordDecl *ClassWithFields = nullptr;
1452 AccessSpecifier AS = AS_public;
1453 if (RD->hasDirectFields())
1454 // [dcl.decomp]p4:
1455 // Otherwise, all of E's non-static data members shall be public direct
1456 // members of E ...
1457 ClassWithFields = RD;
1458 else {
1459 // ... or of ...
1460 CXXBasePaths Paths;
1461 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1462 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1463 // If no classes have fields, just decompose RD itself. (This will work
1464 // if and only if zero bindings were provided.)
1465 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1466 }
1467
1468 CXXBasePath *BestPath = nullptr;
1469 for (auto &P : Paths) {
1470 if (!BestPath)
1471 BestPath = &P;
1472 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1473 T2: BestPath->back().Base->getType())) {
1474 // ... the same ...
1475 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1476 << false << RD << BestPath->back().Base->getType()
1477 << P.back().Base->getType();
1478 return DeclAccessPair();
1479 } else if (P.Access < BestPath->Access) {
1480 BestPath = &P;
1481 }
1482 }
1483
1484 // ... unambiguous ...
1485 QualType BaseType = BestPath->back().Base->getType();
1486 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1487 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1488 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1489 return DeclAccessPair();
1490 }
1491
1492 // ... [accessible, implied by other rules] base class of E.
1493 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1494 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1495 AS = BestPath->Access;
1496
1497 ClassWithFields = BaseType->getAsCXXRecordDecl();
1498 S.BuildBasePathArray(Paths, BasePath);
1499 }
1500
1501 // The above search did not check whether the selected class itself has base
1502 // classes with fields, so check that now.
1503 CXXBasePaths Paths;
1504 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1505 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1506 << (ClassWithFields == RD) << RD << ClassWithFields
1507 << Paths.front().back().Base->getType();
1508 return DeclAccessPair();
1509 }
1510
1511 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1512}
1513
1514static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1515 const CXXRecordDecl *OrigRD,
1516 QualType DecompType,
1517 DeclAccessPair BasePair) {
1518 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1519 if (!RD)
1520 return true;
1521
1522 for (auto *FD : RD->fields()) {
1523 if (FD->isUnnamedBitField())
1524 continue;
1525
1526 // All the non-static data members are required to be nameable, so they
1527 // must all have names.
1528 if (!FD->getDeclName()) {
1529 if (RD->isLambda()) {
1530 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1531 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1532 return true;
1533 }
1534
1535 if (FD->isAnonymousStructOrUnion()) {
1536 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1537 << DecompType << FD->getType()->isUnionType();
1538 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1539 return true;
1540 }
1541
1542 // FIXME: Are there any other ways we could have an anonymous member?
1543 }
1544 // The field must be accessible in the context of the structured binding.
1545 // We already checked that the base class is accessible.
1546 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1547 // const_cast here.
1548 S.CheckStructuredBindingMemberAccess(
1549 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1550 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1551 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1552 }
1553 return false;
1554}
1555
1556static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1557 ValueDecl *Src, QualType DecompType,
1558 const CXXRecordDecl *OrigRD) {
1559 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1560 DiagID: diag::err_incomplete_type))
1561 return true;
1562
1563 CXXCastPath BasePath;
1564 DeclAccessPair BasePair =
1565 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1566 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1567 if (!RD)
1568 return true;
1569 QualType BaseType = S.Context.getQualifiedType(
1570 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1571
1572 auto *DD = cast<DecompositionDecl>(Val: Src);
1573 unsigned NumFields = llvm::count_if(
1574 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1575 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1576 return true;
1577
1578 // all of E's non-static data members shall be [...] well-formed
1579 // when named as e.name in the context of the structured binding,
1580 // E shall not have an anonymous union member, ...
1581 auto FlatBindings = DD->flat_bindings();
1582 assert(llvm::range_size(FlatBindings) == NumFields);
1583 auto FlatBindingsItr = FlatBindings.begin();
1584
1585 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1586 BasePair))
1587 return true;
1588
1589 for (auto *FD : RD->fields()) {
1590 if (FD->isUnnamedBitField())
1591 continue;
1592
1593 // We have a real field to bind.
1594 assert(FlatBindingsItr != FlatBindings.end());
1595 BindingDecl *B = *(FlatBindingsItr++);
1596 SourceLocation Loc = B->getLocation();
1597
1598 // Initialize the binding to Src.FD.
1599 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1600 if (E.isInvalid())
1601 return true;
1602 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1603 VK: VK_LValue, BasePath: &BasePath);
1604 if (E.isInvalid())
1605 return true;
1606 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1607 SS: CXXScopeSpec(), Field: FD,
1608 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1609 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1610 if (E.isInvalid())
1611 return true;
1612
1613 // If the type of the member is T, the referenced type is cv T, where cv is
1614 // the cv-qualification of the decomposition expression.
1615 //
1616 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1617 // 'const' to the type of the field.
1618 Qualifiers Q = DecompType.getQualifiers();
1619 if (FD->isMutable())
1620 Q.removeConst();
1621 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1622 }
1623
1624 return false;
1625}
1626
1627void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1628 QualType DecompType = DD->getType();
1629
1630 // If the type of the decomposition is dependent, then so is the type of
1631 // each binding.
1632 if (DecompType->isDependentType()) {
1633 // Note that all of the types are still Null or PackExpansionType.
1634 for (auto *B : DD->bindings()) {
1635 // Do not overwrite any pack type.
1636 if (B->getType().isNull())
1637 B->setType(Context.DependentTy);
1638 }
1639 return;
1640 }
1641
1642 DecompType = DecompType.getNonReferenceType();
1643 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1644
1645 // C++1z [dcl.decomp]/2:
1646 // If E is an array type [...]
1647 // As an extension, we also support decomposition of built-in complex and
1648 // vector types.
1649 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1650 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1651 DD->setInvalidDecl();
1652 return;
1653 }
1654 if (auto *VT = DecompType->getAs<VectorType>()) {
1655 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1656 DD->setInvalidDecl();
1657 return;
1658 }
1659 if (auto *CT = DecompType->getAs<ComplexType>()) {
1660 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1661 DD->setInvalidDecl();
1662 return;
1663 }
1664
1665 // C++1z [dcl.decomp]/3:
1666 // if the expression std::tuple_size<E>::value is a well-formed integral
1667 // constant expression, [...]
1668 unsigned TupleSize;
1669 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1670 case IsTupleLike::Error:
1671 DD->setInvalidDecl();
1672 return;
1673
1674 case IsTupleLike::TupleLike:
1675 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1676 DD->setInvalidDecl();
1677 return;
1678
1679 case IsTupleLike::NotTupleLike:
1680 break;
1681 }
1682
1683 // C++1z [dcl.dcl]/8:
1684 // [E shall be of array or non-union class type]
1685 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1686 if (!RD || RD->isUnion()) {
1687 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1688 << DD << !RD << DecompType;
1689 DD->setInvalidDecl();
1690 return;
1691 }
1692
1693 // C++1z [dcl.decomp]/4:
1694 // all of E's non-static data members shall be [...] direct members of
1695 // E or of the same unambiguous public base class of E, ...
1696 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1697 DD->setInvalidDecl();
1698}
1699
1700UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1701 SourceLocation Loc) {
1702 const ASTContext &Ctx = getASTContext();
1703 assert(!T->isDependentType());
1704
1705 Qualifiers Quals;
1706 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1707 Quals.removeCVRQualifiers();
1708 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1709
1710 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1711 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1712 if (auto *VT = T->getAs<VectorType>())
1713 return VT->getNumElements();
1714 if (T->getAs<ComplexType>())
1715 return 2u;
1716
1717 unsigned TupleSize;
1718 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1719 case IsTupleLike::Error:
1720 return std::nullopt;
1721 case IsTupleLike::TupleLike:
1722 return TupleSize;
1723 case IsTupleLike::NotTupleLike:
1724 break;
1725 }
1726
1727 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1728 if (!OrigRD || OrigRD->isUnion())
1729 return std::nullopt;
1730
1731 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1732 return std::nullopt;
1733
1734 CXXCastPath BasePath;
1735 DeclAccessPair BasePair =
1736 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1737 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1738 if (!RD)
1739 return std::nullopt;
1740
1741 unsigned NumFields = llvm::count_if(
1742 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1743
1744 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1745 return std::nullopt;
1746
1747 return NumFields;
1748}
1749
1750void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1751 // Shortcut if exceptions are disabled.
1752 if (!getLangOpts().CXXExceptions)
1753 return;
1754
1755 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1756 "Should only be called if types are otherwise the same.");
1757
1758 QualType NewType = New->getType();
1759 QualType OldType = Old->getType();
1760
1761 // We're only interested in pointers and references to functions, as well
1762 // as pointers to member functions.
1763 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1764 NewType = R->getPointeeType();
1765 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1766 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1767 NewType = P->getPointeeType();
1768 OldType = OldType->castAs<PointerType>()->getPointeeType();
1769 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1770 NewType = M->getPointeeType();
1771 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1772 }
1773
1774 if (!NewType->isFunctionProtoType())
1775 return;
1776
1777 // There's lots of special cases for functions. For function pointers, system
1778 // libraries are hopefully not as broken so that we don't need these
1779 // workarounds.
1780 if (CheckEquivalentExceptionSpec(
1781 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1782 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1783 New->setInvalidDecl();
1784 }
1785}
1786
1787/// CheckCXXDefaultArguments - Verify that the default arguments for a
1788/// function declaration are well-formed according to C++
1789/// [dcl.fct.default].
1790void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1791 // This checking doesn't make sense for explicit specializations; their
1792 // default arguments are determined by the declaration we're specializing,
1793 // not by FD.
1794 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1795 return;
1796 if (auto *FTD = FD->getDescribedFunctionTemplate())
1797 if (FTD->isMemberSpecialization())
1798 return;
1799
1800 unsigned NumParams = FD->getNumParams();
1801 unsigned ParamIdx = 0;
1802
1803 // Find first parameter with a default argument
1804 for (; ParamIdx < NumParams; ++ParamIdx) {
1805 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1806 if (Param->hasDefaultArg())
1807 break;
1808 }
1809
1810 // C++20 [dcl.fct.default]p4:
1811 // In a given function declaration, each parameter subsequent to a parameter
1812 // with a default argument shall have a default argument supplied in this or
1813 // a previous declaration, unless the parameter was expanded from a
1814 // parameter pack, or shall be a function parameter pack.
1815 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1816 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1817 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1818 (CurrentInstantiationScope &&
1819 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1820 continue;
1821 if (Param->isInvalidDecl())
1822 /* We already complained about this parameter. */;
1823 else if (Param->getIdentifier())
1824 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1825 << Param->getIdentifier();
1826 else
1827 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1828 }
1829}
1830
1831/// Check that the given type is a literal type. Issue a diagnostic if not,
1832/// if Kind is Diagnose.
1833/// \return \c true if a problem has been found (and optionally diagnosed).
1834template <typename... Ts>
1835static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1836 SourceLocation Loc, QualType T, unsigned DiagID,
1837 Ts &&...DiagArgs) {
1838 if (T->isDependentType())
1839 return false;
1840
1841 switch (Kind) {
1842 case Sema::CheckConstexprKind::Diagnose:
1843 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1844 std::forward<Ts>(DiagArgs)...);
1845
1846 case Sema::CheckConstexprKind::CheckValid:
1847 return !T->isLiteralType(Ctx: SemaRef.Context);
1848 }
1849
1850 llvm_unreachable("unknown CheckConstexprKind");
1851}
1852
1853/// Determine whether a destructor cannot be constexpr due to
1854static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1855 const CXXDestructorDecl *DD,
1856 Sema::CheckConstexprKind Kind) {
1857 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1858 "this check is obsolete for C++23");
1859 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1860 const CXXRecordDecl *RD =
1861 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1862 if (!RD || RD->hasConstexprDestructor())
1863 return true;
1864
1865 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1866 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1867 << static_cast<int>(DD->getConstexprKind()) << !FD
1868 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1869 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1870 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1871 }
1872 return false;
1873 };
1874
1875 const CXXRecordDecl *RD = DD->getParent();
1876 for (const CXXBaseSpecifier &B : RD->bases())
1877 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1878 return false;
1879 for (const FieldDecl *FD : RD->fields())
1880 if (!Check(FD->getLocation(), FD->getType(), FD))
1881 return false;
1882 return true;
1883}
1884
1885/// Check whether a function's parameter types are all literal types. If so,
1886/// return true. If not, produce a suitable diagnostic and return false.
1887static bool CheckConstexprParameterTypes(Sema &SemaRef,
1888 const FunctionDecl *FD,
1889 Sema::CheckConstexprKind Kind) {
1890 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1891 "this check is obsolete for C++23");
1892 unsigned ArgIndex = 0;
1893 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1894 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1895 e = FT->param_type_end();
1896 i != e; ++i, ++ArgIndex) {
1897 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1898 assert(PD && "null in a parameter list");
1899 SourceLocation ParamLoc = PD->getLocation();
1900 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1901 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1902 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1903 DiagArgs: FD->isConsteval()))
1904 return false;
1905 }
1906 return true;
1907}
1908
1909/// Check whether a function's return type is a literal type. If so, return
1910/// true. If not, produce a suitable diagnostic and return false.
1911static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1912 Sema::CheckConstexprKind Kind) {
1913 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1914 "this check is obsolete for C++23");
1915 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1916 DiagID: diag::err_constexpr_non_literal_return,
1917 DiagArgs: FD->isConsteval()))
1918 return false;
1919 return true;
1920}
1921
1922/// Get diagnostic %select index for tag kind for
1923/// record diagnostic message.
1924/// WARNING: Indexes apply to particular diagnostics only!
1925///
1926/// \returns diagnostic %select index.
1927static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1928 switch (Tag) {
1929 case TagTypeKind::Struct:
1930 return 0;
1931 case TagTypeKind::Interface:
1932 return 1;
1933 case TagTypeKind::Class:
1934 return 2;
1935 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1936 }
1937}
1938
1939static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1940 Stmt *Body,
1941 Sema::CheckConstexprKind Kind);
1942static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1943
1944bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1945 CheckConstexprKind Kind) {
1946 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1947 if (MD && MD->isInstance()) {
1948 // C++11 [dcl.constexpr]p4:
1949 // The definition of a constexpr constructor shall satisfy the following
1950 // constraints:
1951 // - the class shall not have any virtual base classes;
1952 //
1953 // FIXME: This only applies to constructors and destructors, not arbitrary
1954 // member functions.
1955 const CXXRecordDecl *RD = MD->getParent();
1956 if (RD->getNumVBases()) {
1957 if (Kind == CheckConstexprKind::CheckValid)
1958 return false;
1959
1960 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1961 << isa<CXXConstructorDecl>(Val: NewFD)
1962 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1963 for (const auto &I : RD->vbases())
1964 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1965 << I.getSourceRange();
1966 return false;
1967 }
1968 }
1969
1970 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1971 // C++11 [dcl.constexpr]p3:
1972 // The definition of a constexpr function shall satisfy the following
1973 // constraints:
1974 // - it shall not be virtual; (removed in C++20)
1975 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
1976 if (Method && Method->isVirtual()) {
1977 if (getLangOpts().CPlusPlus20) {
1978 if (Kind == CheckConstexprKind::Diagnose)
1979 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
1980 } else {
1981 if (Kind == CheckConstexprKind::CheckValid)
1982 return false;
1983
1984 Method = Method->getCanonicalDecl();
1985 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
1986
1987 // If it's not obvious why this function is virtual, find an overridden
1988 // function which uses the 'virtual' keyword.
1989 const CXXMethodDecl *WrittenVirtual = Method;
1990 while (!WrittenVirtual->isVirtualAsWritten())
1991 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
1992 if (WrittenVirtual != Method)
1993 Diag(Loc: WrittenVirtual->getLocation(),
1994 DiagID: diag::note_overridden_virtual_function);
1995 return false;
1996 }
1997 }
1998
1999 // - its return type shall be a literal type; (removed in C++23)
2000 if (!getLangOpts().CPlusPlus23 &&
2001 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
2002 return false;
2003 }
2004
2005 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
2006 // A destructor can be constexpr only if the defaulted destructor could be;
2007 // we don't need to check the members and bases if we already know they all
2008 // have constexpr destructors. (removed in C++23)
2009 if (!getLangOpts().CPlusPlus23 &&
2010 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2011 if (Kind == CheckConstexprKind::CheckValid)
2012 return false;
2013 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
2014 return false;
2015 }
2016 }
2017
2018 // - each of its parameter types shall be a literal type; (removed in C++23)
2019 if (!getLangOpts().CPlusPlus23 &&
2020 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
2021 return false;
2022
2023 Stmt *Body = NewFD->getBody();
2024 assert(Body &&
2025 "CheckConstexprFunctionDefinition called on function with no body");
2026 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2027}
2028
2029/// Check the given declaration statement is legal within a constexpr function
2030/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2031///
2032/// \return true if the body is OK (maybe only as an extension), false if we
2033/// have diagnosed a problem.
2034static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2035 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2036 Sema::CheckConstexprKind Kind) {
2037 // C++11 [dcl.constexpr]p3 and p4:
2038 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2039 // contain only
2040 for (const auto *DclIt : DS->decls()) {
2041 switch (DclIt->getKind()) {
2042 case Decl::StaticAssert:
2043 case Decl::Using:
2044 case Decl::UsingShadow:
2045 case Decl::UsingDirective:
2046 case Decl::UnresolvedUsingTypename:
2047 case Decl::UnresolvedUsingValue:
2048 case Decl::UsingEnum:
2049 // - static_assert-declarations
2050 // - using-declarations,
2051 // - using-directives,
2052 // - using-enum-declaration
2053 continue;
2054
2055 case Decl::Typedef:
2056 case Decl::TypeAlias: {
2057 // - typedef declarations and alias-declarations that do not define
2058 // classes or enumerations,
2059 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2060 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2061 // Don't allow variably-modified types in constexpr functions.
2062 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2063 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2064 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2065 << TL.getSourceRange() << TL.getType()
2066 << isa<CXXConstructorDecl>(Val: Dcl);
2067 }
2068 return false;
2069 }
2070 continue;
2071 }
2072
2073 case Decl::Enum:
2074 case Decl::CXXRecord:
2075 // C++1y allows types to be defined, not just declared.
2076 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2077 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2078 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2079 CompatDiagId: diag_compat::constexpr_type_definition)
2080 << isa<CXXConstructorDecl>(Val: Dcl);
2081 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2082 return false;
2083 }
2084 }
2085 continue;
2086
2087 case Decl::EnumConstant:
2088 case Decl::IndirectField:
2089 case Decl::ParmVar:
2090 // These can only appear with other declarations which are banned in
2091 // C++11 and permitted in C++1y, so ignore them.
2092 continue;
2093
2094 case Decl::Var:
2095 case Decl::Decomposition: {
2096 // C++1y [dcl.constexpr]p3 allows anything except:
2097 // a definition of a variable of non-literal type or of static or
2098 // thread storage duration or [before C++2a] for which no
2099 // initialization is performed.
2100 const auto *VD = cast<VarDecl>(Val: DclIt);
2101 if (VD->isThisDeclarationADefinition()) {
2102 if (VD->isStaticLocal()) {
2103 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2104 SemaRef.DiagCompat(Loc: VD->getLocation(),
2105 CompatDiagId: diag_compat::constexpr_static_var)
2106 << isa<CXXConstructorDecl>(Val: Dcl)
2107 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2108 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2109 return false;
2110 }
2111 }
2112 if (SemaRef.LangOpts.CPlusPlus23) {
2113 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2114 DiagID: diag::warn_cxx20_compat_constexpr_var,
2115 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2116 } else if (CheckLiteralType(
2117 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2118 DiagID: diag::err_constexpr_local_var_non_literal_type,
2119 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2120 return false;
2121 }
2122 if (!VD->getType()->isDependentType() &&
2123 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2124 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2125 SemaRef.DiagCompat(Loc: VD->getLocation(),
2126 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2127 << isa<CXXConstructorDecl>(Val: Dcl);
2128 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2129 return false;
2130 }
2131 continue;
2132 }
2133 }
2134 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2135 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2136 << isa<CXXConstructorDecl>(Val: Dcl);
2137 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2138 return false;
2139 }
2140 continue;
2141 }
2142
2143 case Decl::NamespaceAlias:
2144 case Decl::Function:
2145 // These are disallowed in C++11 and permitted in C++1y. Allow them
2146 // everywhere as an extension.
2147 if (!Cxx1yLoc.isValid())
2148 Cxx1yLoc = DS->getBeginLoc();
2149 continue;
2150
2151 default:
2152 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2153 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2154 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2155 }
2156 return false;
2157 }
2158 }
2159
2160 return true;
2161}
2162
2163/// Check that the given field is initialized within a constexpr constructor.
2164///
2165/// \param Dcl The constexpr constructor being checked.
2166/// \param Field The field being checked. This may be a member of an anonymous
2167/// struct or union nested within the class being checked.
2168/// \param Inits All declarations, including anonymous struct/union members and
2169/// indirect members, for which any initialization was provided.
2170/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2171/// multiple notes for different members to the same error.
2172/// \param Kind Whether we're diagnosing a constructor as written or determining
2173/// whether the formal requirements are satisfied.
2174/// \return \c false if we're checking for validity and the constructor does
2175/// not satisfy the requirements on a constexpr constructor.
2176static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2177 const FunctionDecl *Dcl,
2178 FieldDecl *Field,
2179 llvm::SmallPtrSet<Decl *, 16> &Inits,
2180 bool &Diagnosed,
2181 Sema::CheckConstexprKind Kind) {
2182 // In C++20 onwards, there's nothing to check for validity.
2183 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2184 SemaRef.getLangOpts().CPlusPlus20)
2185 return true;
2186
2187 if (Field->isInvalidDecl())
2188 return true;
2189
2190 if (Field->isUnnamedBitField())
2191 return true;
2192
2193 // Anonymous unions with no variant members and empty anonymous structs do not
2194 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2195 // indirect fields don't need initializing.
2196 if (Field->isAnonymousStructOrUnion() &&
2197 (Field->getType()->isUnionType()
2198 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2199 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2200 return true;
2201
2202 if (!Inits.count(Ptr: Field)) {
2203 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2204 if (!Diagnosed) {
2205 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2206 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2207 Diagnosed = true;
2208 }
2209 SemaRef.Diag(Loc: Field->getLocation(),
2210 DiagID: diag::note_constexpr_ctor_missing_init);
2211 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2212 return false;
2213 }
2214 } else if (Field->isAnonymousStructOrUnion()) {
2215 const auto *RD = Field->getType()->castAsRecordDecl();
2216 for (auto *I : RD->fields())
2217 // If an anonymous union contains an anonymous struct of which any member
2218 // is initialized, all members must be initialized.
2219 if (!RD->isUnion() || Inits.count(Ptr: I))
2220 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2221 Kind))
2222 return false;
2223 }
2224 return true;
2225}
2226
2227/// Check the provided statement is allowed in a constexpr function
2228/// definition.
2229static bool
2230CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2231 SmallVectorImpl<SourceLocation> &ReturnStmts,
2232 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2233 SourceLocation &Cxx2bLoc,
2234 Sema::CheckConstexprKind Kind) {
2235 // - its function-body shall be [...] a compound-statement that contains only
2236 switch (S->getStmtClass()) {
2237 case Stmt::NullStmtClass:
2238 // - null statements,
2239 return true;
2240
2241 case Stmt::DeclStmtClass:
2242 // - static_assert-declarations
2243 // - using-declarations,
2244 // - using-directives,
2245 // - typedef declarations and alias-declarations that do not define
2246 // classes or enumerations,
2247 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS: cast<DeclStmt>(Val: S), Cxx1yLoc, Kind))
2248 return false;
2249 return true;
2250
2251 case Stmt::ReturnStmtClass:
2252 // - and exactly one return statement;
2253 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2254 // C++1y allows return statements in constexpr constructors.
2255 if (!Cxx1yLoc.isValid())
2256 Cxx1yLoc = S->getBeginLoc();
2257 return true;
2258 }
2259
2260 ReturnStmts.push_back(Elt: S->getBeginLoc());
2261 return true;
2262
2263 case Stmt::AttributedStmtClass:
2264 // Attributes on a statement don't affect its formal kind and hence don't
2265 // affect its validity in a constexpr function.
2266 return CheckConstexprFunctionStmt(
2267 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2268 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2269
2270 case Stmt::CompoundStmtClass: {
2271 // C++1y allows compound-statements.
2272 if (!Cxx1yLoc.isValid())
2273 Cxx1yLoc = S->getBeginLoc();
2274
2275 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2276 for (auto *BodyIt : CompStmt->body()) {
2277 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2278 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2279 return false;
2280 }
2281 return true;
2282 }
2283
2284 case Stmt::IfStmtClass: {
2285 // C++1y allows if-statements.
2286 if (!Cxx1yLoc.isValid())
2287 Cxx1yLoc = S->getBeginLoc();
2288
2289 IfStmt *If = cast<IfStmt>(Val: S);
2290 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2291 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2292 return false;
2293 if (If->getElse() &&
2294 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2295 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2296 return false;
2297 return true;
2298 }
2299
2300 case Stmt::WhileStmtClass:
2301 case Stmt::DoStmtClass:
2302 case Stmt::ForStmtClass:
2303 case Stmt::CXXForRangeStmtClass:
2304 case Stmt::ContinueStmtClass:
2305 // C++1y allows all of these. We don't allow them as extensions in C++11,
2306 // because they don't make sense without variable mutation.
2307 if (!SemaRef.getLangOpts().CPlusPlus14)
2308 break;
2309 if (!Cxx1yLoc.isValid())
2310 Cxx1yLoc = S->getBeginLoc();
2311 for (Stmt *SubStmt : S->children()) {
2312 if (SubStmt &&
2313 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2314 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2315 return false;
2316 }
2317 return true;
2318
2319 case Stmt::SwitchStmtClass:
2320 case Stmt::CaseStmtClass:
2321 case Stmt::DefaultStmtClass:
2322 case Stmt::BreakStmtClass:
2323 // C++1y allows switch-statements, and since they don't need variable
2324 // mutation, we can reasonably allow them in C++11 as an extension.
2325 if (!Cxx1yLoc.isValid())
2326 Cxx1yLoc = S->getBeginLoc();
2327 for (Stmt *SubStmt : S->children()) {
2328 if (SubStmt &&
2329 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2330 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2331 return false;
2332 }
2333 return true;
2334
2335 case Stmt::LabelStmtClass:
2336 case Stmt::GotoStmtClass:
2337 if (Cxx2bLoc.isInvalid())
2338 Cxx2bLoc = S->getBeginLoc();
2339 for (Stmt *SubStmt : S->children()) {
2340 if (SubStmt &&
2341 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2342 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2343 return false;
2344 }
2345 return true;
2346
2347 case Stmt::GCCAsmStmtClass:
2348 case Stmt::MSAsmStmtClass:
2349 // C++2a allows inline assembly statements.
2350 case Stmt::CXXTryStmtClass:
2351 if (Cxx2aLoc.isInvalid())
2352 Cxx2aLoc = S->getBeginLoc();
2353 for (Stmt *SubStmt : S->children()) {
2354 if (SubStmt &&
2355 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2356 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2357 return false;
2358 }
2359 return true;
2360
2361 case Stmt::CXXCatchStmtClass:
2362 // Do not bother checking the language mode (already covered by the
2363 // try block check).
2364 if (!CheckConstexprFunctionStmt(
2365 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2366 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2367 return false;
2368 return true;
2369
2370 default:
2371 if (!isa<Expr>(Val: S))
2372 break;
2373
2374 // C++1y allows expression-statements.
2375 if (!Cxx1yLoc.isValid())
2376 Cxx1yLoc = S->getBeginLoc();
2377 return true;
2378 }
2379
2380 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2381 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2382 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2383 }
2384 return false;
2385}
2386
2387/// Check the body for the given constexpr function declaration only contains
2388/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2389///
2390/// \return true if the body is OK, false if we have found or diagnosed a
2391/// problem.
2392static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2393 Stmt *Body,
2394 Sema::CheckConstexprKind Kind) {
2395 SmallVector<SourceLocation, 4> ReturnStmts;
2396
2397 if (isa<CXXTryStmt>(Val: Body)) {
2398 // C++11 [dcl.constexpr]p3:
2399 // The definition of a constexpr function shall satisfy the following
2400 // constraints: [...]
2401 // - its function-body shall be = delete, = default, or a
2402 // compound-statement
2403 //
2404 // C++11 [dcl.constexpr]p4:
2405 // In the definition of a constexpr constructor, [...]
2406 // - its function-body shall not be a function-try-block;
2407 //
2408 // This restriction is lifted in C++2a, as long as inner statements also
2409 // apply the general constexpr rules.
2410 switch (Kind) {
2411 case Sema::CheckConstexprKind::CheckValid:
2412 if (!SemaRef.getLangOpts().CPlusPlus20)
2413 return false;
2414 break;
2415
2416 case Sema::CheckConstexprKind::Diagnose:
2417 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2418 CompatDiagId: diag_compat::constexpr_function_try_block)
2419 << isa<CXXConstructorDecl>(Val: Dcl);
2420 break;
2421 }
2422 }
2423
2424 // - its function-body shall be [...] a compound-statement that contains only
2425 // [... list of cases ...]
2426 //
2427 // Note that walking the children here is enough to properly check for
2428 // CompoundStmt and CXXTryStmt body.
2429 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2430 for (Stmt *SubStmt : Body->children()) {
2431 if (SubStmt &&
2432 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2433 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2434 return false;
2435 }
2436
2437 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2438 // If this is only valid as an extension, report that we don't satisfy the
2439 // constraints of the current language.
2440 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2441 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2442 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2443 return false;
2444 } else if (Cxx2bLoc.isValid()) {
2445 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2446 << isa<CXXConstructorDecl>(Val: Dcl);
2447 } else if (Cxx2aLoc.isValid()) {
2448 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2449 << isa<CXXConstructorDecl>(Val: Dcl);
2450 } else if (Cxx1yLoc.isValid()) {
2451 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2452 << isa<CXXConstructorDecl>(Val: Dcl);
2453 }
2454
2455 if (const CXXConstructorDecl *Constructor
2456 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2457 const CXXRecordDecl *RD = Constructor->getParent();
2458 // DR1359:
2459 // - every non-variant non-static data member and base class sub-object
2460 // shall be initialized;
2461 // DR1460:
2462 // - if the class is a union having variant members, exactly one of them
2463 // shall be initialized;
2464 if (RD->isUnion()) {
2465 if (Constructor->getNumCtorInitializers() == 0 &&
2466 RD->hasVariantMembers()) {
2467 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2468 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2469 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2470 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2471 return false;
2472 }
2473 }
2474 } else if (!Constructor->isDependentContext() &&
2475 !Constructor->isDelegatingConstructor()) {
2476 assert(RD->getNumVBases() == 0 && "constexpr ctor with virtual bases");
2477
2478 // Skip detailed checking if we have enough initializers, and we would
2479 // allow at most one initializer per member.
2480 bool AnyAnonStructUnionMembers = false;
2481 unsigned Fields = 0;
2482 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2483 E = RD->field_end(); I != E; ++I, ++Fields) {
2484 if (I->isAnonymousStructOrUnion()) {
2485 AnyAnonStructUnionMembers = true;
2486 break;
2487 }
2488 }
2489 // DR1460:
2490 // - if the class is a union-like class, but is not a union, for each of
2491 // its anonymous union members having variant members, exactly one of
2492 // them shall be initialized;
2493 if (AnyAnonStructUnionMembers ||
2494 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2495 // Check initialization of non-static data members. Base classes are
2496 // always initialized so do not need to be checked. Dependent bases
2497 // might not have initializers in the member initializer list.
2498 llvm::SmallPtrSet<Decl *, 16> Inits;
2499 for (const auto *I: Constructor->inits()) {
2500 if (FieldDecl *FD = I->getMember())
2501 Inits.insert(Ptr: FD);
2502 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2503 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2504 }
2505
2506 bool Diagnosed = false;
2507 for (auto *I : RD->fields())
2508 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2509 Kind))
2510 return false;
2511 }
2512 }
2513 } else {
2514 if (ReturnStmts.empty()) {
2515 switch (Kind) {
2516 case Sema::CheckConstexprKind::Diagnose:
2517 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2518 return false;
2519 break;
2520
2521 case Sema::CheckConstexprKind::CheckValid:
2522 // The formal requirements don't include this rule in C++14, even
2523 // though the "must be able to produce a constant expression" rules
2524 // still imply it in some cases.
2525 if (!SemaRef.getLangOpts().CPlusPlus14)
2526 return false;
2527 break;
2528 }
2529 } else if (ReturnStmts.size() > 1) {
2530 switch (Kind) {
2531 case Sema::CheckConstexprKind::Diagnose:
2532 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2533 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2534 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2535 SemaRef.Diag(Loc: ReturnStmts[I],
2536 DiagID: diag::note_constexpr_body_previous_return);
2537 break;
2538
2539 case Sema::CheckConstexprKind::CheckValid:
2540 if (!SemaRef.getLangOpts().CPlusPlus14)
2541 return false;
2542 break;
2543 }
2544 }
2545 }
2546
2547 // C++11 [dcl.constexpr]p5:
2548 // if no function argument values exist such that the function invocation
2549 // substitution would produce a constant expression, the program is
2550 // ill-formed; no diagnostic required.
2551 // C++11 [dcl.constexpr]p3:
2552 // - every constructor call and implicit conversion used in initializing the
2553 // return value shall be one of those allowed in a constant expression.
2554 // C++11 [dcl.constexpr]p4:
2555 // - every constructor involved in initializing non-static data members and
2556 // base class sub-objects shall be a constexpr constructor.
2557 //
2558 // Note that this rule is distinct from the "requirements for a constexpr
2559 // function", so is not checked in CheckValid mode. Because the check for
2560 // constexpr potential is expensive, skip the check if the diagnostic is
2561 // disabled, the function is declared in a system header, or we're in C++23
2562 // or later mode (see https://wg21.link/P2448).
2563 bool SkipCheck =
2564 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2565 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2566 SemaRef.getDiagnostics().isIgnored(
2567 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2568 SmallVector<PartialDiagnosticAt, 8> Diags;
2569 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2570 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2571 SemaRef.Diag(Loc: Dcl->getLocation(),
2572 DiagID: diag::ext_constexpr_function_never_constant_expr)
2573 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2574 << Dcl->getNameInfo().getSourceRange();
2575 for (const auto &Diag : Diags)
2576 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2577 // Don't return false here: we allow this for compatibility in
2578 // system headers.
2579 }
2580
2581 return true;
2582}
2583
2584static bool CheckConstexprMissingReturn(Sema &SemaRef,
2585 const FunctionDecl *Dcl) {
2586 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2587 Dcl->getReturnType()->isDependentType();
2588 // Skip emitting a missing return error diagnostic for non-void functions
2589 // since C++23 no longer mandates constexpr functions to yield constant
2590 // expressions.
2591 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2592 return true;
2593
2594 // C++14 doesn't require constexpr functions to contain a 'return'
2595 // statement. We still do, unless the return type might be void, because
2596 // otherwise if there's no return statement, the function cannot
2597 // be used in a core constant expression.
2598 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2599 SemaRef.Diag(Loc: Dcl->getLocation(),
2600 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2601 : diag::err_constexpr_body_no_return)
2602 << Dcl->isConsteval();
2603 return OK;
2604}
2605
2606bool Sema::CheckImmediateEscalatingFunctionDefinition(
2607 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2608 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2609 return true;
2610 FD->setBodyContainsImmediateEscalatingExpressions(
2611 FSI->FoundImmediateEscalatingExpression);
2612 if (FSI->FoundImmediateEscalatingExpression) {
2613 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2614 if (it != UndefinedButUsed.end()) {
2615 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2616 << it->first;
2617 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2618 if (FD->isImmediateFunction() && !FD->isConsteval())
2619 DiagnoseImmediateEscalatingReason(FD);
2620 return false;
2621 }
2622 }
2623 return true;
2624}
2625
2626void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2627 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2628 "expected an immediate function");
2629 assert(FD->hasBody() && "expected the function to have a body");
2630 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2631 Sema &SemaRef;
2632
2633 const FunctionDecl *ImmediateFn;
2634 bool ImmediateFnIsConstructor;
2635 CXXConstructorDecl *CurrentConstructor = nullptr;
2636 CXXCtorInitializer *CurrentInit = nullptr;
2637
2638 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2639 : SemaRef(SemaRef), ImmediateFn(FD),
2640 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2641 ShouldVisitImplicitCode = true;
2642 ShouldVisitLambdaBody = false;
2643 }
2644
2645 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2646 SourceLocation Loc = E->getBeginLoc();
2647 SourceRange Range = E->getSourceRange();
2648 if (CurrentConstructor && CurrentInit) {
2649 Loc = CurrentConstructor->getLocation();
2650 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2651 : SourceRange();
2652 }
2653
2654 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2655
2656 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2657 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2658 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2659 << (InitializedField != nullptr)
2660 << (CurrentInit && !CurrentInit->isWritten())
2661 << InitializedField << Range;
2662 }
2663 bool TraverseCallExpr(CallExpr *E) override {
2664 if (const auto *DR =
2665 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2666 DR && DR->isImmediateEscalating()) {
2667 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2668 return false;
2669 }
2670
2671 for (Expr *A : E->arguments())
2672 if (!TraverseStmt(S: A))
2673 return false;
2674
2675 return true;
2676 }
2677
2678 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2679 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2680 ReferencedFn && E->isImmediateEscalating()) {
2681 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2682 return false;
2683 }
2684
2685 return true;
2686 }
2687
2688 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2689 CXXConstructorDecl *D = E->getConstructor();
2690 if (E->isImmediateEscalating()) {
2691 Diag(E, Fn: D, /*IsCall=*/true);
2692 return false;
2693 }
2694 return true;
2695 }
2696
2697 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2698 llvm::SaveAndRestore RAII(CurrentInit, Init);
2699 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2700 }
2701
2702 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2703 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2704 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2705 }
2706
2707 bool TraverseType(QualType T, bool TraverseQualifier) override {
2708 return true;
2709 }
2710 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2711
2712 } Visitor(*this, FD);
2713 Visitor.TraverseDecl(D: FD);
2714}
2715
2716CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2717 assert(getLangOpts().CPlusPlus && "No class names in C!");
2718
2719 if (SS && SS->isInvalid())
2720 return nullptr;
2721
2722 if (SS && SS->isNotEmpty()) {
2723 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2724 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2725 }
2726
2727 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2728}
2729
2730bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2731 const CXXScopeSpec *SS) {
2732 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2733 return CurDecl && &II == CurDecl->getIdentifier();
2734}
2735
2736bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2737 assert(getLangOpts().CPlusPlus && "No class names in C!");
2738
2739 if (!getLangOpts().SpellChecking)
2740 return false;
2741
2742 CXXRecordDecl *CurDecl;
2743 if (SS && SS->isSet() && !SS->isInvalid()) {
2744 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2745 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2746 } else
2747 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2748
2749 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2750 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2751 < II->getLength()) {
2752 II = CurDecl->getIdentifier();
2753 return true;
2754 }
2755
2756 return false;
2757}
2758
2759CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2760 SourceRange SpecifierRange,
2761 bool Virtual, AccessSpecifier Access,
2762 TypeSourceInfo *TInfo,
2763 SourceLocation EllipsisLoc) {
2764 QualType BaseType = TInfo->getType();
2765 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2766 if (BaseType->containsErrors()) {
2767 // Already emitted a diagnostic when parsing the error type.
2768 return nullptr;
2769 }
2770
2771 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2772 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2773 << TInfo->getTypeLoc().getSourceRange();
2774 EllipsisLoc = SourceLocation();
2775 }
2776
2777 auto *BaseDecl =
2778 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2779 // C++ [class.derived.general]p2:
2780 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2781 // that is not an incompletely defined class; any cv-qualifiers are
2782 // ignored.
2783 if (BaseDecl) {
2784 // C++ [class.union.general]p4:
2785 // [...] A union shall not be used as a base class.
2786 if (BaseDecl->isUnion()) {
2787 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2788 return nullptr;
2789 }
2790
2791 if (BaseType.hasQualifiers()) {
2792 std::string Quals =
2793 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2794 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2795 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2796 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2797 }
2798
2799 // For the MS ABI, propagate DLL attributes to base class templates.
2800 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2801 Context.getTargetInfo().getTriple().isPS()) {
2802 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2803 if (auto *BaseSpec =
2804 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2805 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2806 BaseLoc);
2807 }
2808 }
2809 }
2810
2811 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2812 Args: SpecifierRange)) {
2813 Class->setInvalidDecl();
2814 return nullptr;
2815 }
2816
2817 BaseDecl = BaseDecl->getDefinition();
2818 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2819
2820 // Microsoft docs say:
2821 // "If a base-class has a code_seg attribute, derived classes must have the
2822 // same attribute."
2823 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2824 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2825 if ((DerivedCSA || BaseCSA) &&
2826 (!BaseCSA || !DerivedCSA ||
2827 BaseCSA->getName() != DerivedCSA->getName())) {
2828 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2829 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2830 << BaseDecl;
2831 return nullptr;
2832 }
2833
2834 // A class which contains a flexible array member is not suitable for use as
2835 // a base class:
2836 // - If the layout determines that a base comes before another base,
2837 // the flexible array member would index into the subsequent base.
2838 // - If the layout determines that base comes before the derived class,
2839 // the flexible array member would index into the derived class.
2840 if (BaseDecl->hasFlexibleArrayMember()) {
2841 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2842 << BaseDecl->getDeclName();
2843 return nullptr;
2844 }
2845
2846 // C++ [class]p3:
2847 // If a class is marked final and it appears as a base-type-specifier in
2848 // base-clause, the program is ill-formed.
2849 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2850 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2851 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2852 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2853 << BaseDecl->getDeclName() << FA->getRange();
2854 return nullptr;
2855 }
2856
2857 // If the base class is invalid the derived class is as well.
2858 if (BaseDecl->isInvalidDecl())
2859 Class->setInvalidDecl();
2860 } else if (BaseType->isDependentType()) {
2861 // Make sure that we don't make an ill-formed AST where the type of the
2862 // Class is non-dependent and its attached base class specifier is an
2863 // dependent type, which violates invariants in many clang code paths (e.g.
2864 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2865 // explicitly mark the Class decl invalid. The diagnostic was already
2866 // emitted.
2867 if (!Class->isDependentContext())
2868 Class->setInvalidDecl();
2869 } else {
2870 // The base class is some non-dependent non-class type.
2871 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2872 return nullptr;
2873 }
2874
2875 // In HLSL, unspecified class access is public rather than private.
2876 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2877 Access == AS_none)
2878 Access = AS_public;
2879
2880 // Create the base specifier.
2881 return new (Context) CXXBaseSpecifier(
2882 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2883 Access, TInfo, EllipsisLoc);
2884}
2885
2886BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2887 const ParsedAttributesView &Attributes,
2888 bool Virtual, AccessSpecifier Access,
2889 ParsedType basetype, SourceLocation BaseLoc,
2890 SourceLocation EllipsisLoc) {
2891 if (!classdecl)
2892 return true;
2893
2894 AdjustDeclIfTemplate(Decl&: classdecl);
2895 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2896 if (!Class)
2897 return true;
2898
2899 // We haven't yet attached the base specifiers.
2900 Class->setIsParsingBaseSpecifiers();
2901
2902 // We do not support any C++11 attributes on base-specifiers yet.
2903 // Diagnose any attributes we see.
2904 for (const ParsedAttr &AL : Attributes) {
2905 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2906 continue;
2907 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2908 DiagnoseUnknownAttribute(AL);
2909 else
2910 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2911 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2912 }
2913
2914 TypeSourceInfo *TInfo = nullptr;
2915 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2916
2917 if (EllipsisLoc.isInvalid() &&
2918 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2919 UPPC: UPPC_BaseType))
2920 return true;
2921
2922 // C++ [class.union.general]p4:
2923 // [...] A union shall not have base classes.
2924 if (Class->isUnion()) {
2925 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2926 << SpecifierRange;
2927 return true;
2928 }
2929
2930 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2931 Virtual, Access, TInfo,
2932 EllipsisLoc))
2933 return BaseSpec;
2934
2935 Class->setInvalidDecl();
2936 return true;
2937}
2938
2939/// Use small set to collect indirect bases. As this is only used
2940/// locally, there's no need to abstract the small size parameter.
2941typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2942
2943/// Recursively add the bases of Type. Don't add Type itself.
2944static void
2945NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2946 const QualType &Type)
2947{
2948 // Even though the incoming type is a base, it might not be
2949 // a class -- it could be a template parm, for instance.
2950 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2951 // Iterate over its bases.
2952 for (const auto &BaseSpec : Decl->bases()) {
2953 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2954 .getUnqualifiedType();
2955 if (Set.insert(Ptr: Base).second)
2956 // If we've not already seen it, recurse.
2957 NoteIndirectBases(Context, Set, Type: Base);
2958 }
2959 }
2960}
2961
2962bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
2963 MutableArrayRef<CXXBaseSpecifier *> Bases) {
2964 if (Bases.empty())
2965 return false;
2966
2967 // Used to keep track of which base types we have already seen, so
2968 // that we can properly diagnose redundant direct base types. Note
2969 // that the key is always the unqualified canonical type of the base
2970 // class.
2971 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
2972
2973 // Used to track indirect bases so we can see if a direct base is
2974 // ambiguous.
2975 IndirectBaseSet IndirectBaseTypes;
2976
2977 // Copy non-redundant base specifiers into permanent storage.
2978 unsigned NumGoodBases = 0;
2979 bool Invalid = false;
2980 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
2981 QualType NewBaseType
2982 = Context.getCanonicalType(T: Bases[idx]->getType());
2983 NewBaseType = NewBaseType.getLocalUnqualifiedType();
2984
2985 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
2986 if (KnownBase) {
2987 // C++ [class.mi]p3:
2988 // A class shall not be specified as a direct base class of a
2989 // derived class more than once.
2990 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
2991 << KnownBase->getType() << Bases[idx]->getSourceRange();
2992
2993 // Delete the duplicate base class specifier; we're going to
2994 // overwrite its pointer later.
2995 Context.Deallocate(Ptr: Bases[idx]);
2996
2997 Invalid = true;
2998 } else {
2999 // Okay, add this new base class.
3000 KnownBase = Bases[idx];
3001 Bases[NumGoodBases++] = Bases[idx];
3002
3003 if (NewBaseType->isDependentType())
3004 continue;
3005 // Note this base's direct & indirect bases, if there could be ambiguity.
3006 if (Bases.size() > 1)
3007 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
3008
3009 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3010 if (Class->isInterface() &&
3011 (!RD->isInterfaceLike() ||
3012 KnownBase->getAccessSpecifier() != AS_public)) {
3013 // The Microsoft extension __interface does not permit bases that
3014 // are not themselves public interfaces.
3015 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
3016 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
3017 << RD->getSourceRange();
3018 Invalid = true;
3019 }
3020 if (RD->hasAttr<WeakAttr>())
3021 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
3022 }
3023 }
3024 }
3025
3026 // Attach the remaining base class specifiers to the derived class.
3027 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3028
3029 // Check that the only base classes that are duplicate are virtual.
3030 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3031 // Check whether this direct base is inaccessible due to ambiguity.
3032 QualType BaseType = Bases[idx]->getType();
3033
3034 // Skip all dependent types in templates being used as base specifiers.
3035 // Checks below assume that the base specifier is a CXXRecord.
3036 if (BaseType->isDependentType())
3037 continue;
3038
3039 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3040 .getUnqualifiedType();
3041
3042 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3043 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3044 /*DetectVirtual=*/true);
3045 bool found
3046 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3047 assert(found);
3048 (void)found;
3049
3050 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3051 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3052 << BaseType << getAmbiguousPathsDisplayString(Paths)
3053 << Bases[idx]->getSourceRange();
3054 else
3055 assert(Bases[idx]->isVirtual());
3056 }
3057
3058 // Delete the base class specifier, since its data has been copied
3059 // into the CXXRecordDecl.
3060 Context.Deallocate(Ptr: Bases[idx]);
3061 }
3062
3063 return Invalid;
3064}
3065
3066void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3067 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3068 if (!ClassDecl || Bases.empty())
3069 return;
3070
3071 AdjustDeclIfTemplate(Decl&: ClassDecl);
3072 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3073}
3074
3075bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3076 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3077 if (!getLangOpts().CPlusPlus)
3078 return false;
3079
3080 if (!Base || !Derived)
3081 return false;
3082
3083 // If either the base or the derived type is invalid, don't try to
3084 // check whether one is derived from the other.
3085 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3086 return false;
3087
3088 // FIXME: In a modules build, do we need the entire path to be visible for us
3089 // to be able to use the inheritance relationship?
3090 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3091 !Derived->isBeingDefined())
3092 return false;
3093
3094 return Derived->isDerivedFrom(Base, Paths);
3095}
3096
3097bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3098 CXXRecordDecl *Base) {
3099 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3100 /*DetectVirtual=*/false);
3101 return IsDerivedFrom(Loc, Derived, Base, Paths);
3102}
3103
3104bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3105 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3106 /*DetectVirtual=*/false);
3107 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3108 Base: Base->getAsCXXRecordDecl(), Paths);
3109}
3110
3111bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3112 CXXBasePaths &Paths) {
3113 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3114 Base: Base->getAsCXXRecordDecl(), Paths);
3115}
3116
3117static void BuildBasePathArray(const CXXBasePath &Path,
3118 CXXCastPath &BasePathArray) {
3119 // We first go backward and check if we have a virtual base.
3120 // FIXME: It would be better if CXXBasePath had the base specifier for
3121 // the nearest virtual base.
3122 unsigned Start = 0;
3123 for (unsigned I = Path.size(); I != 0; --I) {
3124 if (Path[I - 1].Base->isVirtual()) {
3125 Start = I - 1;
3126 break;
3127 }
3128 }
3129
3130 // Now add all bases.
3131 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3132 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3133}
3134
3135
3136void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3137 CXXCastPath &BasePathArray) {
3138 assert(BasePathArray.empty() && "Base path array must be empty!");
3139 assert(Paths.isRecordingPaths() && "Must record paths!");
3140 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3141}
3142
3143bool
3144Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3145 unsigned InaccessibleBaseID,
3146 unsigned AmbiguousBaseConvID,
3147 SourceLocation Loc, SourceRange Range,
3148 DeclarationName Name,
3149 CXXCastPath *BasePath,
3150 bool IgnoreAccess) {
3151 // First, determine whether the path from Derived to Base is
3152 // ambiguous. This is slightly more expensive than checking whether
3153 // the Derived to Base conversion exists, because here we need to
3154 // explore multiple paths to determine if there is an ambiguity.
3155 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3156 /*DetectVirtual=*/false);
3157 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3158 if (!DerivationOkay)
3159 return true;
3160
3161 const CXXBasePath *Path = nullptr;
3162 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3163 Path = &Paths.front();
3164
3165 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3166 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3167 // user to access such bases.
3168 if (!Path && getLangOpts().MSVCCompat) {
3169 for (const CXXBasePath &PossiblePath : Paths) {
3170 if (PossiblePath.size() == 1) {
3171 Path = &PossiblePath;
3172 if (AmbiguousBaseConvID)
3173 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3174 << Base << Derived << Range;
3175 break;
3176 }
3177 }
3178 }
3179
3180 if (Path) {
3181 if (!IgnoreAccess) {
3182 // Check that the base class can be accessed.
3183 switch (
3184 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3185 case AR_inaccessible:
3186 return true;
3187 case AR_accessible:
3188 case AR_dependent:
3189 case AR_delayed:
3190 break;
3191 }
3192 }
3193
3194 // Build a base path if necessary.
3195 if (BasePath)
3196 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3197 return false;
3198 }
3199
3200 if (AmbiguousBaseConvID) {
3201 // We know that the derived-to-base conversion is ambiguous, and
3202 // we're going to produce a diagnostic. Perform the derived-to-base
3203 // search just one more time to compute all of the possible paths so
3204 // that we can print them out. This is more expensive than any of
3205 // the previous derived-to-base checks we've done, but at this point
3206 // performance isn't as much of an issue.
3207 Paths.clear();
3208 Paths.setRecordingPaths(true);
3209 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3210 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3211 (void)StillOkay;
3212
3213 // Build up a textual representation of the ambiguous paths, e.g.,
3214 // D -> B -> A, that will be used to illustrate the ambiguous
3215 // conversions in the diagnostic. We only print one of the paths
3216 // to each base class subobject.
3217 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3218
3219 Diag(Loc, DiagID: AmbiguousBaseConvID)
3220 << Derived << Base << PathDisplayStr << Range << Name;
3221 }
3222 return true;
3223}
3224
3225bool
3226Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3227 SourceLocation Loc, SourceRange Range,
3228 CXXCastPath *BasePath,
3229 bool IgnoreAccess) {
3230 return CheckDerivedToBaseConversion(
3231 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3232 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3233 BasePath, IgnoreAccess);
3234}
3235
3236std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3237 std::string PathDisplayStr;
3238 std::set<unsigned> DisplayedPaths;
3239 for (const CXXBasePath &Path : Paths) {
3240 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3241 // We haven't displayed a path to this particular base
3242 // class subobject yet.
3243 PathDisplayStr += "\n ";
3244 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3245 .getAsString();
3246 for (const CXXBasePathElement &Element : Path)
3247 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3248 }
3249 }
3250
3251 return PathDisplayStr;
3252}
3253
3254//===----------------------------------------------------------------------===//
3255// C++ class member Handling
3256//===----------------------------------------------------------------------===//
3257
3258bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3259 SourceLocation ColonLoc,
3260 const ParsedAttributesView &Attrs) {
3261 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3262 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3263 ASLoc, ColonLoc);
3264 CurContext->addHiddenDecl(D: ASDecl);
3265 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3266}
3267
3268void Sema::CheckOverrideControl(NamedDecl *D) {
3269 if (D->isInvalidDecl())
3270 return;
3271
3272 // We only care about "override" and "final" declarations.
3273 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3274 return;
3275
3276 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3277
3278 // We can't check dependent instance methods.
3279 if (MD && MD->isInstance() &&
3280 (MD->getParent()->hasAnyDependentBases() ||
3281 MD->getType()->isDependentType()))
3282 return;
3283
3284 if (MD && !MD->isVirtual()) {
3285 // If we have a non-virtual method, check if it hides a virtual method.
3286 // (In that case, it's most likely the method has the wrong type.)
3287 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3288 FindHiddenVirtualMethods(MD, OverloadedMethods);
3289
3290 if (!OverloadedMethods.empty()) {
3291 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3292 Diag(Loc: OA->getLocation(),
3293 DiagID: diag::override_keyword_hides_virtual_member_function)
3294 << "override" << (OverloadedMethods.size() > 1);
3295 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3296 Diag(Loc: FA->getLocation(),
3297 DiagID: diag::override_keyword_hides_virtual_member_function)
3298 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3299 << (OverloadedMethods.size() > 1);
3300 }
3301 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3302 MD->setInvalidDecl();
3303 return;
3304 }
3305 // Fall through into the general case diagnostic.
3306 // FIXME: We might want to attempt typo correction here.
3307 }
3308
3309 if (!MD || !MD->isVirtual()) {
3310 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3311 Diag(Loc: OA->getLocation(),
3312 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3313 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3314 D->dropAttr<OverrideAttr>();
3315 }
3316 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3317 Diag(Loc: FA->getLocation(),
3318 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3319 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3320 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3321 D->dropAttr<FinalAttr>();
3322 }
3323 return;
3324 }
3325
3326 // C++11 [class.virtual]p5:
3327 // If a function is marked with the virt-specifier override and
3328 // does not override a member function of a base class, the program is
3329 // ill-formed.
3330 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3331 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3332 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3333 << MD->getDeclName();
3334}
3335
3336void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3337 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3338 return;
3339 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3340 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3341 return;
3342
3343 SourceLocation Loc = MD->getLocation();
3344 SourceLocation SpellingLoc = Loc;
3345 if (getSourceManager().isMacroArgExpansion(Loc))
3346 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3347 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3348 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3349 return;
3350
3351 if (MD->size_overridden_methods() > 0) {
3352 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3353 unsigned DiagID =
3354 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3355 ? DiagInconsistent
3356 : DiagSuggest;
3357 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3358 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3359 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3360 };
3361 if (isa<CXXDestructorDecl>(Val: MD))
3362 EmitDiag(
3363 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3364 diag::warn_suggest_destructor_marked_not_override_overriding);
3365 else
3366 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3367 diag::warn_suggest_function_marked_not_override_overriding);
3368 }
3369}
3370
3371bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3372 const CXXMethodDecl *Old) {
3373 FinalAttr *FA = Old->getAttr<FinalAttr>();
3374 if (!FA)
3375 return false;
3376
3377 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3378 << New->getDeclName()
3379 << FA->isSpelledAsSealed();
3380 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3381 return true;
3382}
3383
3384static bool InitializationHasSideEffects(const FieldDecl &FD) {
3385 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3386 // FIXME: Destruction of ObjC lifetime types has side-effects.
3387 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3388 return !RD->isCompleteDefinition() ||
3389 !RD->hasTrivialDefaultConstructor() ||
3390 !RD->hasTrivialDestructor();
3391 return false;
3392}
3393
3394void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3395 DeclarationName FieldName,
3396 const CXXRecordDecl *RD,
3397 bool DeclIsField) {
3398 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3399 return;
3400
3401 // To record a shadowed field in a base
3402 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3403 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3404 CXXBasePath &Path) {
3405 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3406 // Record an ambiguous path directly
3407 if (Bases.find(x: Base) != Bases.end())
3408 return true;
3409 for (const auto Field : Base->lookup(Name: FieldName)) {
3410 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3411 Field->getAccess() != AS_private) {
3412 assert(Field->getAccess() != AS_none);
3413 assert(Bases.find(Base) == Bases.end());
3414 Bases[Base] = Field;
3415 return true;
3416 }
3417 }
3418 return false;
3419 };
3420
3421 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3422 /*DetectVirtual=*/true);
3423 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3424 return;
3425
3426 for (const auto &P : Paths) {
3427 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3428 auto It = Bases.find(x: Base);
3429 // Skip duplicated bases
3430 if (It == Bases.end())
3431 continue;
3432 auto BaseField = It->second;
3433 assert(BaseField->getAccess() != AS_private);
3434 if (AS_none !=
3435 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3436 Diag(Loc, DiagID: diag::warn_shadow_field)
3437 << FieldName << RD << Base << DeclIsField;
3438 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3439 Bases.erase(position: It);
3440 }
3441 }
3442}
3443
3444template <typename AttrType>
3445inline static bool HasAttribute(const QualType &T) {
3446 if (const TagDecl *TD = T->getAsTagDecl())
3447 return TD->hasAttr<AttrType>();
3448 if (const TypedefType *TDT = T->getAs<TypedefType>())
3449 return TDT->getDecl()->hasAttr<AttrType>();
3450 return false;
3451}
3452
3453static bool IsUnusedPrivateField(const FieldDecl *FD) {
3454 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3455 QualType FieldType = FD->getType();
3456 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3457 return true;
3458
3459 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3460 !FD->getParent()->isDependentContext() &&
3461 !HasAttribute<UnusedAttr>(T: FieldType) &&
3462 !InitializationHasSideEffects(FD: *FD);
3463 }
3464 return false;
3465}
3466
3467NamedDecl *
3468Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3469 MultiTemplateParamsArg TemplateParameterLists,
3470 Expr *BitWidth, const VirtSpecifiers &VS,
3471 InClassInitStyle InitStyle) {
3472 const DeclSpec &DS = D.getDeclSpec();
3473 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3474 DeclarationName Name = NameInfo.getName();
3475 SourceLocation Loc = NameInfo.getLoc();
3476
3477 // For anonymous bitfields, the location should point to the type.
3478 if (Loc.isInvalid())
3479 Loc = D.getBeginLoc();
3480
3481 assert(isa<CXXRecordDecl>(CurContext));
3482 assert(!DS.isFriendSpecified());
3483
3484 bool isFunc = D.isDeclarationOfFunction();
3485 const ParsedAttr *MSPropertyAttr =
3486 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3487
3488 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3489 // The Microsoft extension __interface only permits public member functions
3490 // and prohibits constructors, destructors, operators, non-public member
3491 // functions, static methods and data members.
3492 unsigned InvalidDecl;
3493 bool ShowDeclName = true;
3494 if (!isFunc &&
3495 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3496 InvalidDecl = 0;
3497 else if (!isFunc)
3498 InvalidDecl = 1;
3499 else if (AS != AS_public)
3500 InvalidDecl = 2;
3501 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3502 InvalidDecl = 3;
3503 else switch (Name.getNameKind()) {
3504 case DeclarationName::CXXConstructorName:
3505 InvalidDecl = 4;
3506 ShowDeclName = false;
3507 break;
3508
3509 case DeclarationName::CXXDestructorName:
3510 InvalidDecl = 5;
3511 ShowDeclName = false;
3512 break;
3513
3514 case DeclarationName::CXXOperatorName:
3515 case DeclarationName::CXXConversionFunctionName:
3516 InvalidDecl = 6;
3517 break;
3518
3519 default:
3520 InvalidDecl = 0;
3521 break;
3522 }
3523
3524 if (InvalidDecl) {
3525 if (ShowDeclName)
3526 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3527 << (InvalidDecl-1) << Name;
3528 else
3529 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3530 << (InvalidDecl-1) << "";
3531 return nullptr;
3532 }
3533 }
3534
3535 // HLSL prohibits user defined constructors and destructors.
3536 if (getLangOpts().HLSL) {
3537 switch (Name.getNameKind()) {
3538 case DeclarationName::CXXConstructorName:
3539 case DeclarationName::CXXDestructorName:
3540 Diag(Loc, DiagID: diag::err_hlsl_cstor_dstor);
3541 return nullptr;
3542 default:
3543 break;
3544 }
3545 }
3546
3547 // C++ 9.2p6: A member shall not be declared to have automatic storage
3548 // duration (auto, register) or with the extern storage-class-specifier.
3549 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3550 // data members and cannot be applied to names declared const or static,
3551 // and cannot be applied to reference members.
3552 switch (DS.getStorageClassSpec()) {
3553 case DeclSpec::SCS_unspecified:
3554 case DeclSpec::SCS_typedef:
3555 case DeclSpec::SCS_static:
3556 break;
3557 case DeclSpec::SCS_mutable:
3558 if (isFunc) {
3559 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3560
3561 // FIXME: It would be nicer if the keyword was ignored only for this
3562 // declarator. Otherwise we could get follow-up errors.
3563 D.getMutableDeclSpec().ClearStorageClassSpecs();
3564 }
3565 break;
3566 default:
3567 Diag(Loc: DS.getStorageClassSpecLoc(),
3568 DiagID: diag::err_storageclass_invalid_for_member);
3569 D.getMutableDeclSpec().ClearStorageClassSpecs();
3570 break;
3571 }
3572
3573 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3574 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3575 !isFunc && TemplateParameterLists.empty();
3576
3577 if (DS.hasConstexprSpecifier() && isInstField) {
3578 SemaDiagnosticBuilder B =
3579 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3580 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3581 if (InitStyle == ICIS_NoInit) {
3582 B << 0 << 0;
3583 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3584 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3585 else {
3586 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3587 D.getMutableDeclSpec().ClearConstexprSpec();
3588 const char *PrevSpec;
3589 unsigned DiagID;
3590 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3591 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3592 (void)Failed;
3593 assert(!Failed && "Making a constexpr member const shouldn't fail");
3594 }
3595 } else {
3596 B << 1;
3597 const char *PrevSpec;
3598 unsigned DiagID;
3599 if (D.getMutableDeclSpec().SetStorageClassSpec(
3600 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3601 Policy: Context.getPrintingPolicy())) {
3602 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3603 "This is the only DeclSpec that should fail to be applied");
3604 B << 1;
3605 } else {
3606 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3607 isInstField = false;
3608 }
3609 }
3610 }
3611
3612 NamedDecl *Member;
3613 if (isInstField) {
3614 CXXScopeSpec &SS = D.getCXXScopeSpec();
3615
3616 // Data members must have identifiers for names.
3617 if (!Name.isIdentifier()) {
3618 Diag(Loc, DiagID: diag::err_bad_variable_name)
3619 << Name;
3620 return nullptr;
3621 }
3622
3623 IdentifierInfo *II = Name.getAsIdentifierInfo();
3624 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3625 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3626 << II
3627 << SourceRange(D.getName().TemplateId->LAngleLoc,
3628 D.getName().TemplateId->RAngleLoc)
3629 << D.getName().TemplateId->LAngleLoc;
3630 D.SetIdentifier(Id: II, IdLoc: Loc);
3631 }
3632
3633 if (SS.isSet() && !SS.isInvalid()) {
3634 // The user provided a superfluous scope specifier inside a class
3635 // definition:
3636 //
3637 // class X {
3638 // int X::member;
3639 // };
3640 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3641 TemplateIdAnnotation *TemplateId =
3642 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3643 ? D.getName().TemplateId
3644 : nullptr;
3645 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3646 TemplateId,
3647 /*IsMemberSpecialization=*/false);
3648 } else {
3649 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3650 << Name << SS.getRange();
3651 }
3652 SS.clear();
3653 }
3654
3655 if (MSPropertyAttr) {
3656 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3657 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3658 if (!Member)
3659 return nullptr;
3660 isInstField = false;
3661 } else {
3662 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3663 BitfieldWidth: BitWidth, InitStyle, AS);
3664 if (!Member)
3665 return nullptr;
3666 }
3667
3668 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3669 } else {
3670 Member = HandleDeclarator(S, D, TemplateParameterLists);
3671 if (!Member)
3672 return nullptr;
3673
3674 // Non-instance-fields can't have a bitfield.
3675 if (BitWidth) {
3676 if (Member->isInvalidDecl()) {
3677 // don't emit another diagnostic.
3678 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3679 // C++ 9.6p3: A bit-field shall not be a static member.
3680 // "static member 'A' cannot be a bit-field"
3681 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3682 << Name << BitWidth->getSourceRange();
3683 } else if (isa<TypedefDecl>(Val: Member)) {
3684 // "typedef member 'x' cannot be a bit-field"
3685 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3686 << Name << BitWidth->getSourceRange();
3687 } else {
3688 // A function typedef ("typedef int f(); f a;").
3689 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3690 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3691 << Name << cast<ValueDecl>(Val: Member)->getType()
3692 << BitWidth->getSourceRange();
3693 }
3694
3695 BitWidth = nullptr;
3696 Member->setInvalidDecl();
3697 }
3698
3699 NamedDecl *NonTemplateMember = Member;
3700 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3701 NonTemplateMember = FunTmpl->getTemplatedDecl();
3702 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3703 NonTemplateMember = VarTmpl->getTemplatedDecl();
3704
3705 Member->setAccess(AS);
3706
3707 // If we have declared a member function template or static data member
3708 // template, set the access of the templated declaration as well.
3709 if (NonTemplateMember != Member)
3710 NonTemplateMember->setAccess(AS);
3711
3712 // C++ [temp.deduct.guide]p3:
3713 // A deduction guide [...] for a member class template [shall be
3714 // declared] with the same access [as the template].
3715 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3716 auto *TD = DG->getDeducedTemplate();
3717 // Access specifiers are only meaningful if both the template and the
3718 // deduction guide are from the same scope.
3719 if (AS != TD->getAccess() &&
3720 TD->getDeclContext()->getRedeclContext()->Equals(
3721 DC: DG->getDeclContext()->getRedeclContext())) {
3722 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3723 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3724 << TD->getAccess();
3725 const AccessSpecDecl *LastAccessSpec = nullptr;
3726 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3727 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3728 LastAccessSpec = AccessSpec;
3729 }
3730 assert(LastAccessSpec && "differing access with no access specifier");
3731 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3732 << AS;
3733 }
3734 }
3735 }
3736
3737 if (VS.isOverrideSpecified())
3738 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3739 if (VS.isFinalSpecified())
3740 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3741 S: VS.isFinalSpelledSealed()
3742 ? FinalAttr::Keyword_sealed
3743 : FinalAttr::Keyword_final));
3744
3745 if (VS.getLastLocation().isValid()) {
3746 // Update the end location of a method that has a virt-specifiers.
3747 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3748 MD->setRangeEnd(VS.getLastLocation());
3749 }
3750
3751 CheckOverrideControl(D: Member);
3752
3753 assert((Name || isInstField) && "No identifier for non-field ?");
3754
3755 if (isInstField) {
3756 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3757 FieldCollector->Add(D: FD);
3758
3759 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3760 IsUnusedPrivateField(FD)) {
3761 // Remember all explicit private FieldDecls that have a name, no side
3762 // effects and are not part of a dependent type declaration.
3763 UnusedPrivateFields.insert(X: FD);
3764 }
3765 }
3766
3767 return Member;
3768}
3769
3770namespace {
3771 class UninitializedFieldVisitor
3772 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3773 Sema &S;
3774 // List of Decls to generate a warning on. Also remove Decls that become
3775 // initialized.
3776 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3777 // List of base classes of the record. Classes are removed after their
3778 // initializers.
3779 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3780 // Vector of decls to be removed from the Decl set prior to visiting the
3781 // nodes. These Decls may have been initialized in the prior initializer.
3782 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3783 // If non-null, add a note to the warning pointing back to the constructor.
3784 const CXXConstructorDecl *Constructor;
3785 // Variables to hold state when processing an initializer list. When
3786 // InitList is true, special case initialization of FieldDecls matching
3787 // InitListFieldDecl.
3788 bool InitList;
3789 FieldDecl *InitListFieldDecl;
3790 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3791
3792 public:
3793 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3794 UninitializedFieldVisitor(Sema &S,
3795 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3796 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3797 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3798 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3799
3800 // Returns true if the use of ME is not an uninitialized use.
3801 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3802 bool CheckReferenceOnly) {
3803 llvm::SmallVector<FieldDecl*, 4> Fields;
3804 bool ReferenceField = false;
3805 while (ME) {
3806 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3807 if (!FD)
3808 return false;
3809 Fields.push_back(Elt: FD);
3810 if (FD->getType()->isReferenceType())
3811 ReferenceField = true;
3812 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3813 }
3814
3815 // Binding a reference to an uninitialized field is not an
3816 // uninitialized use.
3817 if (CheckReferenceOnly && !ReferenceField)
3818 return true;
3819
3820 // Discard the first field since it is the field decl that is being
3821 // initialized.
3822 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3823 auto UsedIter = UsedFields.begin();
3824 const auto UsedEnd = UsedFields.end();
3825
3826 for (const unsigned Orig : InitFieldIndex) {
3827 if (UsedIter == UsedEnd)
3828 break;
3829 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3830 if (UsedIndex < Orig)
3831 return true;
3832 if (UsedIndex > Orig)
3833 break;
3834 ++UsedIter;
3835 }
3836
3837 return false;
3838 }
3839
3840 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3841 bool AddressOf) {
3842 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3843 return;
3844
3845 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3846 // or union.
3847 MemberExpr *FieldME = ME;
3848
3849 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3850
3851 Expr *Base = ME;
3852 while (MemberExpr *SubME =
3853 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3854
3855 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3856 return;
3857
3858 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3859 if (!FD->isAnonymousStructOrUnion())
3860 FieldME = SubME;
3861
3862 if (!FieldME->getType().isPODType(Context: S.Context))
3863 AllPODFields = false;
3864
3865 Base = SubME->getBase();
3866 }
3867
3868 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3869 Visit(S: Base);
3870 return;
3871 }
3872
3873 if (AddressOf && AllPODFields)
3874 return;
3875
3876 ValueDecl* FoundVD = FieldME->getMemberDecl();
3877
3878 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3879 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3880 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3881 }
3882
3883 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3884 QualType T = BaseCast->getType();
3885 if (T->isPointerType() &&
3886 BaseClasses.count(Ptr: T->getPointeeType())) {
3887 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3888 << T->getPointeeType() << FoundVD;
3889 }
3890 }
3891 }
3892
3893 if (!Decls.count(Ptr: FoundVD))
3894 return;
3895
3896 const bool IsReference = FoundVD->getType()->isReferenceType();
3897
3898 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3899 // Special checking for initializer lists.
3900 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3901 return;
3902 }
3903 } else {
3904 // Prevent double warnings on use of unbounded references.
3905 if (CheckReferenceOnly && !IsReference)
3906 return;
3907 }
3908
3909 unsigned diag = IsReference
3910 ? diag::warn_reference_field_is_uninit
3911 : diag::warn_field_is_uninit;
3912 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3913 if (Constructor)
3914 S.Diag(Loc: Constructor->getLocation(),
3915 DiagID: diag::note_uninit_in_this_constructor)
3916 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3917
3918 }
3919
3920 void HandleValue(Expr *E, bool AddressOf) {
3921 E = E->IgnoreParens();
3922
3923 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3924 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3925 AddressOf /*AddressOf*/);
3926 return;
3927 }
3928
3929 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3930 Visit(S: CO->getCond());
3931 HandleValue(E: CO->getTrueExpr(), AddressOf);
3932 HandleValue(E: CO->getFalseExpr(), AddressOf);
3933 return;
3934 }
3935
3936 if (BinaryConditionalOperator *BCO =
3937 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3938 Visit(S: BCO->getCond());
3939 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3940 return;
3941 }
3942
3943 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3944 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3945 return;
3946 }
3947
3948 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3949 switch (BO->getOpcode()) {
3950 default:
3951 break;
3952 case(BO_PtrMemD):
3953 case(BO_PtrMemI):
3954 HandleValue(E: BO->getLHS(), AddressOf);
3955 Visit(S: BO->getRHS());
3956 return;
3957 case(BO_Comma):
3958 Visit(S: BO->getLHS());
3959 HandleValue(E: BO->getRHS(), AddressOf);
3960 return;
3961 }
3962 }
3963
3964 Visit(S: E);
3965 }
3966
3967 void CheckInitListExpr(InitListExpr *ILE) {
3968 InitFieldIndex.push_back(Elt: 0);
3969 for (auto *Child : ILE->children()) {
3970 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
3971 CheckInitListExpr(ILE: SubList);
3972 } else {
3973 Visit(S: Child);
3974 }
3975 ++InitFieldIndex.back();
3976 }
3977 InitFieldIndex.pop_back();
3978 }
3979
3980 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
3981 FieldDecl *Field, const Type *BaseClass) {
3982 // Remove Decls that may have been initialized in the previous
3983 // initializer.
3984 for (ValueDecl* VD : DeclsToRemove)
3985 Decls.erase(Ptr: VD);
3986 DeclsToRemove.clear();
3987
3988 Constructor = FieldConstructor;
3989 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
3990
3991 if (ILE && Field) {
3992 InitList = true;
3993 InitListFieldDecl = Field;
3994 InitFieldIndex.clear();
3995 CheckInitListExpr(ILE);
3996 } else {
3997 InitList = false;
3998 Visit(S: E);
3999 }
4000
4001 if (Field)
4002 Decls.erase(Ptr: Field);
4003 if (BaseClass)
4004 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4005 }
4006
4007 void VisitMemberExpr(MemberExpr *ME) {
4008 // All uses of unbounded reference fields will warn.
4009 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4010 }
4011
4012 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4013 if (E->getCastKind() == CK_LValueToRValue) {
4014 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4015 return;
4016 }
4017
4018 Inherited::VisitImplicitCastExpr(S: E);
4019 }
4020
4021 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4022 if (E->getConstructor()->isCopyConstructor()) {
4023 Expr *ArgExpr = E->getArg(Arg: 0);
4024 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4025 if (ILE->getNumInits() == 1)
4026 ArgExpr = ILE->getInit(Init: 0);
4027 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4028 if (ICE->getCastKind() == CK_NoOp)
4029 ArgExpr = ICE->getSubExpr();
4030 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4031 return;
4032 }
4033 Inherited::VisitCXXConstructExpr(S: E);
4034 }
4035
4036 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4037 Expr *Callee = E->getCallee();
4038 if (isa<MemberExpr>(Val: Callee)) {
4039 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4040 for (auto *Arg : E->arguments())
4041 Visit(S: Arg);
4042 return;
4043 }
4044
4045 Inherited::VisitCXXMemberCallExpr(S: E);
4046 }
4047
4048 void VisitCallExpr(CallExpr *E) {
4049 // Treat std::move as a use.
4050 if (E->isCallToStdMove()) {
4051 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4052 return;
4053 }
4054
4055 Inherited::VisitCallExpr(CE: E);
4056 }
4057
4058 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4059 Expr *Callee = E->getCallee();
4060
4061 if (isa<UnresolvedLookupExpr>(Val: Callee))
4062 return Inherited::VisitCXXOperatorCallExpr(S: E);
4063
4064 Visit(S: Callee);
4065 for (auto *Arg : E->arguments())
4066 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4067 }
4068
4069 void VisitBinaryOperator(BinaryOperator *E) {
4070 // If a field assignment is detected, remove the field from the
4071 // uninitiailized field set.
4072 if (E->getOpcode() == BO_Assign)
4073 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4074 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4075 if (!FD->getType()->isReferenceType())
4076 DeclsToRemove.push_back(Elt: FD);
4077
4078 if (E->isCompoundAssignmentOp()) {
4079 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4080 Visit(S: E->getRHS());
4081 return;
4082 }
4083
4084 Inherited::VisitBinaryOperator(S: E);
4085 }
4086
4087 void VisitUnaryOperator(UnaryOperator *E) {
4088 if (E->isIncrementDecrementOp()) {
4089 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4090 return;
4091 }
4092 if (E->getOpcode() == UO_AddrOf) {
4093 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4094 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4095 return;
4096 }
4097 }
4098
4099 Inherited::VisitUnaryOperator(S: E);
4100 }
4101 };
4102
4103 // Diagnose value-uses of fields to initialize themselves, e.g.
4104 // foo(foo)
4105 // where foo is not also a parameter to the constructor.
4106 // Also diagnose across field uninitialized use such as
4107 // x(y), y(x)
4108 // TODO: implement -Wuninitialized and fold this into that framework.
4109 static void DiagnoseUninitializedFields(
4110 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4111
4112 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4113 Loc: Constructor->getLocation())) {
4114 return;
4115 }
4116
4117 if (Constructor->isInvalidDecl())
4118 return;
4119
4120 const CXXRecordDecl *RD = Constructor->getParent();
4121
4122 if (RD->isDependentContext())
4123 return;
4124
4125 // Holds fields that are uninitialized.
4126 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4127
4128 // At the beginning, all fields are uninitialized.
4129 for (auto *I : RD->decls()) {
4130 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4131 UninitializedFields.insert(Ptr: FD);
4132 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4133 UninitializedFields.insert(Ptr: IFD->getAnonField());
4134 }
4135 }
4136
4137 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4138 for (const auto &I : RD->bases())
4139 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4140
4141 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4142 return;
4143
4144 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4145 UninitializedFields,
4146 UninitializedBaseClasses);
4147
4148 for (const auto *FieldInit : Constructor->inits()) {
4149 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4150 break;
4151
4152 Expr *InitExpr = FieldInit->getInit();
4153 if (!InitExpr)
4154 continue;
4155
4156 if (CXXDefaultInitExpr *Default =
4157 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4158 InitExpr = Default->getExpr();
4159 if (!InitExpr)
4160 continue;
4161 // In class initializers will point to the constructor.
4162 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4163 Field: FieldInit->getAnyMember(),
4164 BaseClass: FieldInit->getBaseClass());
4165 } else {
4166 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4167 Field: FieldInit->getAnyMember(),
4168 BaseClass: FieldInit->getBaseClass());
4169 }
4170 }
4171 }
4172} // namespace
4173
4174void Sema::ActOnStartCXXInClassMemberInitializer() {
4175 // Create a synthetic function scope to represent the call to the constructor
4176 // that notionally surrounds a use of this initializer.
4177 PushFunctionScope();
4178}
4179
4180void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4181 if (!D.isFunctionDeclarator())
4182 return;
4183 auto &FTI = D.getFunctionTypeInfo();
4184 if (!FTI.Params)
4185 return;
4186 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4187 FTI.NumParams)) {
4188 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4189 if (ParamDecl->getDeclName())
4190 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4191 }
4192}
4193
4194ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4195 return ActOnRequiresClause(ConstraintExpr);
4196}
4197
4198ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4199 if (ConstraintExpr.isInvalid())
4200 return ExprError();
4201
4202 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4203 UPPC: UPPC_RequiresClause))
4204 return ExprError();
4205
4206 return ConstraintExpr;
4207}
4208
4209ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4210 Expr *InitExpr,
4211 SourceLocation InitLoc) {
4212 InitializedEntity Entity =
4213 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4214 InitializationKind Kind =
4215 FD->getInClassInitStyle() == ICIS_ListInit
4216 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4217 LBraceLoc: InitExpr->getBeginLoc(),
4218 RBraceLoc: InitExpr->getEndLoc())
4219 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4220 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4221 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4222}
4223
4224void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4225 SourceLocation InitLoc,
4226 ExprResult InitExpr) {
4227 // Pop the notional constructor scope we created earlier.
4228 PopFunctionScopeInfo(WP: nullptr, D);
4229
4230 // Microsoft C++'s property declaration cannot have a default member
4231 // initializer.
4232 if (isa<MSPropertyDecl>(Val: D)) {
4233 D->setInvalidDecl();
4234 return;
4235 }
4236
4237 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4238 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4239 "must set init style when field is created");
4240
4241 if (!InitExpr.isUsable() ||
4242 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4243 FD->setInvalidDecl();
4244 ExprResult RecoveryInit =
4245 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4246 if (RecoveryInit.isUsable())
4247 FD->setInClassInitializer(RecoveryInit.get());
4248 return;
4249 }
4250
4251 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4252 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4253 // C++11 [class.base.init]p7:
4254 // The initialization of each base and member constitutes a
4255 // full-expression.
4256 if (!InitExpr.isInvalid())
4257 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4258 if (InitExpr.isInvalid()) {
4259 FD->setInvalidDecl();
4260 return;
4261 }
4262 }
4263
4264 FD->setInClassInitializer(InitExpr.get());
4265}
4266
4267/// Find the direct and/or virtual base specifiers that
4268/// correspond to the given base type, for use in base initialization
4269/// within a constructor.
4270static bool FindBaseInitializer(Sema &SemaRef,
4271 CXXRecordDecl *ClassDecl,
4272 QualType BaseType,
4273 const CXXBaseSpecifier *&DirectBaseSpec,
4274 const CXXBaseSpecifier *&VirtualBaseSpec) {
4275 // First, check for a direct base class.
4276 DirectBaseSpec = nullptr;
4277 for (const auto &Base : ClassDecl->bases()) {
4278 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4279 // We found a direct base of this type. That's what we're
4280 // initializing.
4281 DirectBaseSpec = &Base;
4282 break;
4283 }
4284 }
4285
4286 // Check for a virtual base class.
4287 // FIXME: We might be able to short-circuit this if we know in advance that
4288 // there are no virtual bases.
4289 VirtualBaseSpec = nullptr;
4290 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4291 // We haven't found a base yet; search the class hierarchy for a
4292 // virtual base class.
4293 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4294 /*DetectVirtual=*/false);
4295 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4296 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4297 Base: BaseType, Paths)) {
4298 for (const CXXBasePath &Path : Paths) {
4299 if (Path.back().Base->isVirtual()) {
4300 VirtualBaseSpec = Path.back().Base;
4301 break;
4302 }
4303 }
4304 }
4305 }
4306
4307 return DirectBaseSpec || VirtualBaseSpec;
4308}
4309
4310MemInitResult
4311Sema::ActOnMemInitializer(Decl *ConstructorD,
4312 Scope *S,
4313 CXXScopeSpec &SS,
4314 IdentifierInfo *MemberOrBase,
4315 ParsedType TemplateTypeTy,
4316 const DeclSpec &DS,
4317 SourceLocation IdLoc,
4318 Expr *InitList,
4319 SourceLocation EllipsisLoc) {
4320 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4321 DS, IdLoc, Init: InitList,
4322 EllipsisLoc);
4323}
4324
4325MemInitResult
4326Sema::ActOnMemInitializer(Decl *ConstructorD,
4327 Scope *S,
4328 CXXScopeSpec &SS,
4329 IdentifierInfo *MemberOrBase,
4330 ParsedType TemplateTypeTy,
4331 const DeclSpec &DS,
4332 SourceLocation IdLoc,
4333 SourceLocation LParenLoc,
4334 ArrayRef<Expr *> Args,
4335 SourceLocation RParenLoc,
4336 SourceLocation EllipsisLoc) {
4337 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4338 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4339 DS, IdLoc, Init: List, EllipsisLoc);
4340}
4341
4342namespace {
4343
4344// Callback to only accept typo corrections that can be a valid C++ member
4345// initializer: either a non-static field member or a base class.
4346class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4347public:
4348 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4349 : ClassDecl(ClassDecl) {}
4350
4351 bool ValidateCandidate(const TypoCorrection &candidate) override {
4352 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4353 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4354 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4355 return isa<TypeDecl>(Val: ND);
4356 }
4357 return false;
4358 }
4359
4360 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4361 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4362 }
4363
4364private:
4365 CXXRecordDecl *ClassDecl;
4366};
4367
4368}
4369
4370bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4371 RecordDecl *ClassDecl,
4372 const IdentifierInfo *Name) {
4373 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4374 DeclContextLookupResult::iterator Found =
4375 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4376 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4377 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4378 });
4379 // We did not find a placeholder variable
4380 if (Found == Result.end())
4381 return false;
4382 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4383 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4384 const NamedDecl *ND = *It;
4385 if (ND->getDeclContext() != ND->getDeclContext())
4386 break;
4387 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4388 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4389 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4390 }
4391 return true;
4392}
4393
4394ValueDecl *
4395Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4396 const IdentifierInfo *MemberOrBase) {
4397 ValueDecl *ND = nullptr;
4398 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4399 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4400 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4401 if (ND) {
4402 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4403 return nullptr;
4404 break;
4405 }
4406 if (!IsPlaceholder)
4407 return cast<ValueDecl>(Val: D);
4408 ND = cast<ValueDecl>(Val: D);
4409 }
4410 }
4411 return ND;
4412}
4413
4414ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4415 CXXScopeSpec &SS,
4416 ParsedType TemplateTypeTy,
4417 IdentifierInfo *MemberOrBase) {
4418 if (SS.getScopeRep() || TemplateTypeTy)
4419 return nullptr;
4420 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4421}
4422
4423MemInitResult
4424Sema::BuildMemInitializer(Decl *ConstructorD,
4425 Scope *S,
4426 CXXScopeSpec &SS,
4427 IdentifierInfo *MemberOrBase,
4428 ParsedType TemplateTypeTy,
4429 const DeclSpec &DS,
4430 SourceLocation IdLoc,
4431 Expr *Init,
4432 SourceLocation EllipsisLoc) {
4433 if (!ConstructorD || !Init)
4434 return true;
4435
4436 AdjustDeclIfTemplate(Decl&: ConstructorD);
4437
4438 CXXConstructorDecl *Constructor
4439 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4440 if (!Constructor) {
4441 // The user wrote a constructor initializer on a function that is
4442 // not a C++ constructor. Ignore the error for now, because we may
4443 // have more member initializers coming; we'll diagnose it just
4444 // once in ActOnMemInitializers.
4445 return true;
4446 }
4447
4448 CXXRecordDecl *ClassDecl = Constructor->getParent();
4449
4450 // C++ [class.base.init]p2:
4451 // Names in a mem-initializer-id are looked up in the scope of the
4452 // constructor's class and, if not found in that scope, are looked
4453 // up in the scope containing the constructor's definition.
4454 // [Note: if the constructor's class contains a member with the
4455 // same name as a direct or virtual base class of the class, a
4456 // mem-initializer-id naming the member or base class and composed
4457 // of a single identifier refers to the class member. A
4458 // mem-initializer-id for the hidden base class may be specified
4459 // using a qualified name. ]
4460
4461 // Look for a member, first.
4462 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4463 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4464 if (EllipsisLoc.isValid())
4465 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4466 << MemberOrBase
4467 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4468
4469 return BuildMemberInitializer(Member, Init, IdLoc);
4470 }
4471 // It didn't name a member, so see if it names a class.
4472 QualType BaseType;
4473 TypeSourceInfo *TInfo = nullptr;
4474
4475 if (TemplateTypeTy) {
4476 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4477 if (BaseType.isNull())
4478 return true;
4479 } else if (DS.getTypeSpecType() == TST_decltype) {
4480 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4481 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4482 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4483 return true;
4484 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4485 BaseType =
4486 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4487 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4488 } else {
4489 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4490 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4491
4492 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4493 if (!TyD) {
4494 if (R.isAmbiguous()) return true;
4495
4496 // We don't want access-control diagnostics here.
4497 R.suppressDiagnostics();
4498
4499 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4500 bool NotUnknownSpecialization = false;
4501 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4502 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4503 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4504
4505 if (!NotUnknownSpecialization) {
4506 // When the scope specifier can refer to a member of an unknown
4507 // specialization, we take it as a type name.
4508 BaseType = CheckTypenameType(
4509 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4510 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4511 if (BaseType.isNull())
4512 return true;
4513
4514 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4515 DependentNameTypeLoc TL =
4516 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4517 if (!TL.isNull()) {
4518 TL.setNameLoc(IdLoc);
4519 TL.setElaboratedKeywordLoc(SourceLocation());
4520 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4521 }
4522
4523 R.clear();
4524 R.setLookupName(MemberOrBase);
4525 }
4526 }
4527
4528 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4529 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4530 auto *TempSpec = cast<TemplateSpecializationType>(
4531 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4532 TemplateName TN = TempSpec->getTemplateName();
4533 for (auto const &Base : ClassDecl->bases()) {
4534 auto BaseTemplate =
4535 Base.getType()->getAs<TemplateSpecializationType>();
4536 if (BaseTemplate &&
4537 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4538 /*IgnoreDeduced=*/true)) {
4539 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4540 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4541 BaseType = Base.getType();
4542 break;
4543 }
4544 }
4545 }
4546 }
4547
4548 // If no results were found, try to correct typos.
4549 TypoCorrection Corr;
4550 MemInitializerValidatorCCC CCC(ClassDecl);
4551 if (R.empty() && BaseType.isNull() &&
4552 (Corr =
4553 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4554 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4555 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4556 // We have found a non-static data member with a similar
4557 // name to what was typed; complain and initialize that
4558 // member.
4559 diagnoseTypo(Correction: Corr,
4560 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4561 << MemberOrBase << true);
4562 return BuildMemberInitializer(Member, Init, IdLoc);
4563 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4564 const CXXBaseSpecifier *DirectBaseSpec;
4565 const CXXBaseSpecifier *VirtualBaseSpec;
4566 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4567 BaseType: Context.getTypeDeclType(Decl: Type),
4568 DirectBaseSpec, VirtualBaseSpec)) {
4569 // We have found a direct or virtual base class with a
4570 // similar name to what was typed; complain and initialize
4571 // that base class.
4572 diagnoseTypo(Correction: Corr,
4573 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4574 << MemberOrBase << false,
4575 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4576
4577 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4578 : VirtualBaseSpec;
4579 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4580 << BaseSpec->getType() << BaseSpec->getSourceRange();
4581
4582 TyD = Type;
4583 }
4584 }
4585 }
4586
4587 if (!TyD && BaseType.isNull()) {
4588 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4589 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4590 return true;
4591 }
4592 }
4593
4594 if (BaseType.isNull()) {
4595 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4596
4597 TypeLocBuilder TLB;
4598 // FIXME: This is missing building the UsingType for TyD, if any.
4599 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4600 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4601 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4602 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4603 TL.setElaboratedKeywordLoc(SourceLocation());
4604 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4605 TL.setNameLoc(IdLoc);
4606 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4607 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4608 Qualifier: SS.getScopeRep(), Decl: TN);
4609 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4610 /*ElaboratedKeywordLoc=*/SourceLocation(),
4611 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4612 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4613 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4614 Qualifier: SS.getScopeRep(), D: UD);
4615 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4616 /*ElaboratedKeywordLoc=*/SourceLocation(),
4617 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4618 } else {
4619 // FIXME: What else can appear here?
4620 assert(SS.isEmpty());
4621 BaseType = Context.getTypeDeclType(Decl: TyD);
4622 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4623 }
4624 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4625 }
4626 }
4627
4628 if (!TInfo)
4629 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4630
4631 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4632}
4633
4634MemInitResult
4635Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4636 SourceLocation IdLoc) {
4637 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4638 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4639 assert((DirectMember || IndirectMember) &&
4640 "Member must be a FieldDecl or IndirectFieldDecl");
4641
4642 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4643 return true;
4644
4645 if (Member->isInvalidDecl())
4646 return true;
4647
4648 MultiExprArg Args;
4649 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4650 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4651 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4652 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4653 } else {
4654 // Template instantiation doesn't reconstruct ParenListExprs for us.
4655 Args = Init;
4656 }
4657
4658 SourceRange InitRange = Init->getSourceRange();
4659
4660 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4661 // Can't check initialization for a member of dependent type or when
4662 // any of the arguments are type-dependent expressions.
4663 DiscardCleanupsInEvaluationContext();
4664 } else {
4665 bool InitList = false;
4666 if (isa<InitListExpr>(Val: Init)) {
4667 InitList = true;
4668 Args = Init;
4669 }
4670
4671 // Initialize the member.
4672 InitializedEntity MemberEntity =
4673 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4674 : InitializedEntity::InitializeMember(Member: IndirectMember,
4675 Parent: nullptr);
4676 InitializationKind Kind =
4677 InitList ? InitializationKind::CreateDirectList(
4678 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4679 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4680 RParenLoc: InitRange.getEnd());
4681
4682 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4683 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4684 ResultType: nullptr);
4685 if (!MemberInit.isInvalid()) {
4686 // C++11 [class.base.init]p7:
4687 // The initialization of each base and member constitutes a
4688 // full-expression.
4689 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4690 /*DiscardedValue*/ false);
4691 }
4692
4693 if (MemberInit.isInvalid()) {
4694 // Args were sensible expressions but we couldn't initialize the member
4695 // from them. Preserve them in a RecoveryExpr instead.
4696 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4697 T: Member->getType())
4698 .get();
4699 if (!Init)
4700 return true;
4701 } else {
4702 Init = MemberInit.get();
4703 }
4704 }
4705
4706 if (DirectMember) {
4707 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4708 InitRange.getBegin(), Init,
4709 InitRange.getEnd());
4710 } else {
4711 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4712 InitRange.getBegin(), Init,
4713 InitRange.getEnd());
4714 }
4715}
4716
4717MemInitResult
4718Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4719 CXXRecordDecl *ClassDecl) {
4720 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4721 if (!LangOpts.CPlusPlus11)
4722 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4723 << TInfo->getTypeLoc().getSourceRange();
4724 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4725
4726 bool InitList = true;
4727 MultiExprArg Args = Init;
4728 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4729 InitList = false;
4730 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4731 }
4732
4733 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4734
4735 SourceRange InitRange = Init->getSourceRange();
4736 // Initialize the object.
4737 InitializedEntity DelegationEntity =
4738 InitializedEntity::InitializeDelegation(Type: ClassType);
4739 InitializationKind Kind =
4740 InitList ? InitializationKind::CreateDirectList(
4741 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4742 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4743 RParenLoc: InitRange.getEnd());
4744 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4745 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4746 Args, ResultType: nullptr);
4747 if (!DelegationInit.isInvalid()) {
4748 assert((DelegationInit.get()->containsErrors() ||
4749 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4750 "Delegating constructor with no target?");
4751
4752 // C++11 [class.base.init]p7:
4753 // The initialization of each base and member constitutes a
4754 // full-expression.
4755 DelegationInit = ActOnFinishFullExpr(
4756 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4757 }
4758
4759 if (DelegationInit.isInvalid()) {
4760 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4761 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4762 if (DelegationInit.isInvalid())
4763 return true;
4764 } else {
4765 // If we are in a dependent context, template instantiation will
4766 // perform this type-checking again. Just save the arguments that we
4767 // received in a ParenListExpr.
4768 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4769 // of the information that we have about the base
4770 // initializer. However, deconstructing the ASTs is a dicey process,
4771 // and this approach is far more likely to get the corner cases right.
4772 if (CurContext->isDependentContext())
4773 DelegationInit = Init;
4774 }
4775
4776 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4777 DelegationInit.getAs<Expr>(),
4778 InitRange.getEnd());
4779}
4780
4781MemInitResult
4782Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4783 Expr *Init, CXXRecordDecl *ClassDecl,
4784 SourceLocation EllipsisLoc) {
4785 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4786
4787 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4788 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4789 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4790
4791 // C++ [class.base.init]p2:
4792 // [...] Unless the mem-initializer-id names a nonstatic data
4793 // member of the constructor's class or a direct or virtual base
4794 // of that class, the mem-initializer is ill-formed. A
4795 // mem-initializer-list can initialize a base class using any
4796 // name that denotes that base class type.
4797
4798 // We can store the initializers in "as-written" form and delay analysis until
4799 // instantiation if the constructor is dependent. But not for dependent
4800 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4801 bool Dependent = CurContext->isDependentContext() &&
4802 (BaseType->isDependentType() || Init->isTypeDependent());
4803
4804 SourceRange InitRange = Init->getSourceRange();
4805 if (EllipsisLoc.isValid()) {
4806 // This is a pack expansion.
4807 if (!BaseType->containsUnexpandedParameterPack()) {
4808 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4809 << SourceRange(BaseLoc, InitRange.getEnd());
4810
4811 EllipsisLoc = SourceLocation();
4812 }
4813 } else {
4814 // Check for any unexpanded parameter packs.
4815 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4816 return true;
4817
4818 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4819 return true;
4820 }
4821
4822 // Check for direct and virtual base classes.
4823 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4824 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4825 if (!Dependent) {
4826 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4827 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4828
4829 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4830 VirtualBaseSpec);
4831
4832 // C++ [base.class.init]p2:
4833 // Unless the mem-initializer-id names a nonstatic data member of the
4834 // constructor's class or a direct or virtual base of that class, the
4835 // mem-initializer is ill-formed.
4836 if (!DirectBaseSpec && !VirtualBaseSpec) {
4837 // If the class has any dependent bases, then it's possible that
4838 // one of those types will resolve to the same type as
4839 // BaseType. Therefore, just treat this as a dependent base
4840 // class initialization. FIXME: Should we try to check the
4841 // initialization anyway? It seems odd.
4842 if (ClassDecl->hasAnyDependentBases())
4843 Dependent = true;
4844 else
4845 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4846 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4847 << BaseTInfo->getTypeLoc().getSourceRange();
4848 }
4849 }
4850
4851 if (Dependent) {
4852 DiscardCleanupsInEvaluationContext();
4853
4854 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4855 /*IsVirtual=*/false,
4856 InitRange.getBegin(), Init,
4857 InitRange.getEnd(), EllipsisLoc);
4858 }
4859
4860 // C++ [base.class.init]p2:
4861 // If a mem-initializer-id is ambiguous because it designates both
4862 // a direct non-virtual base class and an inherited virtual base
4863 // class, the mem-initializer is ill-formed.
4864 if (DirectBaseSpec && VirtualBaseSpec)
4865 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4866 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4867
4868 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4869 if (!BaseSpec)
4870 BaseSpec = VirtualBaseSpec;
4871
4872 // Initialize the base.
4873 bool InitList = true;
4874 MultiExprArg Args = Init;
4875 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4876 InitList = false;
4877 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4878 }
4879
4880 InitializedEntity BaseEntity =
4881 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4882 InitializationKind Kind =
4883 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4884 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4885 RParenLoc: InitRange.getEnd());
4886 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4887 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4888 if (!BaseInit.isInvalid()) {
4889 // C++11 [class.base.init]p7:
4890 // The initialization of each base and member constitutes a
4891 // full-expression.
4892 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4893 /*DiscardedValue*/ false);
4894 }
4895
4896 if (BaseInit.isInvalid()) {
4897 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4898 SubExprs: Args, T: BaseType);
4899 if (BaseInit.isInvalid())
4900 return true;
4901 } else {
4902 // If we are in a dependent context, template instantiation will
4903 // perform this type-checking again. Just save the arguments that we
4904 // received in a ParenListExpr.
4905 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4906 // of the information that we have about the base
4907 // initializer. However, deconstructing the ASTs is a dicey process,
4908 // and this approach is far more likely to get the corner cases right.
4909 if (CurContext->isDependentContext())
4910 BaseInit = Init;
4911 }
4912
4913 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4914 BaseSpec->isVirtual(),
4915 InitRange.getBegin(),
4916 BaseInit.getAs<Expr>(),
4917 InitRange.getEnd(), EllipsisLoc);
4918}
4919
4920// Create a static_cast\<T&&>(expr).
4921static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4922 QualType TargetType =
4923 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4924 Loc: SourceLocation(), Entity: DeclarationName());
4925 SourceLocation ExprLoc = E->getBeginLoc();
4926 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4927 T: TargetType, Loc: ExprLoc);
4928
4929 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4930 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4931 Parens: E->getSourceRange()).get();
4932}
4933
4934/// ImplicitInitializerKind - How an implicit base or member initializer should
4935/// initialize its base or member.
4936enum ImplicitInitializerKind {
4937 IIK_Default,
4938 IIK_Copy,
4939 IIK_Move,
4940 IIK_Inherit
4941};
4942
4943static bool
4944BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
4945 ImplicitInitializerKind ImplicitInitKind,
4946 CXXBaseSpecifier *BaseSpec,
4947 bool IsInheritedVirtualBase,
4948 CXXCtorInitializer *&CXXBaseInit) {
4949 InitializedEntity InitEntity
4950 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
4951 IsInheritedVirtualBase);
4952
4953 ExprResult BaseInit;
4954
4955 switch (ImplicitInitKind) {
4956 case IIK_Inherit:
4957 case IIK_Default: {
4958 InitializationKind InitKind
4959 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
4960 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
4961 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
4962 break;
4963 }
4964
4965 case IIK_Move:
4966 case IIK_Copy: {
4967 bool Moving = ImplicitInitKind == IIK_Move;
4968 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
4969 QualType ParamType = Param->getType().getNonReferenceType();
4970
4971 Expr *CopyCtorArg =
4972 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
4973 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
4974 NameLoc: Constructor->getLocation(), T: ParamType,
4975 VK: VK_LValue, FoundD: nullptr);
4976
4977 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
4978
4979 // Cast to the base class to avoid ambiguities.
4980 QualType ArgTy =
4981 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
4982 Qs: ParamType.getQualifiers());
4983
4984 if (Moving) {
4985 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
4986 }
4987
4988 CXXCastPath BasePath;
4989 BasePath.push_back(Elt: BaseSpec);
4990 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
4991 CK: CK_UncheckedDerivedToBase,
4992 VK: Moving ? VK_XValue : VK_LValue,
4993 BasePath: &BasePath).get();
4994
4995 InitializationKind InitKind
4996 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
4997 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
4998 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
4999 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
5000 break;
5001 }
5002 }
5003
5004 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
5005 if (BaseInit.isInvalid())
5006 return true;
5007
5008 CXXBaseInit =
5009 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5010 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5011 Loc: SourceLocation()),
5012 BaseSpec->isVirtual(),
5013 SourceLocation(),
5014 BaseInit.getAs<Expr>(),
5015 SourceLocation(),
5016 SourceLocation());
5017
5018 return false;
5019}
5020
5021static bool RefersToRValueRef(Expr *MemRef) {
5022 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5023 return Referenced->getType()->isRValueReferenceType();
5024}
5025
5026static bool
5027BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5028 ImplicitInitializerKind ImplicitInitKind,
5029 FieldDecl *Field, IndirectFieldDecl *Indirect,
5030 CXXCtorInitializer *&CXXMemberInit) {
5031 if (Field->isInvalidDecl())
5032 return true;
5033
5034 SourceLocation Loc = Constructor->getLocation();
5035
5036 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5037 bool Moving = ImplicitInitKind == IIK_Move;
5038 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5039 QualType ParamType = Param->getType().getNonReferenceType();
5040
5041 // Suppress copying zero-width bitfields.
5042 if (Field->isZeroLengthBitField())
5043 return false;
5044
5045 Expr *MemberExprBase =
5046 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5047 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5048 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5049
5050 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5051
5052 if (Moving) {
5053 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5054 }
5055
5056 // Build a reference to this field within the parameter.
5057 CXXScopeSpec SS;
5058 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5059 Sema::LookupMemberName);
5060 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5061 : cast<ValueDecl>(Val: Field), AS: AS_public);
5062 MemberLookup.resolveKind();
5063 ExprResult CtorArg
5064 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5065 BaseType: ParamType, OpLoc: Loc,
5066 /*IsArrow=*/false,
5067 SS,
5068 /*TemplateKWLoc=*/SourceLocation(),
5069 /*FirstQualifierInScope=*/nullptr,
5070 R&: MemberLookup,
5071 /*TemplateArgs=*/nullptr,
5072 /*S*/nullptr);
5073 if (CtorArg.isInvalid())
5074 return true;
5075
5076 // C++11 [class.copy]p15:
5077 // - if a member m has rvalue reference type T&&, it is direct-initialized
5078 // with static_cast<T&&>(x.m);
5079 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5080 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5081 }
5082
5083 InitializedEntity Entity =
5084 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5085 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5086
5087 // Direct-initialize to use the copy constructor.
5088 InitializationKind InitKind =
5089 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5090
5091 Expr *CtorArgE = CtorArg.getAs<Expr>();
5092 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5093 ExprResult MemberInit =
5094 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5095 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5096 if (MemberInit.isInvalid())
5097 return true;
5098
5099 if (Indirect)
5100 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5101 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5102 else
5103 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5104 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5105 return false;
5106 }
5107
5108 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5109 "Unhandled implicit init kind!");
5110
5111 QualType FieldBaseElementType =
5112 SemaRef.Context.getBaseElementType(QT: Field->getType());
5113
5114 if (FieldBaseElementType->isRecordType()) {
5115 InitializedEntity InitEntity =
5116 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5117 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5118 InitializationKind InitKind =
5119 InitializationKind::CreateDefault(InitLoc: Loc);
5120
5121 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5122 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5123
5124 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5125 if (MemberInit.isInvalid())
5126 return true;
5127
5128 if (Indirect)
5129 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5130 Indirect, Loc,
5131 Loc,
5132 MemberInit.get(),
5133 Loc);
5134 else
5135 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5136 Field, Loc, Loc,
5137 MemberInit.get(),
5138 Loc);
5139 return false;
5140 }
5141
5142 if (!Field->getParent()->isUnion()) {
5143 if (FieldBaseElementType->isReferenceType()) {
5144 SemaRef.Diag(Loc: Constructor->getLocation(),
5145 DiagID: diag::err_uninitialized_member_in_ctor)
5146 << (int)Constructor->isImplicit()
5147 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5148 << Field->getDeclName();
5149 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5150 return true;
5151 }
5152
5153 if (FieldBaseElementType.isConstQualified()) {
5154 SemaRef.Diag(Loc: Constructor->getLocation(),
5155 DiagID: diag::err_uninitialized_member_in_ctor)
5156 << (int)Constructor->isImplicit()
5157 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5158 << Field->getDeclName();
5159 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5160 return true;
5161 }
5162 }
5163
5164 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5165 // ARC and Weak:
5166 // Default-initialize Objective-C pointers to NULL.
5167 CXXMemberInit
5168 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5169 Loc, Loc,
5170 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5171 Loc);
5172 return false;
5173 }
5174
5175 // Nothing to initialize.
5176 CXXMemberInit = nullptr;
5177 return false;
5178}
5179
5180namespace {
5181struct BaseAndFieldInfo {
5182 Sema &S;
5183 CXXConstructorDecl *Ctor;
5184 bool AnyErrorsInInits;
5185 ImplicitInitializerKind IIK;
5186 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5187 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5188 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5189
5190 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5191 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5192 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5193 if (Ctor->getInheritedConstructor())
5194 IIK = IIK_Inherit;
5195 else if (Generated && Ctor->isCopyConstructor())
5196 IIK = IIK_Copy;
5197 else if (Generated && Ctor->isMoveConstructor())
5198 IIK = IIK_Move;
5199 else
5200 IIK = IIK_Default;
5201 }
5202
5203 bool isImplicitCopyOrMove() const {
5204 switch (IIK) {
5205 case IIK_Copy:
5206 case IIK_Move:
5207 return true;
5208
5209 case IIK_Default:
5210 case IIK_Inherit:
5211 return false;
5212 }
5213
5214 llvm_unreachable("Invalid ImplicitInitializerKind!");
5215 }
5216
5217 bool addFieldInitializer(CXXCtorInitializer *Init) {
5218 AllToInit.push_back(Elt: Init);
5219
5220 // Check whether this initializer makes the field "used".
5221 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5222 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5223
5224 return false;
5225 }
5226
5227 bool isInactiveUnionMember(FieldDecl *Field) {
5228 RecordDecl *Record = Field->getParent();
5229 if (!Record->isUnion())
5230 return false;
5231
5232 if (FieldDecl *Active =
5233 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5234 return Active != Field->getCanonicalDecl();
5235
5236 // In an implicit copy or move constructor, ignore any in-class initializer.
5237 if (isImplicitCopyOrMove())
5238 return true;
5239
5240 // If there's no explicit initialization, the field is active only if it
5241 // has an in-class initializer...
5242 if (Field->hasInClassInitializer())
5243 return false;
5244 // ... or it's an anonymous struct or union whose class has an in-class
5245 // initializer.
5246 if (!Field->isAnonymousStructOrUnion())
5247 return true;
5248 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5249 return !FieldRD->hasInClassInitializer();
5250 }
5251
5252 /// Determine whether the given field is, or is within, a union member
5253 /// that is inactive (because there was an initializer given for a different
5254 /// member of the union, or because the union was not initialized at all).
5255 bool isWithinInactiveUnionMember(FieldDecl *Field,
5256 IndirectFieldDecl *Indirect) {
5257 if (!Indirect)
5258 return isInactiveUnionMember(Field);
5259
5260 for (auto *C : Indirect->chain()) {
5261 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5262 if (Field && isInactiveUnionMember(Field))
5263 return true;
5264 }
5265 return false;
5266 }
5267};
5268}
5269
5270/// Determine whether the given type is an incomplete or zero-lenfgth
5271/// array type.
5272static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5273 if (T->isIncompleteArrayType())
5274 return true;
5275
5276 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5277 if (ArrayT->isZeroSize())
5278 return true;
5279
5280 T = ArrayT->getElementType();
5281 }
5282
5283 return false;
5284}
5285
5286static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5287 FieldDecl *Field,
5288 IndirectFieldDecl *Indirect = nullptr) {
5289 if (Field->isInvalidDecl())
5290 return false;
5291
5292 // Overwhelmingly common case: we have a direct initializer for this field.
5293 if (CXXCtorInitializer *Init =
5294 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5295 return Info.addFieldInitializer(Init);
5296
5297 // C++11 [class.base.init]p8:
5298 // if the entity is a non-static data member that has a
5299 // brace-or-equal-initializer and either
5300 // -- the constructor's class is a union and no other variant member of that
5301 // union is designated by a mem-initializer-id or
5302 // -- the constructor's class is not a union, and, if the entity is a member
5303 // of an anonymous union, no other member of that union is designated by
5304 // a mem-initializer-id,
5305 // the entity is initialized as specified in [dcl.init].
5306 //
5307 // We also apply the same rules to handle anonymous structs within anonymous
5308 // unions.
5309 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5310 return false;
5311
5312 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5313 ExprResult DIE =
5314 SemaRef.BuildCXXDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5315 if (DIE.isInvalid())
5316 return true;
5317
5318 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5319 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5320
5321 CXXCtorInitializer *Init;
5322 if (Indirect)
5323 Init = new (SemaRef.Context)
5324 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5325 SourceLocation(), DIE.get(), SourceLocation());
5326 else
5327 Init = new (SemaRef.Context)
5328 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5329 SourceLocation(), DIE.get(), SourceLocation());
5330 return Info.addFieldInitializer(Init);
5331 }
5332
5333 // Don't initialize incomplete or zero-length arrays.
5334 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5335 return false;
5336
5337 // Don't try to build an implicit initializer if there were semantic
5338 // errors in any of the initializers (and therefore we might be
5339 // missing some that the user actually wrote).
5340 if (Info.AnyErrorsInInits)
5341 return false;
5342
5343 CXXCtorInitializer *Init = nullptr;
5344 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5345 Indirect, CXXMemberInit&: Init))
5346 return true;
5347
5348 if (!Init)
5349 return false;
5350
5351 return Info.addFieldInitializer(Init);
5352}
5353
5354bool
5355Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5356 CXXCtorInitializer *Initializer) {
5357 assert(Initializer->isDelegatingInitializer());
5358 Constructor->setNumCtorInitializers(1);
5359 CXXCtorInitializer **initializer =
5360 new (Context) CXXCtorInitializer*[1];
5361 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5362 Constructor->setCtorInitializers(initializer);
5363
5364 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5365 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5366 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5367 }
5368
5369 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5370
5371 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5372
5373 return false;
5374}
5375
5376static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5377 CXXRecordDecl *Class) {
5378 if (Class->isInvalidDecl())
5379 return nullptr;
5380 if (Class->hasIrrelevantDestructor())
5381 return nullptr;
5382
5383 // Dtor might still be missing, e.g because it's invalid.
5384 return S.LookupDestructor(Class);
5385}
5386
5387static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5388 FieldDecl *Field) {
5389 if (Field->isInvalidDecl())
5390 return;
5391
5392 // Don't destroy incomplete or zero-length arrays.
5393 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5394 return;
5395
5396 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5397
5398 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5399 if (!FieldClassDecl)
5400 return;
5401
5402 // The destructor for an implicit anonymous union member is never invoked.
5403 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5404 return;
5405
5406 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5407 if (!Dtor)
5408 return;
5409
5410 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5411 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5412 << Field->getDeclName() << FieldType);
5413
5414 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5415 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5416}
5417
5418static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5419 CXXRecordDecl *ClassDecl) {
5420 if (ClassDecl->isDependentContext())
5421 return;
5422
5423 // We only potentially invoke the destructors of potentially constructed
5424 // subobjects.
5425 bool VisitVirtualBases = !ClassDecl->isAbstract();
5426
5427 // If the destructor exists and has already been marked used in the MS ABI,
5428 // then virtual base destructors have already been checked and marked used.
5429 // Skip checking them again to avoid duplicate diagnostics.
5430 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5431 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5432 if (Dtor && Dtor->isUsed())
5433 VisitVirtualBases = false;
5434 }
5435
5436 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5437
5438 // Bases.
5439 for (const auto &Base : ClassDecl->bases()) {
5440 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5441 if (!BaseClassDecl)
5442 continue;
5443
5444 // Remember direct virtual bases.
5445 if (Base.isVirtual()) {
5446 if (!VisitVirtualBases)
5447 continue;
5448 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5449 }
5450
5451 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5452 if (!Dtor)
5453 continue;
5454
5455 // FIXME: caret should be on the start of the class name
5456 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5457 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5458 << Base.getType() << Base.getSourceRange(),
5459 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5460
5461 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5462 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5463 }
5464
5465 if (VisitVirtualBases)
5466 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5467 DirectVirtualBases: &DirectVirtualBases);
5468}
5469
5470bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5471 ArrayRef<CXXCtorInitializer *> Initializers) {
5472 if (Constructor->isDependentContext()) {
5473 // Just store the initializers as written, they will be checked during
5474 // instantiation.
5475 if (!Initializers.empty()) {
5476 Constructor->setNumCtorInitializers(Initializers.size());
5477 CXXCtorInitializer **baseOrMemberInitializers =
5478 new (Context) CXXCtorInitializer*[Initializers.size()];
5479 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5480 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5481 Constructor->setCtorInitializers(baseOrMemberInitializers);
5482 }
5483
5484 // Let template instantiation know whether we had errors.
5485 if (AnyErrors)
5486 Constructor->setInvalidDecl();
5487
5488 return false;
5489 }
5490
5491 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5492
5493 // We need to build the initializer AST according to order of construction
5494 // and not what user specified in the Initializers list.
5495 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5496 if (!ClassDecl)
5497 return true;
5498
5499 bool HadError = false;
5500
5501 for (CXXCtorInitializer *Member : Initializers) {
5502 if (Member->isBaseInitializer())
5503 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5504 Member;
5505 else {
5506 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5507
5508 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5509 for (auto *C : F->chain()) {
5510 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5511 if (FD && FD->getParent()->isUnion())
5512 Info.ActiveUnionMember.insert(KV: std::make_pair(
5513 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5514 }
5515 } else if (FieldDecl *FD = Member->getMember()) {
5516 if (FD->getParent()->isUnion())
5517 Info.ActiveUnionMember.insert(KV: std::make_pair(
5518 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5519 }
5520 }
5521 }
5522
5523 // Keep track of the direct virtual bases.
5524 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5525 for (auto &I : ClassDecl->bases()) {
5526 if (I.isVirtual())
5527 DirectVBases.insert(Ptr: &I);
5528 }
5529
5530 // Push virtual bases before others.
5531 for (auto &VBase : ClassDecl->vbases()) {
5532 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5533 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5534 // [class.base.init]p7, per DR257:
5535 // A mem-initializer where the mem-initializer-id names a virtual base
5536 // class is ignored during execution of a constructor of any class that
5537 // is not the most derived class.
5538 if (ClassDecl->isAbstract()) {
5539 // FIXME: Provide a fixit to remove the base specifier. This requires
5540 // tracking the location of the associated comma for a base specifier.
5541 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5542 << VBase.getType() << ClassDecl;
5543 DiagnoseAbstractType(RD: ClassDecl);
5544 }
5545
5546 Info.AllToInit.push_back(Elt: Value);
5547 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5548 // [class.base.init]p8, per DR257:
5549 // If a given [...] base class is not named by a mem-initializer-id
5550 // [...] and the entity is not a virtual base class of an abstract
5551 // class, then [...] the entity is default-initialized.
5552 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5553 CXXCtorInitializer *CXXBaseInit;
5554 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5555 BaseSpec: &VBase, IsInheritedVirtualBase,
5556 CXXBaseInit)) {
5557 HadError = true;
5558 continue;
5559 }
5560
5561 Info.AllToInit.push_back(Elt: CXXBaseInit);
5562 }
5563 }
5564
5565 // Non-virtual bases.
5566 for (auto &Base : ClassDecl->bases()) {
5567 // Virtuals are in the virtual base list and already constructed.
5568 if (Base.isVirtual())
5569 continue;
5570
5571 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5572 Val: Base.getType()->getAsCanonical<RecordType>())) {
5573 Info.AllToInit.push_back(Elt: Value);
5574 } else if (!AnyErrors) {
5575 CXXCtorInitializer *CXXBaseInit;
5576 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5577 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5578 CXXBaseInit)) {
5579 HadError = true;
5580 continue;
5581 }
5582
5583 Info.AllToInit.push_back(Elt: CXXBaseInit);
5584 }
5585 }
5586
5587 // Fields.
5588 for (auto *Mem : ClassDecl->decls()) {
5589 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5590 // C++ [class.bit]p2:
5591 // A declaration for a bit-field that omits the identifier declares an
5592 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5593 // initialized.
5594 if (F->isUnnamedBitField())
5595 continue;
5596
5597 // If we're not generating the implicit copy/move constructor, then we'll
5598 // handle anonymous struct/union fields based on their individual
5599 // indirect fields.
5600 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5601 continue;
5602
5603 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5604 HadError = true;
5605 continue;
5606 }
5607
5608 // Beyond this point, we only consider default initialization.
5609 if (Info.isImplicitCopyOrMove())
5610 continue;
5611
5612 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5613 if (F->getType()->isIncompleteArrayType()) {
5614 assert(ClassDecl->hasFlexibleArrayMember() &&
5615 "Incomplete array type is not valid");
5616 continue;
5617 }
5618
5619 // Initialize each field of an anonymous struct individually.
5620 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5621 HadError = true;
5622
5623 continue;
5624 }
5625 }
5626
5627 unsigned NumInitializers = Info.AllToInit.size();
5628 if (NumInitializers > 0) {
5629 Constructor->setNumCtorInitializers(NumInitializers);
5630 CXXCtorInitializer **baseOrMemberInitializers =
5631 new (Context) CXXCtorInitializer*[NumInitializers];
5632 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5633 n: NumInitializers * sizeof(CXXCtorInitializer*));
5634 Constructor->setCtorInitializers(baseOrMemberInitializers);
5635
5636 SourceLocation Location = Constructor->getLocation();
5637
5638 // Constructors implicitly reference the base and member
5639 // destructors.
5640
5641 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5642 FieldDecl *Field = Initializer->getAnyMember();
5643 if (!Field)
5644 continue;
5645
5646 // C++ [class.base.init]p12:
5647 // In a non-delegating constructor, the destructor for each
5648 // potentially constructed subobject of class type is potentially
5649 // invoked.
5650 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5651 }
5652
5653 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5654 }
5655
5656 return HadError;
5657}
5658
5659static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5660 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5661 const RecordDecl *RD = RT->getDecl();
5662 if (RD->isAnonymousStructOrUnion()) {
5663 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5664 PopulateKeysForFields(Field, IdealInits);
5665 return;
5666 }
5667 }
5668 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5669}
5670
5671static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5672 return Context.getCanonicalType(T: BaseType).getTypePtr();
5673}
5674
5675static const void *GetKeyForMember(ASTContext &Context,
5676 CXXCtorInitializer *Member) {
5677 if (!Member->isAnyMemberInitializer())
5678 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5679
5680 return Member->getAnyMember()->getCanonicalDecl();
5681}
5682
5683static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5684 const CXXCtorInitializer *Previous,
5685 const CXXCtorInitializer *Current) {
5686 if (Previous->isAnyMemberInitializer())
5687 Diag << 0 << Previous->getAnyMember();
5688 else
5689 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5690
5691 if (Current->isAnyMemberInitializer())
5692 Diag << 0 << Current->getAnyMember();
5693 else
5694 Diag << 1 << Current->getTypeSourceInfo()->getType();
5695}
5696
5697static void DiagnoseBaseOrMemInitializerOrder(
5698 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5699 ArrayRef<CXXCtorInitializer *> Inits) {
5700 if (Constructor->getDeclContext()->isDependentContext())
5701 return;
5702
5703 // Don't check initializers order unless the warning is enabled at the
5704 // location of at least one initializer.
5705 bool ShouldCheckOrder = false;
5706 for (const CXXCtorInitializer *Init : Inits) {
5707 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5708 Loc: Init->getSourceLocation())) {
5709 ShouldCheckOrder = true;
5710 break;
5711 }
5712 }
5713 if (!ShouldCheckOrder)
5714 return;
5715
5716 // Build the list of bases and members in the order that they'll
5717 // actually be initialized. The explicit initializers should be in
5718 // this same order but may be missing things.
5719 SmallVector<const void*, 32> IdealInitKeys;
5720
5721 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5722
5723 // 1. Virtual bases.
5724 for (const auto &VBase : ClassDecl->vbases())
5725 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5726
5727 // 2. Non-virtual bases.
5728 for (const auto &Base : ClassDecl->bases()) {
5729 if (Base.isVirtual())
5730 continue;
5731 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5732 }
5733
5734 // 3. Direct fields.
5735 for (auto *Field : ClassDecl->fields()) {
5736 if (Field->isUnnamedBitField())
5737 continue;
5738
5739 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5740 }
5741
5742 unsigned NumIdealInits = IdealInitKeys.size();
5743 unsigned IdealIndex = 0;
5744
5745 // Track initializers that are in an incorrect order for either a warning or
5746 // note if multiple ones occur.
5747 SmallVector<unsigned> WarnIndexes;
5748 // Correlates the index of an initializer in the init-list to the index of
5749 // the field/base in the class.
5750 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5751
5752 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5753 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5754
5755 // Scan forward to try to find this initializer in the idealized
5756 // initializers list.
5757 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5758 if (InitKey == IdealInitKeys[IdealIndex])
5759 break;
5760
5761 // If we didn't find this initializer, it must be because we
5762 // scanned past it on a previous iteration. That can only
5763 // happen if we're out of order; emit a warning.
5764 if (IdealIndex == NumIdealInits && InitIndex) {
5765 WarnIndexes.push_back(Elt: InitIndex);
5766
5767 // Move back to the initializer's location in the ideal list.
5768 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5769 if (InitKey == IdealInitKeys[IdealIndex])
5770 break;
5771
5772 assert(IdealIndex < NumIdealInits &&
5773 "initializer not found in initializer list");
5774 }
5775 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5776 }
5777
5778 if (WarnIndexes.empty())
5779 return;
5780
5781 // Sort based on the ideal order, first in the pair.
5782 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5783
5784 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5785 // emit the diagnostic before we can try adding notes.
5786 {
5787 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5788 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5789 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5790 : diag::warn_some_initializers_out_of_order);
5791
5792 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5793 if (CorrelatedInitOrder[I].second == I)
5794 continue;
5795 // Ideally we would be using InsertFromRange here, but clang doesn't
5796 // appear to handle InsertFromRange correctly when the source range is
5797 // modified by another fix-it.
5798 D << FixItHint::CreateReplacement(
5799 RemoveRange: Inits[I]->getSourceRange(),
5800 Code: Lexer::getSourceText(
5801 Range: CharSourceRange::getTokenRange(
5802 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5803 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5804 }
5805
5806 // If there is only 1 item out of order, the warning expects the name and
5807 // type of each being added to it.
5808 if (WarnIndexes.size() == 1) {
5809 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5810 Current: Inits[WarnIndexes.front()]);
5811 return;
5812 }
5813 }
5814 // More than 1 item to warn, create notes letting the user know which ones
5815 // are bad.
5816 for (unsigned WarnIndex : WarnIndexes) {
5817 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5818 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5819 DiagID: diag::note_initializer_out_of_order);
5820 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5821 D << PrevInit->getSourceRange();
5822 }
5823}
5824
5825namespace {
5826bool CheckRedundantInit(Sema &S,
5827 CXXCtorInitializer *Init,
5828 CXXCtorInitializer *&PrevInit) {
5829 if (!PrevInit) {
5830 PrevInit = Init;
5831 return false;
5832 }
5833
5834 if (FieldDecl *Field = Init->getAnyMember())
5835 S.Diag(Loc: Init->getSourceLocation(),
5836 DiagID: diag::err_multiple_mem_initialization)
5837 << Field->getDeclName()
5838 << Init->getSourceRange();
5839 else {
5840 const Type *BaseClass = Init->getBaseClass();
5841 assert(BaseClass && "neither field nor base");
5842 S.Diag(Loc: Init->getSourceLocation(),
5843 DiagID: diag::err_multiple_base_initialization)
5844 << QualType(BaseClass, 0)
5845 << Init->getSourceRange();
5846 }
5847 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5848 << 0 << PrevInit->getSourceRange();
5849
5850 return true;
5851}
5852
5853typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5854typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5855
5856bool CheckRedundantUnionInit(Sema &S,
5857 CXXCtorInitializer *Init,
5858 RedundantUnionMap &Unions) {
5859 FieldDecl *Field = Init->getAnyMember();
5860 RecordDecl *Parent = Field->getParent();
5861 NamedDecl *Child = Field;
5862
5863 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5864 if (Parent->isUnion()) {
5865 UnionEntry &En = Unions[Parent];
5866 if (En.first && En.first != Child) {
5867 S.Diag(Loc: Init->getSourceLocation(),
5868 DiagID: diag::err_multiple_mem_union_initialization)
5869 << Field->getDeclName()
5870 << Init->getSourceRange();
5871 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5872 << 0 << En.second->getSourceRange();
5873 return true;
5874 }
5875 if (!En.first) {
5876 En.first = Child;
5877 En.second = Init;
5878 }
5879 if (!Parent->isAnonymousStructOrUnion())
5880 return false;
5881 }
5882
5883 Child = Parent;
5884 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5885 }
5886
5887 return false;
5888}
5889} // namespace
5890
5891void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5892 SourceLocation ColonLoc,
5893 ArrayRef<CXXCtorInitializer*> MemInits,
5894 bool AnyErrors) {
5895 if (!ConstructorDecl)
5896 return;
5897
5898 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5899
5900 CXXConstructorDecl *Constructor
5901 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5902
5903 if (!Constructor) {
5904 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5905 return;
5906 }
5907
5908 // Mapping for the duplicate initializers check.
5909 // For member initializers, this is keyed with a FieldDecl*.
5910 // For base initializers, this is keyed with a Type*.
5911 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5912
5913 // Mapping for the inconsistent anonymous-union initializers check.
5914 RedundantUnionMap MemberUnions;
5915
5916 bool HadError = false;
5917 for (unsigned i = 0; i < MemInits.size(); i++) {
5918 CXXCtorInitializer *Init = MemInits[i];
5919
5920 // Set the source order index.
5921 Init->setSourceOrder(i);
5922
5923 if (Init->isAnyMemberInitializer()) {
5924 const void *Key = GetKeyForMember(Context, Member: Init);
5925 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5926 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5927 HadError = true;
5928 } else if (Init->isBaseInitializer()) {
5929 const void *Key = GetKeyForMember(Context, Member: Init);
5930 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5931 HadError = true;
5932 } else {
5933 assert(Init->isDelegatingInitializer());
5934 // This must be the only initializer
5935 if (MemInits.size() != 1) {
5936 Diag(Loc: Init->getSourceLocation(),
5937 DiagID: diag::err_delegating_initializer_alone)
5938 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5939 // We will treat this as being the only initializer.
5940 }
5941 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5942 // Return immediately as the initializer is set.
5943 return;
5944 }
5945 }
5946
5947 if (HadError)
5948 return;
5949
5950 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
5951
5952 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
5953
5954 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5955}
5956
5957void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
5958 CXXRecordDecl *ClassDecl) {
5959 // Ignore dependent contexts. Also ignore unions, since their members never
5960 // have destructors implicitly called.
5961 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
5962 return;
5963
5964 // FIXME: all the access-control diagnostics are positioned on the
5965 // field/base declaration. That's probably good; that said, the
5966 // user might reasonably want to know why the destructor is being
5967 // emitted, and we currently don't say.
5968
5969 // Non-static data members.
5970 for (auto *Field : ClassDecl->fields()) {
5971 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5972 }
5973
5974 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
5975}
5976
5977void Sema::MarkVirtualBaseDestructorsReferenced(
5978 SourceLocation Location, CXXRecordDecl *ClassDecl,
5979 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
5980 // Virtual bases.
5981 for (const auto &VBase : ClassDecl->vbases()) {
5982 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
5983 if (!BaseClassDecl)
5984 continue;
5985
5986 // Ignore already visited direct virtual bases.
5987 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
5988 continue;
5989
5990 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
5991 if (!Dtor)
5992 continue;
5993
5994 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
5995 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
5996 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
5997 << CT << VBase.getType(),
5998 objectType: CT) == AR_accessible) {
5999 CheckDerivedToBaseConversion(
6000 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
6001 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
6002 }
6003
6004 MarkFunctionReferenced(Loc: Location, Func: Dtor);
6005 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
6006 }
6007}
6008
6009void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
6010 if (!CDtorDecl)
6011 return;
6012
6013 if (CXXConstructorDecl *Constructor
6014 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6015 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6016 !ClassDecl || ClassDecl->isInvalidDecl()) {
6017 return;
6018 }
6019 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6020 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6021 }
6022}
6023
6024bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6025 if (!getLangOpts().CPlusPlus)
6026 return false;
6027
6028 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6029 if (!RD)
6030 return false;
6031
6032 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6033 // class template specialization here, but doing so breaks a lot of code.
6034
6035 // We can't answer whether something is abstract until it has a
6036 // definition. If it's currently being defined, we'll walk back
6037 // over all the declarations when we have a full definition.
6038 const CXXRecordDecl *Def = RD->getDefinition();
6039 if (!Def || Def->isBeingDefined())
6040 return false;
6041
6042 return RD->isAbstract();
6043}
6044
6045bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6046 TypeDiagnoser &Diagnoser) {
6047 if (!isAbstractType(Loc, T))
6048 return false;
6049
6050 T = Context.getBaseElementType(QT: T);
6051 Diagnoser.diagnose(S&: *this, Loc, T);
6052 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6053 return true;
6054}
6055
6056void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6057 // Check if we've already emitted the list of pure virtual functions
6058 // for this class.
6059 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6060 return;
6061
6062 // If the diagnostic is suppressed, don't emit the notes. We're only
6063 // going to emit them once, so try to attach them to a diagnostic we're
6064 // actually going to show.
6065 if (Diags.isLastDiagnosticIgnored())
6066 return;
6067
6068 CXXFinalOverriderMap FinalOverriders;
6069 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6070
6071 // Keep a set of seen pure methods so we won't diagnose the same method
6072 // more than once.
6073 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6074
6075 for (const auto &M : FinalOverriders) {
6076 for (const auto &SO : M.second) {
6077 // C++ [class.abstract]p4:
6078 // A class is abstract if it contains or inherits at least one
6079 // pure virtual function for which the final overrider is pure
6080 // virtual.
6081
6082 if (SO.second.size() != 1)
6083 continue;
6084 const CXXMethodDecl *Method = SO.second.front().Method;
6085
6086 if (!Method->isPureVirtual())
6087 continue;
6088
6089 if (!SeenPureMethods.insert(Ptr: Method).second)
6090 continue;
6091
6092 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6093 << Method->getDeclName() << RD->getDeclName();
6094 }
6095 }
6096
6097 if (!PureVirtualClassDiagSet)
6098 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6099 PureVirtualClassDiagSet->insert(Ptr: RD);
6100}
6101
6102namespace {
6103struct AbstractUsageInfo {
6104 Sema &S;
6105 CXXRecordDecl *Record;
6106 CanQualType AbstractType;
6107 bool Invalid;
6108
6109 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6110 : S(S), Record(Record),
6111 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6112
6113 void DiagnoseAbstractType() {
6114 if (Invalid) return;
6115 S.DiagnoseAbstractType(RD: Record);
6116 Invalid = true;
6117 }
6118
6119 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6120};
6121
6122struct CheckAbstractUsage {
6123 AbstractUsageInfo &Info;
6124 const NamedDecl *Ctx;
6125
6126 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6127 : Info(Info), Ctx(Ctx) {}
6128
6129 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6130 switch (TL.getTypeLocClass()) {
6131#define ABSTRACT_TYPELOC(CLASS, PARENT)
6132#define TYPELOC(CLASS, PARENT) \
6133 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6134#include "clang/AST/TypeLocNodes.def"
6135 }
6136 }
6137
6138 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6139 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6140 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6141 if (!TL.getParam(i: I))
6142 continue;
6143
6144 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6145 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6146 }
6147 }
6148
6149 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6150 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6151 }
6152
6153 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6154 // Visit the type parameters from a permissive context.
6155 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6156 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6157 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6158 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6159 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6160 // TODO: other template argument types?
6161 }
6162 }
6163
6164 // Visit pointee types from a permissive context.
6165#define CheckPolymorphic(Type) \
6166 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6167 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6168 }
6169 CheckPolymorphic(PointerTypeLoc)
6170 CheckPolymorphic(ReferenceTypeLoc)
6171 CheckPolymorphic(MemberPointerTypeLoc)
6172 CheckPolymorphic(BlockPointerTypeLoc)
6173 CheckPolymorphic(AtomicTypeLoc)
6174
6175 /// Handle all the types we haven't given a more specific
6176 /// implementation for above.
6177 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6178 // Every other kind of type that we haven't called out already
6179 // that has an inner type is either (1) sugar or (2) contains that
6180 // inner type in some way as a subobject.
6181 if (TypeLoc Next = TL.getNextTypeLoc())
6182 return Visit(TL: Next, Sel);
6183
6184 // If there's no inner type and we're in a permissive context,
6185 // don't diagnose.
6186 if (Sel == Sema::AbstractNone) return;
6187
6188 // Check whether the type matches the abstract type.
6189 QualType T = TL.getType();
6190 if (T->isArrayType()) {
6191 Sel = Sema::AbstractArrayType;
6192 T = Info.S.Context.getBaseElementType(QT: T);
6193 }
6194 CanQualType CT = T->getCanonicalTypeUnqualified();
6195 if (CT != Info.AbstractType) return;
6196
6197 // It matched; do some magic.
6198 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6199 if (Sel == Sema::AbstractArrayType) {
6200 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6201 << T << TL.getSourceRange();
6202 } else {
6203 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6204 << Sel << T << TL.getSourceRange();
6205 }
6206 Info.DiagnoseAbstractType();
6207 }
6208};
6209
6210void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6211 Sema::AbstractDiagSelID Sel) {
6212 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6213}
6214
6215}
6216
6217/// Check for invalid uses of an abstract type in a function declaration.
6218static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6219 FunctionDecl *FD) {
6220 // Only definitions are required to refer to complete and
6221 // non-abstract types.
6222 if (!FD->doesThisDeclarationHaveABody())
6223 return;
6224
6225 // For safety's sake, just ignore it if we don't have type source
6226 // information. This should never happen for non-implicit methods,
6227 // but...
6228 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6229 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6230}
6231
6232/// Check for invalid uses of an abstract type in a variable0 declaration.
6233static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6234 VarDecl *VD) {
6235 // No need to do the check on definitions, which require that
6236 // the type is complete.
6237 if (VD->isThisDeclarationADefinition())
6238 return;
6239
6240 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6241 Sel: Sema::AbstractVariableType);
6242}
6243
6244/// Check for invalid uses of an abstract type within a class definition.
6245static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6246 CXXRecordDecl *RD) {
6247 for (auto *D : RD->decls()) {
6248 if (D->isImplicit()) continue;
6249
6250 // Step through friends to the befriended declaration.
6251 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6252 D = FD->getFriendDecl();
6253 if (!D) continue;
6254 }
6255
6256 // Functions and function templates.
6257 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6258 CheckAbstractClassUsage(Info, FD);
6259 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6260 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6261
6262 // Fields and static variables.
6263 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6264 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6265 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6266 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6267 CheckAbstractClassUsage(Info, VD);
6268 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6269 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6270
6271 // Nested classes and class templates.
6272 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6273 CheckAbstractClassUsage(Info, RD);
6274 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6275 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6276 }
6277 }
6278}
6279
6280static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6281 Attr *ClassAttr = getDLLAttr(D: Class);
6282 if (!ClassAttr)
6283 return;
6284
6285 assert(ClassAttr->getKind() == attr::DLLExport);
6286
6287 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6288
6289 if (TSK == TSK_ExplicitInstantiationDeclaration)
6290 // Don't go any further if this is just an explicit instantiation
6291 // declaration.
6292 return;
6293
6294 // Add a context note to explain how we got to any diagnostics produced below.
6295 struct MarkingClassDllexported {
6296 Sema &S;
6297 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6298 SourceLocation AttrLoc)
6299 : S(S) {
6300 Sema::CodeSynthesisContext Ctx;
6301 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6302 Ctx.PointOfInstantiation = AttrLoc;
6303 Ctx.Entity = Class;
6304 S.pushCodeSynthesisContext(Ctx);
6305 }
6306 ~MarkingClassDllexported() {
6307 S.popCodeSynthesisContext();
6308 }
6309 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6310
6311 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6312 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6313
6314 for (Decl *Member : Class->decls()) {
6315 // Skip members that were not marked exported.
6316 if (!Member->hasAttr<DLLExportAttr>())
6317 continue;
6318
6319 // Defined static variables that are members of an exported base
6320 // class must be marked export too.
6321 auto *VD = dyn_cast<VarDecl>(Val: Member);
6322 if (VD && VD->getStorageClass() == SC_Static &&
6323 TSK == TSK_ImplicitInstantiation)
6324 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6325
6326 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6327 if (!MD)
6328 continue;
6329
6330 if (MD->isUserProvided()) {
6331 // Instantiate non-default class member functions ...
6332
6333 // .. except for certain kinds of template specializations.
6334 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6335 continue;
6336
6337 // If this is an MS ABI dllexport default constructor, instantiate any
6338 // default arguments.
6339 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6340 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6341 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6342 S.InstantiateDefaultCtorDefaultArgs(Ctor: CD);
6343 }
6344 }
6345
6346 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6347
6348 // The function will be passed to the consumer when its definition is
6349 // encountered.
6350 } else if (MD->isExplicitlyDefaulted()) {
6351 // Synthesize and instantiate explicitly defaulted methods.
6352 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6353
6354 if (TSK != TSK_ExplicitInstantiationDefinition) {
6355 // Except for explicit instantiation defs, we will not see the
6356 // definition again later, so pass it to the consumer now.
6357 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6358 }
6359 } else if (!MD->isTrivial() ||
6360 MD->isCopyAssignmentOperator() ||
6361 MD->isMoveAssignmentOperator()) {
6362 // Synthesize and instantiate non-trivial implicit methods, and the copy
6363 // and move assignment operators. The latter are exported even if they
6364 // are trivial, because the address of an operator can be taken and
6365 // should compare equal across libraries.
6366 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6367
6368 // There is no later point when we will see the definition of this
6369 // function, so pass it to the consumer now.
6370 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6371 }
6372 }
6373}
6374
6375static void checkForMultipleExportedDefaultConstructors(Sema &S,
6376 CXXRecordDecl *Class) {
6377 // Only the MS ABI has default constructor closures, so we don't need to do
6378 // this semantic checking anywhere else.
6379 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6380 return;
6381
6382 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6383 for (Decl *Member : Class->decls()) {
6384 // Look for exported default constructors.
6385 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6386 if (!CD || !CD->isDefaultConstructor())
6387 continue;
6388 auto *Attr = CD->getAttr<DLLExportAttr>();
6389 if (!Attr)
6390 continue;
6391
6392 // If the class is non-dependent, mark the default arguments as ODR-used so
6393 // that we can properly codegen the constructor closure.
6394 if (!Class->isDependentContext()) {
6395 for (ParmVarDecl *PD : CD->parameters()) {
6396 (void)S.CheckCXXDefaultArgExpr(CallLoc: Attr->getLocation(), FD: CD, Param: PD);
6397 S.DiscardCleanupsInEvaluationContext();
6398 }
6399 }
6400
6401 if (LastExportedDefaultCtor) {
6402 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6403 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6404 << Class;
6405 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6406 << CD->getDeclName();
6407 return;
6408 }
6409 LastExportedDefaultCtor = CD;
6410 }
6411}
6412
6413static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6414 CXXRecordDecl *Class) {
6415 bool ErrorReported = false;
6416 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6417 ClassTemplateDecl *TD) {
6418 if (ErrorReported)
6419 return;
6420 S.Diag(Loc: TD->getLocation(),
6421 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6422 << /*surface*/ 0 << TD;
6423 ErrorReported = true;
6424 };
6425
6426 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6427 if (!TD) {
6428 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6429 if (!SD) {
6430 S.Diag(Loc: Class->getLocation(),
6431 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6432 << /*surface*/ 0 << Class;
6433 S.Diag(Loc: Class->getLocation(),
6434 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6435 << Class;
6436 return;
6437 }
6438 TD = SD->getSpecializedTemplate();
6439 }
6440
6441 TemplateParameterList *Params = TD->getTemplateParameters();
6442 unsigned N = Params->size();
6443
6444 if (N != 2) {
6445 reportIllegalClassTemplate(S, TD);
6446 S.Diag(Loc: TD->getLocation(),
6447 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6448 << TD << 2;
6449 }
6450 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6451 reportIllegalClassTemplate(S, TD);
6452 S.Diag(Loc: TD->getLocation(),
6453 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6454 << TD << /*1st*/ 0 << /*type*/ 0;
6455 }
6456 if (N > 1) {
6457 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6458 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6459 reportIllegalClassTemplate(S, TD);
6460 S.Diag(Loc: TD->getLocation(),
6461 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6462 << TD << /*2nd*/ 1 << /*integer*/ 1;
6463 }
6464 }
6465}
6466
6467static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6468 CXXRecordDecl *Class) {
6469 bool ErrorReported = false;
6470 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6471 ClassTemplateDecl *TD) {
6472 if (ErrorReported)
6473 return;
6474 S.Diag(Loc: TD->getLocation(),
6475 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6476 << /*texture*/ 1 << TD;
6477 ErrorReported = true;
6478 };
6479
6480 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6481 if (!TD) {
6482 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6483 if (!SD) {
6484 S.Diag(Loc: Class->getLocation(),
6485 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6486 << /*texture*/ 1 << Class;
6487 S.Diag(Loc: Class->getLocation(),
6488 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6489 << Class;
6490 return;
6491 }
6492 TD = SD->getSpecializedTemplate();
6493 }
6494
6495 TemplateParameterList *Params = TD->getTemplateParameters();
6496 unsigned N = Params->size();
6497
6498 if (N != 3) {
6499 reportIllegalClassTemplate(S, TD);
6500 S.Diag(Loc: TD->getLocation(),
6501 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6502 << TD << 3;
6503 }
6504 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6505 reportIllegalClassTemplate(S, TD);
6506 S.Diag(Loc: TD->getLocation(),
6507 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6508 << TD << /*1st*/ 0 << /*type*/ 0;
6509 }
6510 if (N > 1) {
6511 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6512 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6513 reportIllegalClassTemplate(S, TD);
6514 S.Diag(Loc: TD->getLocation(),
6515 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6516 << TD << /*2nd*/ 1 << /*integer*/ 1;
6517 }
6518 }
6519 if (N > 2) {
6520 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6521 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6522 reportIllegalClassTemplate(S, TD);
6523 S.Diag(Loc: TD->getLocation(),
6524 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6525 << TD << /*3rd*/ 2 << /*integer*/ 1;
6526 }
6527 }
6528}
6529
6530void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6531 // Mark any compiler-generated routines with the implicit code_seg attribute.
6532 for (auto *Method : Class->methods()) {
6533 if (Method->isUserProvided())
6534 continue;
6535 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6536 Method->addAttr(A);
6537 }
6538}
6539
6540void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6541 Attr *ClassAttr = getDLLAttr(D: Class);
6542
6543 // MSVC inherits DLL attributes to partial class template specializations.
6544 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6545 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6546 if (Attr *TemplateAttr =
6547 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6548 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6549 A->setInherited(true);
6550 ClassAttr = A;
6551 }
6552 }
6553 }
6554
6555 if (!ClassAttr)
6556 return;
6557
6558 // MSVC allows imported or exported template classes that have UniqueExternal
6559 // linkage. This occurs when the template class has been instantiated with
6560 // a template parameter which itself has internal linkage.
6561 // We drop the attribute to avoid exporting or importing any members.
6562 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6563 Context.getTargetInfo().getTriple().isPS()) &&
6564 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6565 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6566 return;
6567 }
6568
6569 if (!Class->isExternallyVisible()) {
6570 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6571 << Class << ClassAttr;
6572 return;
6573 }
6574
6575 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6576 !ClassAttr->isInherited()) {
6577 // Diagnose dll attributes on members of class with dll attribute.
6578 for (Decl *Member : Class->decls()) {
6579 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6580 continue;
6581 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6582 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6583 continue;
6584
6585 Diag(Loc: MemberAttr->getLocation(),
6586 DiagID: diag::err_attribute_dll_member_of_dll_class)
6587 << MemberAttr << ClassAttr;
6588 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6589 Member->setInvalidDecl();
6590 }
6591 }
6592
6593 if (Class->getDescribedClassTemplate())
6594 // Don't inherit dll attribute until the template is instantiated.
6595 return;
6596
6597 // The class is either imported or exported.
6598 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6599
6600 // Check if this was a dllimport attribute propagated from a derived class to
6601 // a base class template specialization. We don't apply these attributes to
6602 // static data members.
6603 const bool PropagatedImport =
6604 !ClassExported &&
6605 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6606
6607 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6608
6609 // Ignore explicit dllexport on explicit class template instantiation
6610 // declarations, except in MinGW mode.
6611 if (ClassExported && !ClassAttr->isInherited() &&
6612 TSK == TSK_ExplicitInstantiationDeclaration &&
6613 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6614 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6615 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6616 Class->dropAttr<DLLExportAttr>();
6617 }
6618 return;
6619 }
6620
6621 // Force declaration of implicit members so they can inherit the attribute.
6622 ForceDeclarationOfImplicitMembers(Class);
6623
6624 // Inherited constructors are created lazily; force their creation now so the
6625 // loop below can propagate the DLL attribute to them.
6626 if (ClassExported && getLangOpts().DllExportInlines) {
6627 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6628 for (Decl *D : Class->decls())
6629 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6630 Shadows.push_back(Elt: S);
6631 for (ConstructorUsingShadowDecl *S : Shadows) {
6632 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6633 if (!BC || BC->isDeleted())
6634 continue;
6635 // Skip constructors whose requires clause is not satisfied.
6636 // Normally overload resolution filters these, but we are bypassing
6637 // it to eagerly create inherited constructors for dllexport.
6638 if (BC->getTrailingRequiresClause()) {
6639 ConstraintSatisfaction Satisfaction;
6640 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6641 !Satisfaction.IsSatisfied)
6642 continue;
6643 }
6644 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6645 }
6646 }
6647
6648 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6649 // seem to be true in practice?
6650
6651 for (Decl *Member : Class->decls()) {
6652 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6653 continue;
6654
6655 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6656 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6657
6658 // Only methods and static fields inherit the attributes.
6659 if (!VD && !MD)
6660 continue;
6661
6662 if (MD) {
6663 // Don't process deleted methods.
6664 if (MD->isDeleted())
6665 continue;
6666
6667 if (ClassExported && getLangOpts().DllExportInlines) {
6668 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6669 if (CD && CD->getInheritedConstructor()) {
6670 // Inherited constructors already had their base constructor's
6671 // constraints checked before creation via
6672 // findInheritingConstructor, so only ABI-compatibility checks
6673 // are needed here.
6674 //
6675 // Don't export inherited constructors whose parameters prevent
6676 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6677 // CodeGen) returns false, Clang inlines the constructor body
6678 // instead of emitting a forwarding thunk, producing code that
6679 // is not ABI-compatible with MSVC. Suppress the export and warn
6680 // so the user gets a linker error rather than a silent runtime
6681 // mismatch.
6682 if (CD->isVariadic()) {
6683 Diag(Loc: CD->getLocation(),
6684 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6685 << /*variadic=*/0;
6686 continue;
6687 }
6688 if (Context.getTargetInfo()
6689 .getCXXABI()
6690 .areArgsDestroyedLeftToRightInCallee()) {
6691 bool HasCalleeCleanupParam = false;
6692 for (const ParmVarDecl *P : CD->parameters())
6693 if (P->needsDestruction(Ctx: Context)) {
6694 HasCalleeCleanupParam = true;
6695 break;
6696 }
6697 if (HasCalleeCleanupParam) {
6698 Diag(Loc: CD->getLocation(),
6699 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6700 << /*callee-cleanup=*/1;
6701 continue;
6702 }
6703 }
6704 } else if (MD->getTrailingRequiresClause()) {
6705 // Don't export methods whose requires clause is not satisfied.
6706 // For class template specializations, member constraints may
6707 // depend on template arguments and an unsatisfied constraint
6708 // means the member should not be available in this
6709 // specialization.
6710 ConstraintSatisfaction Satisfaction;
6711 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6712 !Satisfaction.IsSatisfied)
6713 continue;
6714 }
6715 }
6716
6717 if (MD->isInlined()) {
6718 // MinGW does not import or export inline methods. But do it for
6719 // template instantiations and inherited constructors (which are
6720 // marked inline but must be exported to match MSVC behavior).
6721 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6722 TSK != TSK_ExplicitInstantiationDeclaration &&
6723 TSK != TSK_ExplicitInstantiationDefinition) {
6724 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6725 !CD || !CD->getInheritedConstructor())
6726 continue;
6727 }
6728
6729 // MSVC versions before 2015 don't export the move assignment operators
6730 // and move constructor, so don't attempt to import/export them if
6731 // we have a definition.
6732 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6733 if ((MD->isMoveAssignmentOperator() ||
6734 (Ctor && Ctor->isMoveConstructor())) &&
6735 getLangOpts().isCompatibleWithMSVC() &&
6736 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6737 continue;
6738
6739 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6740 // operator is exported anyway.
6741 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6742 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6743 continue;
6744 }
6745 }
6746
6747 // Don't apply dllimport attributes to static data members of class template
6748 // instantiations when the attribute is propagated from a derived class.
6749 if (VD && PropagatedImport)
6750 continue;
6751
6752 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6753 continue;
6754
6755 if (!getDLLAttr(D: Member)) {
6756 InheritableAttr *NewAttr = nullptr;
6757
6758 // Do not export/import inline function when -fno-dllexport-inlines is
6759 // passed. But add attribute for later local static var check.
6760 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6761 TSK != TSK_ExplicitInstantiationDeclaration &&
6762 TSK != TSK_ExplicitInstantiationDefinition) {
6763 if (ClassExported) {
6764 NewAttr = ::new (getASTContext())
6765 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6766 } else {
6767 NewAttr = ::new (getASTContext())
6768 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6769 }
6770 } else {
6771 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6772 }
6773
6774 NewAttr->setInherited(true);
6775 Member->addAttr(A: NewAttr);
6776
6777 if (MD) {
6778 // Propagate DLLAttr to friend re-declarations of MD that have already
6779 // been constructed.
6780 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6781 FD = FD->getPreviousDecl()) {
6782 if (FD->getFriendObjectKind() == Decl::FOK_None)
6783 continue;
6784 assert(!getDLLAttr(FD) &&
6785 "friend re-decl should not already have a DLLAttr");
6786 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6787 NewAttr->setInherited(true);
6788 FD->addAttr(A: NewAttr);
6789 }
6790 }
6791 }
6792 }
6793
6794 if (ClassExported)
6795 DelayedDllExportClasses.push_back(Elt: Class);
6796}
6797
6798void Sema::propagateDLLAttrToBaseClassTemplate(
6799 CXXRecordDecl *Class, Attr *ClassAttr,
6800 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6801 if (getDLLAttr(
6802 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6803 // If the base class template has a DLL attribute, don't try to change it.
6804 return;
6805 }
6806
6807 auto TSK = BaseTemplateSpec->getSpecializationKind();
6808 if (!getDLLAttr(D: BaseTemplateSpec) &&
6809 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6810 TSK == TSK_ImplicitInstantiation)) {
6811 // The template hasn't been instantiated yet (or it has, but only as an
6812 // explicit instantiation declaration or implicit instantiation, which means
6813 // we haven't codegenned any members yet), so propagate the attribute.
6814 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6815 NewAttr->setInherited(true);
6816 BaseTemplateSpec->addAttr(A: NewAttr);
6817
6818 // If this was an import, mark that we propagated it from a derived class to
6819 // a base class template specialization.
6820 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6821 ImportAttr->setPropagatedToBaseTemplate();
6822
6823 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6824 // needs to be run again to work see the new attribute. Otherwise this will
6825 // get run whenever the template is instantiated.
6826 if (TSK != TSK_Undeclared)
6827 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6828
6829 return;
6830 }
6831
6832 if (getDLLAttr(D: BaseTemplateSpec)) {
6833 // The template has already been specialized or instantiated with an
6834 // attribute, explicitly or through propagation. We should not try to change
6835 // it.
6836 return;
6837 }
6838
6839 // The template was previously instantiated or explicitly specialized without
6840 // a dll attribute, It's too late for us to add an attribute, so warn that
6841 // this is unsupported.
6842 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6843 << BaseTemplateSpec->isExplicitSpecialization();
6844 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6845 if (BaseTemplateSpec->isExplicitSpecialization()) {
6846 Diag(Loc: BaseTemplateSpec->getLocation(),
6847 DiagID: diag::note_template_class_explicit_specialization_was_here)
6848 << BaseTemplateSpec;
6849 } else {
6850 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6851 DiagID: diag::note_template_class_instantiation_was_here)
6852 << BaseTemplateSpec;
6853 }
6854}
6855
6856Sema::DefaultedFunctionKind
6857Sema::getDefaultedFunctionKind(const FunctionDecl *FD) {
6858 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD)) {
6859 if (const CXXConstructorDecl *Ctor = dyn_cast<CXXConstructorDecl>(Val: FD)) {
6860 if (Ctor->isDefaultConstructor())
6861 return CXXSpecialMemberKind::DefaultConstructor;
6862
6863 if (Ctor->isCopyConstructor())
6864 return CXXSpecialMemberKind::CopyConstructor;
6865
6866 if (Ctor->isMoveConstructor())
6867 return CXXSpecialMemberKind::MoveConstructor;
6868 }
6869
6870 if (MD->isCopyAssignmentOperator())
6871 return CXXSpecialMemberKind::CopyAssignment;
6872
6873 if (MD->isMoveAssignmentOperator())
6874 return CXXSpecialMemberKind::MoveAssignment;
6875
6876 if (isa<CXXDestructorDecl>(Val: FD))
6877 return CXXSpecialMemberKind::Destructor;
6878 }
6879
6880 switch (FD->getDeclName().getCXXOverloadedOperator()) {
6881 case OO_EqualEqual:
6882 return DefaultedComparisonKind::Equal;
6883
6884 case OO_ExclaimEqual:
6885 return DefaultedComparisonKind::NotEqual;
6886
6887 case OO_Spaceship:
6888 // No point allowing this if <=> doesn't exist in the current language mode.
6889 if (!getLangOpts().CPlusPlus20)
6890 break;
6891 return DefaultedComparisonKind::ThreeWay;
6892
6893 case OO_Less:
6894 case OO_LessEqual:
6895 case OO_Greater:
6896 case OO_GreaterEqual:
6897 // No point allowing this if <=> doesn't exist in the current language mode.
6898 if (!getLangOpts().CPlusPlus20)
6899 break;
6900 return DefaultedComparisonKind::Relational;
6901
6902 default:
6903 break;
6904 }
6905
6906 // Not defaultable.
6907 return DefaultedFunctionKind();
6908}
6909
6910static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6911 SourceLocation DefaultLoc) {
6912 Sema::DefaultedFunctionKind DFK = S.getDefaultedFunctionKind(FD);
6913 if (DFK.isComparison())
6914 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6915
6916 switch (DFK.asSpecialMember()) {
6917 case CXXSpecialMemberKind::DefaultConstructor:
6918 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6919 Constructor: cast<CXXConstructorDecl>(Val: FD));
6920 break;
6921 case CXXSpecialMemberKind::CopyConstructor:
6922 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6923 break;
6924 case CXXSpecialMemberKind::CopyAssignment:
6925 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6926 break;
6927 case CXXSpecialMemberKind::Destructor:
6928 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6929 break;
6930 case CXXSpecialMemberKind::MoveConstructor:
6931 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6932 break;
6933 case CXXSpecialMemberKind::MoveAssignment:
6934 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6935 break;
6936 case CXXSpecialMemberKind::Invalid:
6937 llvm_unreachable("Invalid special member.");
6938 }
6939}
6940
6941/// Determine whether a type is permitted to be passed or returned in
6942/// registers, per C++ [class.temporary]p3.
6943static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6944 TargetInfo::CallingConvKind CCK) {
6945 if (D->isDependentType() || D->isInvalidDecl())
6946 return false;
6947
6948 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6949 // The PS4 platform ABI follows the behavior of Clang 3.2.
6950 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6951 return !D->hasNonTrivialDestructorForCall() &&
6952 !D->hasNonTrivialCopyConstructorForCall();
6953
6954 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6955 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6956 bool DtorIsTrivialForCall = false;
6957
6958 // If a class has at least one eligible, trivial copy constructor, it
6959 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6960 //
6961 // Note: This permits classes with non-trivial copy or move ctors to be
6962 // passed in registers, so long as they *also* have a trivial copy ctor,
6963 // which is non-conforming.
6964 if (D->needsImplicitCopyConstructor()) {
6965 if (!D->defaultedCopyConstructorIsDeleted()) {
6966 if (D->hasTrivialCopyConstructor())
6967 CopyCtorIsTrivial = true;
6968 if (D->hasTrivialCopyConstructorForCall())
6969 CopyCtorIsTrivialForCall = true;
6970 }
6971 } else {
6972 for (const CXXConstructorDecl *CD : D->ctors()) {
6973 if (CD->isCopyConstructor() && !CD->isDeleted() &&
6974 !CD->isIneligibleOrNotSelected()) {
6975 if (CD->isTrivial())
6976 CopyCtorIsTrivial = true;
6977 if (CD->isTrivialForCall())
6978 CopyCtorIsTrivialForCall = true;
6979 }
6980 }
6981 }
6982
6983 if (D->needsImplicitDestructor()) {
6984 if (!D->defaultedDestructorIsDeleted() &&
6985 D->hasTrivialDestructorForCall())
6986 DtorIsTrivialForCall = true;
6987 } else if (const auto *DD = D->getDestructor()) {
6988 if (!DD->isDeleted() && DD->isTrivialForCall())
6989 DtorIsTrivialForCall = true;
6990 }
6991
6992 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
6993 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
6994 return true;
6995
6996 // If a class has a destructor, we'd really like to pass it indirectly
6997 // because it allows us to elide copies. Unfortunately, MSVC makes that
6998 // impossible for small types, which it will pass in a single register or
6999 // stack slot. Most objects with dtors are large-ish, so handle that early.
7000 // We can't call out all large objects as being indirect because there are
7001 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7002 // how we pass large POD types.
7003
7004 // Note: This permits small classes with nontrivial destructors to be
7005 // passed in registers, which is non-conforming.
7006 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7007 uint64_t TypeSize = isAArch64 ? 128 : 64;
7008
7009 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7010 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
7011 return true;
7012 return false;
7013 }
7014
7015 // Per C++ [class.temporary]p3, the relevant condition is:
7016 // each copy constructor, move constructor, and destructor of X is
7017 // either trivial or deleted, and X has at least one non-deleted copy
7018 // or move constructor
7019 bool HasNonDeletedCopyOrMove = false;
7020
7021 if (D->needsImplicitCopyConstructor() &&
7022 !D->defaultedCopyConstructorIsDeleted()) {
7023 if (!D->hasTrivialCopyConstructorForCall())
7024 return false;
7025 HasNonDeletedCopyOrMove = true;
7026 }
7027
7028 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7029 !D->defaultedMoveConstructorIsDeleted()) {
7030 if (!D->hasTrivialMoveConstructorForCall())
7031 return false;
7032 HasNonDeletedCopyOrMove = true;
7033 }
7034
7035 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7036 !D->hasTrivialDestructorForCall())
7037 return false;
7038
7039 for (const CXXMethodDecl *MD : D->methods()) {
7040 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7041 continue;
7042
7043 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7044 if (CD && CD->isCopyOrMoveConstructor())
7045 HasNonDeletedCopyOrMove = true;
7046 else if (!isa<CXXDestructorDecl>(Val: MD))
7047 continue;
7048
7049 if (!MD->isTrivialForCall())
7050 return false;
7051 }
7052
7053 return HasNonDeletedCopyOrMove;
7054}
7055
7056/// Report an error regarding overriding, along with any relevant
7057/// overridden methods.
7058///
7059/// \param DiagID the primary error to report.
7060/// \param MD the overriding method.
7061static bool
7062ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7063 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7064 bool IssuedDiagnostic = false;
7065 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7066 if (Report(O)) {
7067 if (!IssuedDiagnostic) {
7068 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7069 IssuedDiagnostic = true;
7070 }
7071 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7072 }
7073 }
7074 return IssuedDiagnostic;
7075}
7076
7077void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7078 if (!Record)
7079 return;
7080
7081 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7082 AbstractUsageInfo Info(*this, Record);
7083 CheckAbstractClassUsage(Info, RD: Record);
7084 }
7085
7086 // If this is not an aggregate type and has no user-declared constructor,
7087 // complain about any non-static data members of reference or const scalar
7088 // type, since they will never get initializers.
7089 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7090 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7091 !Record->isLambda()) {
7092 bool Complained = false;
7093 for (const auto *F : Record->fields()) {
7094 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7095 continue;
7096
7097 if (F->getType()->isReferenceType() ||
7098 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7099 if (!Complained) {
7100 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7101 << Record->getTagKind() << Record;
7102 Complained = true;
7103 }
7104
7105 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7106 << F->getType()->isReferenceType()
7107 << F->getDeclName();
7108 }
7109 }
7110 }
7111
7112 if (Record->getIdentifier()) {
7113 // C++ [class.mem]p13:
7114 // If T is the name of a class, then each of the following shall have a
7115 // name different from T:
7116 // - every member of every anonymous union that is a member of class T.
7117 //
7118 // C++ [class.mem]p14:
7119 // In addition, if class T has a user-declared constructor (12.1), every
7120 // non-static data member of class T shall have a name different from T.
7121 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7122 const NamedDecl *D = Element->getUnderlyingDecl();
7123 // Invalid IndirectFieldDecls have already been diagnosed with
7124 // err_anonymous_record_member_redecl in
7125 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7126 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7127 Record->hasUserDeclaredConstructor()) ||
7128 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7129 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7130 << D->getDeclName();
7131 break;
7132 }
7133 }
7134 }
7135
7136 // Warn if the class has virtual methods but non-virtual public destructor.
7137 if (Record->isPolymorphic() && !Record->isDependentType()) {
7138 CXXDestructorDecl *dtor = Record->getDestructor();
7139 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7140 !Record->hasAttr<FinalAttr>())
7141 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7142 DiagID: diag::warn_non_virtual_dtor)
7143 << Context.getCanonicalTagType(TD: Record);
7144 }
7145
7146 if (Record->isAbstract()) {
7147 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7148 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7149 << FA->isSpelledAsSealed();
7150 DiagnoseAbstractType(RD: Record);
7151 }
7152 }
7153
7154 // Warn if the class has a final destructor but is not itself marked final.
7155 if (!Record->hasAttr<FinalAttr>()) {
7156 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7157 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7158 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7159 << FA->isSpelledAsSealed()
7160 << FixItHint::CreateInsertion(
7161 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7162 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7163 Diag(Loc: Record->getLocation(),
7164 DiagID: diag::note_final_dtor_non_final_class_silence)
7165 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7166 }
7167 }
7168 }
7169
7170 // See if trivial_abi has to be dropped.
7171 if (Record->hasAttr<TrivialABIAttr>())
7172 checkIllFormedTrivialABIStruct(RD&: *Record);
7173
7174 // Set HasTrivialSpecialMemberForCall if the record has attribute
7175 // "trivial_abi".
7176 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7177
7178 if (HasTrivialABI)
7179 Record->setHasTrivialSpecialMemberForCall();
7180
7181 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7182 // We check these last because they can depend on the properties of the
7183 // primary comparison functions (==, <=>).
7184 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7185
7186 // Perform checks that can't be done until we know all the properties of a
7187 // member function (whether it's defaulted, deleted, virtual, overriding,
7188 // ...).
7189 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7190 // A static function cannot override anything.
7191 if (MD->getStorageClass() == SC_Static) {
7192 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7193 Report: [](const CXXMethodDecl *) { return true; }))
7194 return;
7195 }
7196
7197 // A deleted function cannot override a non-deleted function and vice
7198 // versa.
7199 if (ReportOverrides(S&: *this,
7200 DiagID: MD->isDeleted() ? diag::err_deleted_override
7201 : diag::err_non_deleted_override,
7202 MD, Report: [&](const CXXMethodDecl *V) {
7203 return MD->isDeleted() != V->isDeleted();
7204 })) {
7205 if (MD->isDefaulted() && MD->isDeleted())
7206 // Explain why this defaulted function was deleted.
7207 DiagnoseDeletedDefaultedFunction(FD: MD);
7208 return;
7209 }
7210
7211 // A consteval function cannot override a non-consteval function and vice
7212 // versa.
7213 if (ReportOverrides(S&: *this,
7214 DiagID: MD->isConsteval() ? diag::err_consteval_override
7215 : diag::err_non_consteval_override,
7216 MD, Report: [&](const CXXMethodDecl *V) {
7217 return MD->isConsteval() != V->isConsteval();
7218 })) {
7219 if (MD->isDefaulted() && MD->isDeleted())
7220 // Explain why this defaulted function was deleted.
7221 DiagnoseDeletedDefaultedFunction(FD: MD);
7222 return;
7223 }
7224 };
7225
7226 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7227 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7228 return false;
7229
7230 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
7231 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7232 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7233 DefaultedSecondaryComparisons.push_back(Elt: FD);
7234 return true;
7235 }
7236
7237 CheckExplicitlyDefaultedFunction(S, MD: FD);
7238 return false;
7239 };
7240
7241 if (!Record->isInvalidDecl() &&
7242 Record->hasAttr<VTablePointerAuthenticationAttr>())
7243 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7244
7245 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7246 // Check whether the explicitly-defaulted members are valid.
7247 bool Incomplete = CheckForDefaultedFunction(M);
7248
7249 // Skip the rest of the checks for a member of a dependent class.
7250 if (Record->isDependentType())
7251 return;
7252
7253 // For an explicitly defaulted or deleted special member, we defer
7254 // determining triviality until the class is complete. That time is now!
7255 CXXSpecialMemberKind CSM = getSpecialMember(MD: M);
7256 if (!M->isImplicit() && !M->isUserProvided()) {
7257 if (CSM != CXXSpecialMemberKind::Invalid) {
7258 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7259 // Inform the class that we've finished declaring this member.
7260 Record->finishedDefaultedOrDeletedMember(MD: M);
7261 M->setTrivialForCall(
7262 HasTrivialABI ||
7263 SpecialMemberIsTrivial(MD: M, CSM,
7264 TAH: TrivialABIHandling::ConsiderTrivialABI));
7265 Record->setTrivialForCallFlags(M);
7266 }
7267 }
7268
7269 // Set triviality for the purpose of calls if this is a user-provided
7270 // copy/move constructor or destructor.
7271 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7272 CSM == CXXSpecialMemberKind::MoveConstructor ||
7273 CSM == CXXSpecialMemberKind::Destructor) &&
7274 M->isUserProvided()) {
7275 M->setTrivialForCall(HasTrivialABI);
7276 Record->setTrivialForCallFlags(M);
7277 }
7278
7279 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7280 M->hasAttr<DLLExportAttr>()) {
7281 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7282 M->isTrivial() &&
7283 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7284 CSM == CXXSpecialMemberKind::CopyConstructor ||
7285 CSM == CXXSpecialMemberKind::Destructor))
7286 M->dropAttr<DLLExportAttr>();
7287
7288 if (M->hasAttr<DLLExportAttr>()) {
7289 // Define after any fields with in-class initializers have been parsed.
7290 DelayedDllExportMemberFunctions.push_back(Elt: M);
7291 }
7292 }
7293
7294 bool EffectivelyConstexprDestructor = true;
7295 // Avoid triggering vtable instantiation due to a dtor that is not
7296 // "effectively constexpr" for better compatibility.
7297 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7298 if (isa<CXXDestructorDecl>(Val: M)) {
7299 llvm::SmallDenseSet<QualType> Visited;
7300 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7301 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7302 return false;
7303 const CXXRecordDecl *RD =
7304 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7305 if (!RD || !RD->isCompleteDefinition())
7306 return true;
7307
7308 if (!RD->hasConstexprDestructor())
7309 return false;
7310
7311 for (const CXXBaseSpecifier &B : RD->bases())
7312 if (!Check(B.getType(), Check))
7313 return false;
7314 for (const FieldDecl *FD : RD->fields())
7315 if (!Check(FD->getType(), Check))
7316 return false;
7317 return true;
7318 };
7319 EffectivelyConstexprDestructor =
7320 Check(Context.getCanonicalTagType(TD: Record), Check);
7321 }
7322
7323 // Define defaulted constexpr virtual functions that override a base class
7324 // function right away.
7325 // FIXME: We can defer doing this until the vtable is marked as used.
7326 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7327 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7328 EffectivelyConstexprDestructor)
7329 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7330
7331 if (!Incomplete)
7332 CheckCompletedMemberFunction(M);
7333 };
7334
7335 // Check the destructor before any other member function. We need to
7336 // determine whether it's trivial in order to determine whether the claas
7337 // type is a literal type, which is a prerequisite for determining whether
7338 // other special member functions are valid and whether they're implicitly
7339 // 'constexpr'.
7340 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7341 CompleteMemberFunction(Dtor);
7342
7343 bool HasMethodWithOverrideControl = false,
7344 HasOverridingMethodWithoutOverrideControl = false;
7345 for (auto *D : Record->decls()) {
7346 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7347 // FIXME: We could do this check for dependent types with non-dependent
7348 // bases.
7349 if (!Record->isDependentType()) {
7350 // See if a method overloads virtual methods in a base
7351 // class without overriding any.
7352 if (!M->isStatic())
7353 DiagnoseHiddenVirtualMethods(MD: M);
7354
7355 if (M->hasAttr<OverrideAttr>()) {
7356 HasMethodWithOverrideControl = true;
7357 } else if (M->size_overridden_methods() > 0) {
7358 HasOverridingMethodWithoutOverrideControl = true;
7359 } else {
7360 // Warn on newly-declared virtual methods in `final` classes
7361 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7362 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7363 << M;
7364 }
7365 }
7366 }
7367
7368 if (!isa<CXXDestructorDecl>(Val: M))
7369 CompleteMemberFunction(M);
7370 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7371 CheckForDefaultedFunction(
7372 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7373 }
7374 }
7375
7376 if (HasOverridingMethodWithoutOverrideControl) {
7377 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7378 for (auto *M : Record->methods())
7379 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7380 }
7381
7382 // Check the defaulted secondary comparisons after any other member functions.
7383 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7384 CheckExplicitlyDefaultedFunction(S, MD: FD);
7385
7386 // If this is a member function, we deferred checking it until now.
7387 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7388 CheckCompletedMemberFunction(MD);
7389 }
7390
7391 // {ms,gcc}_struct is a request to change ABI rules to either follow
7392 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7393 // present, we do not layout classes following foreign ABI rules, but
7394 // instead enter a special "compatibility mode", which only changes
7395 // alignments of fundamental types and layout of bit fields.
7396 // Check whether this class uses any C++ features that are implemented
7397 // completely differently in the requested ABI, and if so, emit a
7398 // diagnostic. That diagnostic defaults to an error, but we allow
7399 // projects to map it down to a warning (or ignore it). It's a fairly
7400 // common practice among users of the ms_struct pragma to
7401 // mass-annotate headers, sweeping up a bunch of types that the
7402 // project doesn't really rely on MSVC-compatible layout for. We must
7403 // therefore support "ms_struct except for C++ stuff" as a secondary
7404 // ABI.
7405 // Don't emit this diagnostic if the feature was enabled as a
7406 // language option (as opposed to via a pragma or attribute), as
7407 // the option -mms-bitfields otherwise essentially makes it impossible
7408 // to build C++ code, unless this diagnostic is turned off.
7409 if (Context.getLangOpts().getLayoutCompatibility() ==
7410 LangOptions::LayoutCompatibilityKind::Default &&
7411 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7412 (Record->isPolymorphic() || Record->getNumBases())) {
7413 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7414 }
7415
7416 checkClassLevelDLLAttribute(Class: Record);
7417 checkClassLevelCodeSegAttribute(Class: Record);
7418
7419 bool ClangABICompat4 =
7420 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver4);
7421 TargetInfo::CallingConvKind CCK =
7422 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7423 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7424
7425 // Do not change ArgPassingRestrictions if it has already been set to
7426 // RecordArgPassingKind::CanNeverPassInRegs.
7427 if (Record->getArgPassingRestrictions() !=
7428 RecordArgPassingKind::CanNeverPassInRegs)
7429 Record->setArgPassingRestrictions(
7430 CanPass ? RecordArgPassingKind::CanPassInRegs
7431 : RecordArgPassingKind::CannotPassInRegs);
7432
7433 // If canPassInRegisters returns true despite the record having a non-trivial
7434 // destructor, the record is destructed in the callee. This happens only when
7435 // the record or one of its subobjects has a field annotated with trivial_abi
7436 // or a field qualified with ObjC __strong/__weak.
7437 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7438 Record->setParamDestroyedInCallee(true);
7439 else if (Record->hasNonTrivialDestructor())
7440 Record->setParamDestroyedInCallee(CanPass);
7441
7442 if (getLangOpts().ForceEmitVTables) {
7443 // If we want to emit all the vtables, we need to mark it as used. This
7444 // is especially required for cases like vtable assumption loads.
7445 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7446 }
7447
7448 if (getLangOpts().CUDA) {
7449 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7450 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7451 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7452 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7453 }
7454
7455 llvm::SmallDenseMap<OverloadedOperatorKind,
7456 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7457 TypeAwareDecls{{OO_New, {}},
7458 {OO_Array_New, {}},
7459 {OO_Delete, {}},
7460 {OO_Array_New, {}}};
7461 for (auto *D : Record->decls()) {
7462 const FunctionDecl *FnDecl = D->getAsFunction();
7463 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7464 continue;
7465 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7466 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7467 }
7468 auto CheckMismatchedTypeAwareAllocators =
7469 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7470 OverloadedOperatorKind DeleteKind) {
7471 auto &NewDecls = TypeAwareDecls[NewKind];
7472 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7473 if (NewDecls.empty() == DeleteDecls.empty())
7474 return;
7475 DeclarationName FoundOperator =
7476 Context.DeclarationNames.getCXXOperatorName(
7477 Op: NewDecls.empty() ? DeleteKind : NewKind);
7478 DeclarationName MissingOperator =
7479 Context.DeclarationNames.getCXXOperatorName(
7480 Op: NewDecls.empty() ? NewKind : DeleteKind);
7481 Diag(Loc: Record->getLocation(),
7482 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7483 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7484 << MissingOperator;
7485 for (auto MD : NewDecls)
7486 Diag(Loc: MD->getLocation(),
7487 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7488 << MD;
7489 for (auto MD : DeleteDecls)
7490 Diag(Loc: MD->getLocation(),
7491 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7492 << MD;
7493 };
7494 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7495 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7496}
7497
7498/// Look up the special member function that would be called by a special
7499/// member function for a subobject of class type.
7500///
7501/// \param Class The class type of the subobject.
7502/// \param CSM The kind of special member function.
7503/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7504/// \param ConstRHS True if this is a copy operation with a const object
7505/// on its RHS, that is, if the argument to the outer special member
7506/// function is 'const' and this is not a field marked 'mutable'.
7507static Sema::SpecialMemberOverloadResult
7508lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7509 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7510 bool ConstRHS) {
7511 unsigned LHSQuals = 0;
7512 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7513 CSM == CXXSpecialMemberKind::MoveAssignment)
7514 LHSQuals = FieldQuals;
7515
7516 unsigned RHSQuals = FieldQuals;
7517 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7518 CSM == CXXSpecialMemberKind::Destructor)
7519 RHSQuals = 0;
7520 else if (ConstRHS)
7521 RHSQuals |= Qualifiers::Const;
7522
7523 return S.LookupSpecialMember(D: Class, SM: CSM,
7524 ConstArg: RHSQuals & Qualifiers::Const,
7525 VolatileArg: RHSQuals & Qualifiers::Volatile,
7526 RValueThis: false,
7527 ConstThis: LHSQuals & Qualifiers::Const,
7528 VolatileThis: LHSQuals & Qualifiers::Volatile);
7529}
7530
7531class Sema::InheritedConstructorInfo {
7532 Sema &S;
7533 SourceLocation UseLoc;
7534
7535 /// A mapping from the base classes through which the constructor was
7536 /// inherited to the using shadow declaration in that base class (or a null
7537 /// pointer if the constructor was declared in that base class).
7538 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7539 InheritedFromBases;
7540
7541public:
7542 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7543 ConstructorUsingShadowDecl *Shadow)
7544 : S(S), UseLoc(UseLoc) {
7545 bool DiagnosedMultipleConstructedBases = false;
7546 CXXRecordDecl *ConstructedBase = nullptr;
7547 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7548
7549 // Find the set of such base class subobjects and check that there's a
7550 // unique constructed subobject.
7551 for (auto *D : Shadow->redecls()) {
7552 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7553 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7554 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7555
7556 InheritedFromBases.insert(
7557 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7558 y: DShadow->getNominatedBaseClassShadowDecl()));
7559 if (DShadow->constructsVirtualBase())
7560 InheritedFromBases.insert(
7561 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7562 y: DShadow->getConstructedBaseClassShadowDecl()));
7563 else
7564 assert(DNominatedBase == DConstructedBase);
7565
7566 // [class.inhctor.init]p2:
7567 // If the constructor was inherited from multiple base class subobjects
7568 // of type B, the program is ill-formed.
7569 if (!ConstructedBase) {
7570 ConstructedBase = DConstructedBase;
7571 ConstructedBaseIntroducer = D->getIntroducer();
7572 } else if (ConstructedBase != DConstructedBase &&
7573 !Shadow->isInvalidDecl()) {
7574 if (!DiagnosedMultipleConstructedBases) {
7575 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7576 << Shadow->getTargetDecl();
7577 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7578 DiagID: diag::note_ambiguous_inherited_constructor_using)
7579 << ConstructedBase;
7580 DiagnosedMultipleConstructedBases = true;
7581 }
7582 S.Diag(Loc: D->getIntroducer()->getLocation(),
7583 DiagID: diag::note_ambiguous_inherited_constructor_using)
7584 << DConstructedBase;
7585 }
7586 }
7587
7588 if (DiagnosedMultipleConstructedBases)
7589 Shadow->setInvalidDecl();
7590 }
7591
7592 /// Find the constructor to use for inherited construction of a base class,
7593 /// and whether that base class constructor inherits the constructor from a
7594 /// virtual base class (in which case it won't actually invoke it).
7595 std::pair<CXXConstructorDecl *, bool>
7596 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7597 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7598 if (It == InheritedFromBases.end())
7599 return std::make_pair(x: nullptr, y: false);
7600
7601 // This is an intermediary class.
7602 if (It->second)
7603 return std::make_pair(
7604 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7605 y: It->second->constructsVirtualBase());
7606
7607 // This is the base class from which the constructor was inherited.
7608 return std::make_pair(x&: Ctor, y: false);
7609 }
7610};
7611
7612/// Is the special member function which would be selected to perform the
7613/// specified operation on the specified class type a constexpr constructor?
7614static bool specialMemberIsConstexpr(
7615 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7616 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7617 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7618 // Suppress duplicate constraint checking here, in case a constraint check
7619 // caused us to decide to do this. Any truely recursive checks will get
7620 // caught during these checks anyway.
7621 Sema::SatisfactionStackResetRAII SSRAII{S};
7622
7623 // If we're inheriting a constructor, see if we need to call it for this base
7624 // class.
7625 if (InheritedCtor) {
7626 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7627 auto BaseCtor =
7628 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7629 if (BaseCtor)
7630 return BaseCtor->isConstexpr();
7631 }
7632
7633 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7634 return ClassDecl->hasConstexprDefaultConstructor();
7635 if (CSM == CXXSpecialMemberKind::Destructor)
7636 return ClassDecl->hasConstexprDestructor();
7637
7638 Sema::SpecialMemberOverloadResult SMOR =
7639 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7640 if (!SMOR.getMethod())
7641 // A constructor we wouldn't select can't be "involved in initializing"
7642 // anything.
7643 return true;
7644 return SMOR.getMethod()->isConstexpr();
7645}
7646
7647/// Determine whether the specified special member function would be constexpr
7648/// if it were implicitly defined.
7649static bool defaultedSpecialMemberIsConstexpr(
7650 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7651 CXXConstructorDecl *InheritedCtor = nullptr,
7652 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7653 if (!S.getLangOpts().CPlusPlus11)
7654 return false;
7655
7656 // C++11 [dcl.constexpr]p4:
7657 // In the definition of a constexpr constructor [...]
7658 bool Ctor = true;
7659 switch (CSM) {
7660 case CXXSpecialMemberKind::DefaultConstructor:
7661 if (Inherited)
7662 break;
7663 // Since default constructor lookup is essentially trivial (and cannot
7664 // involve, for instance, template instantiation), we compute whether a
7665 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7666 //
7667 // This is important for performance; we need to know whether the default
7668 // constructor is constexpr to determine whether the type is a literal type.
7669 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7670
7671 case CXXSpecialMemberKind::CopyConstructor:
7672 case CXXSpecialMemberKind::MoveConstructor:
7673 // For copy or move constructors, we need to perform overload resolution.
7674 break;
7675
7676 case CXXSpecialMemberKind::CopyAssignment:
7677 case CXXSpecialMemberKind::MoveAssignment:
7678 if (!S.getLangOpts().CPlusPlus14)
7679 return false;
7680 // In C++1y, we need to perform overload resolution.
7681 Ctor = false;
7682 break;
7683
7684 case CXXSpecialMemberKind::Destructor:
7685 return ClassDecl->defaultedDestructorIsConstexpr();
7686
7687 case CXXSpecialMemberKind::Invalid:
7688 return false;
7689 }
7690
7691 // -- if the class is a non-empty union, or for each non-empty anonymous
7692 // union member of a non-union class, exactly one non-static data member
7693 // shall be initialized; [DR1359]
7694 //
7695 // If we squint, this is guaranteed, since exactly one non-static data member
7696 // will be initialized (if the constructor isn't deleted), we just don't know
7697 // which one.
7698 if (Ctor && ClassDecl->isUnion())
7699 return CSM == CXXSpecialMemberKind::DefaultConstructor
7700 ? ClassDecl->hasInClassInitializer() ||
7701 !ClassDecl->hasVariantMembers()
7702 : true;
7703
7704 // -- the class shall not have any virtual base classes;
7705 if (Ctor && ClassDecl->getNumVBases())
7706 return false;
7707
7708 // C++1y [class.copy]p26:
7709 // -- [the class] is a literal type, and
7710 if (!Ctor && !ClassDecl->isLiteral() && !S.getLangOpts().CPlusPlus23)
7711 return false;
7712
7713 // -- every constructor involved in initializing [...] base class
7714 // sub-objects shall be a constexpr constructor;
7715 // -- the assignment operator selected to copy/move each direct base
7716 // class is a constexpr function, and
7717 if (!S.getLangOpts().CPlusPlus23) {
7718 for (const auto &B : ClassDecl->bases()) {
7719 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7720 if (!BaseClassDecl)
7721 continue;
7722 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7723 InheritedCtor, Inherited))
7724 return false;
7725 }
7726 }
7727
7728 // -- every constructor involved in initializing non-static data members
7729 // [...] shall be a constexpr constructor;
7730 // -- every non-static data member and base class sub-object shall be
7731 // initialized
7732 // -- for each non-static data member of X that is of class type (or array
7733 // thereof), the assignment operator selected to copy/move that member is
7734 // a constexpr function
7735 if (!S.getLangOpts().CPlusPlus23) {
7736 for (const auto *F : ClassDecl->fields()) {
7737 if (F->isInvalidDecl())
7738 continue;
7739 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7740 F->hasInClassInitializer())
7741 continue;
7742 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7743 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7744 auto *FieldRecDecl =
7745 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7746 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7747 Quals: BaseType.getCVRQualifiers(),
7748 ConstRHS: ConstArg && !F->isMutable()))
7749 return false;
7750 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7751 return false;
7752 }
7753 }
7754 }
7755
7756 // All OK, it's constexpr!
7757 return true;
7758}
7759
7760namespace {
7761/// RAII object to register a defaulted function as having its exception
7762/// specification computed.
7763struct ComputingExceptionSpec {
7764 Sema &S;
7765
7766 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7767 : S(S) {
7768 Sema::CodeSynthesisContext Ctx;
7769 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7770 Ctx.PointOfInstantiation = Loc;
7771 Ctx.Entity = FD;
7772 S.pushCodeSynthesisContext(Ctx);
7773 }
7774 ~ComputingExceptionSpec() {
7775 S.popCodeSynthesisContext();
7776 }
7777};
7778}
7779
7780static Sema::ImplicitExceptionSpecification
7781ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7782 CXXMethodDecl *MD,
7783 CXXSpecialMemberKind CSM,
7784 Sema::InheritedConstructorInfo *ICI);
7785
7786static Sema::ImplicitExceptionSpecification
7787ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7788 FunctionDecl *FD,
7789 Sema::DefaultedComparisonKind DCK);
7790
7791static Sema::ImplicitExceptionSpecification
7792computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7793 auto DFK = S.getDefaultedFunctionKind(FD);
7794 if (DFK.isSpecialMember())
7795 return ComputeDefaultedSpecialMemberExceptionSpec(
7796 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7797 if (DFK.isComparison())
7798 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7799 DCK: DFK.asComparison());
7800
7801 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7802 assert(CD->getInheritedConstructor() &&
7803 "only defaulted functions and inherited constructors have implicit "
7804 "exception specs");
7805 Sema::InheritedConstructorInfo ICI(
7806 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7807 return ComputeDefaultedSpecialMemberExceptionSpec(
7808 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7809}
7810
7811static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7812 CXXMethodDecl *MD) {
7813 FunctionProtoType::ExtProtoInfo EPI;
7814
7815 // Build an exception specification pointing back at this member.
7816 EPI.ExceptionSpec.Type = EST_Unevaluated;
7817 EPI.ExceptionSpec.SourceDecl = MD;
7818
7819 // Set the calling convention to the default for C++ instance methods.
7820 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7821 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7822 /*IsCXXMethod=*/true));
7823 return EPI;
7824}
7825
7826void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7827 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7828 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7829 return;
7830
7831 // Evaluate the exception specification.
7832 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7833 auto ESI = IES.getExceptionSpec();
7834
7835 // Update the type of the special member to use it.
7836 UpdateExceptionSpec(FD, ESI);
7837}
7838
7839void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7840 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7841
7842 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
7843 if (!DefKind) {
7844 assert(FD->getDeclContext()->isDependentContext());
7845 return;
7846 }
7847
7848 if (DefKind.isComparison()) {
7849 auto PT = FD->getParamDecl(i: 0)->getType();
7850 if (const CXXRecordDecl *RD =
7851 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7852 for (FieldDecl *Field : RD->fields()) {
7853 UnusedPrivateFields.remove(X: Field);
7854 }
7855 }
7856 }
7857
7858 if (DefKind.isSpecialMember()
7859 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7860 CSM: DefKind.asSpecialMember(),
7861 DefaultLoc: FD->getDefaultLoc())
7862 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7863 FD->setInvalidDecl();
7864}
7865
7866bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7867 CXXSpecialMemberKind CSM,
7868 SourceLocation DefaultLoc) {
7869 CXXRecordDecl *RD = MD->getParent();
7870
7871 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7872 "not an explicitly-defaulted special member");
7873
7874 // Defer all checking for special members of a dependent type.
7875 if (RD->isDependentType())
7876 return false;
7877
7878 // Whether this was the first-declared instance of the constructor.
7879 // This affects whether we implicitly add an exception spec and constexpr.
7880 bool First = MD == MD->getCanonicalDecl();
7881
7882 bool HadError = false;
7883
7884 // C++11 [dcl.fct.def.default]p1:
7885 // A function that is explicitly defaulted shall
7886 // -- be a special member function [...] (checked elsewhere),
7887 // -- have the same type (except for ref-qualifiers, and except that a
7888 // copy operation can take a non-const reference) as an implicit
7889 // declaration, and
7890 // -- not have default arguments.
7891 // C++2a changes the second bullet to instead delete the function if it's
7892 // defaulted on its first declaration, unless it's "an assignment operator,
7893 // and its return type differs or its parameter type is not a reference".
7894 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7895 bool ShouldDeleteForTypeMismatch = false;
7896 unsigned ExpectedParams = 1;
7897 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7898 CSM == CXXSpecialMemberKind::Destructor)
7899 ExpectedParams = 0;
7900 if (MD->getNumExplicitParams() != ExpectedParams) {
7901 // This checks for default arguments: a copy or move constructor with a
7902 // default argument is classified as a default constructor, and assignment
7903 // operations and destructors can't have default arguments.
7904 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7905 << CSM << MD->getSourceRange();
7906 HadError = true;
7907 } else if (MD->isVariadic()) {
7908 if (DeleteOnTypeMismatch)
7909 ShouldDeleteForTypeMismatch = true;
7910 else {
7911 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7912 << CSM << MD->getSourceRange();
7913 HadError = true;
7914 }
7915 }
7916
7917 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7918
7919 bool CanHaveConstParam = false;
7920 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7921 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7922 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7923 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7924
7925 QualType ReturnType = Context.VoidTy;
7926 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7927 CSM == CXXSpecialMemberKind::MoveAssignment) {
7928 // Check for return type matching.
7929 ReturnType = Type->getReturnType();
7930 QualType ThisType = MD->getFunctionObjectParameterType();
7931
7932 QualType DeclType =
7933 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7934 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7935 DeclType = Context.getAddrSpaceQualType(
7936 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7937 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7938
7939 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7940 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7941 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7942 << ExpectedReturnType;
7943 HadError = true;
7944 }
7945
7946 // A defaulted special member cannot have cv-qualifiers.
7947 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7948 if (DeleteOnTypeMismatch)
7949 ShouldDeleteForTypeMismatch = true;
7950 else {
7951 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7952 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7953 << getLangOpts().CPlusPlus14;
7954 HadError = true;
7955 }
7956 }
7957 // [C++23][dcl.fct.def.default]/p2.2
7958 // if F2 has an implicit object parameter of type “reference to C”,
7959 // F1 may be an explicit object member function whose explicit object
7960 // parameter is of (possibly different) type “reference to C”,
7961 // in which case the type of F1 would differ from the type of F2
7962 // in that the type of F1 has an additional parameter;
7963 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7964 ? MD->getParamDecl(i: 0)->getType()
7965 : QualType();
7966 if (!ExplicitObjectParameter.isNull() &&
7967 (!ExplicitObjectParameter->isReferenceType() ||
7968 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
7969 T2: Context.getCanonicalTagType(TD: RD)))) {
7970 if (DeleteOnTypeMismatch)
7971 ShouldDeleteForTypeMismatch = true;
7972 else {
7973 Diag(Loc: MD->getLocation(),
7974 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
7975 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
7976 << MD->getSourceRange();
7977 HadError = true;
7978 }
7979 }
7980 }
7981
7982 // Check for parameter type matching.
7983 QualType ArgType =
7984 ExpectedParams
7985 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
7986 : QualType();
7987 bool HasConstParam = false;
7988 if (ExpectedParams && ArgType->isReferenceType()) {
7989 // Argument must be reference to possibly-const T.
7990 QualType ReferentType = ArgType->getPointeeType();
7991 HasConstParam = ReferentType.isConstQualified();
7992
7993 if (ReferentType.isVolatileQualified()) {
7994 if (DeleteOnTypeMismatch)
7995 ShouldDeleteForTypeMismatch = true;
7996 else {
7997 Diag(Loc: MD->getLocation(),
7998 DiagID: diag::err_defaulted_special_member_volatile_param)
7999 << CSM;
8000 HadError = true;
8001 }
8002 }
8003
8004 if (HasConstParam && !CanHaveConstParam) {
8005 if (DeleteOnTypeMismatch)
8006 ShouldDeleteForTypeMismatch = true;
8007 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8008 CSM == CXXSpecialMemberKind::CopyAssignment) {
8009 Diag(Loc: MD->getLocation(),
8010 DiagID: diag::err_defaulted_special_member_copy_const_param)
8011 << (CSM == CXXSpecialMemberKind::CopyAssignment);
8012 // FIXME: Explain why this special member can't be const.
8013 HadError = true;
8014 } else {
8015 Diag(Loc: MD->getLocation(),
8016 DiagID: diag::err_defaulted_special_member_move_const_param)
8017 << (CSM == CXXSpecialMemberKind::MoveAssignment);
8018 HadError = true;
8019 }
8020 }
8021 } else if (ExpectedParams) {
8022 // A copy assignment operator can take its argument by value, but a
8023 // defaulted one cannot.
8024 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
8025 "unexpected non-ref argument");
8026 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
8027 HadError = true;
8028 }
8029
8030 // C++11 [dcl.fct.def.default]p2:
8031 // An explicitly-defaulted function may be declared constexpr only if it
8032 // would have been implicitly declared as constexpr,
8033 // Do not apply this rule to members of class templates, since core issue 1358
8034 // makes such functions always instantiate to constexpr functions. For
8035 // functions which cannot be constexpr (for non-constructors in C++11 and for
8036 // destructors in C++14 and C++17), this is checked elsewhere.
8037 //
8038 // FIXME: This should not apply if the member is deleted.
8039 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8040 ConstArg: HasConstParam);
8041
8042 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8043 // If the instantiated template specialization of a constexpr function
8044 // template or member function of a class template would fail to satisfy
8045 // the requirements for a constexpr function or constexpr constructor, that
8046 // specialization is still a constexpr function or constexpr constructor,
8047 // even though a call to such a function cannot appear in a constant
8048 // expression.
8049 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8050 Constexpr = true;
8051
8052 if ((getLangOpts().CPlusPlus20 ||
8053 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8054 : isa<CXXConstructorDecl>(Val: MD))) &&
8055 MD->isConstexpr() && !Constexpr &&
8056 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8057 if (!MD->isConsteval() && RD->getNumVBases()) {
8058 Diag(Loc: MD->getBeginLoc(),
8059 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8060 << CSM;
8061 for (const auto &I : RD->vbases())
8062 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8063 } else {
8064 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8065 << CSM << MD->isConsteval();
8066 }
8067 HadError = true;
8068 // FIXME: Explain why the special member can't be constexpr.
8069 }
8070
8071 if (First) {
8072 // C++2a [dcl.fct.def.default]p3:
8073 // If a function is explicitly defaulted on its first declaration, it is
8074 // implicitly considered to be constexpr if the implicit declaration
8075 // would be.
8076 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8077 ? ConstexprSpecKind::Consteval
8078 : ConstexprSpecKind::Constexpr)
8079 : ConstexprSpecKind::Unspecified);
8080
8081 if (!Type->hasExceptionSpec()) {
8082 // C++2a [except.spec]p3:
8083 // If a declaration of a function does not have a noexcept-specifier
8084 // [and] is defaulted on its first declaration, [...] the exception
8085 // specification is as specified below
8086 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8087 EPI.ExceptionSpec.Type = EST_Unevaluated;
8088 EPI.ExceptionSpec.SourceDecl = MD;
8089 MD->setType(
8090 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8091 }
8092 }
8093
8094 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8095 if (First) {
8096 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8097 if (!inTemplateInstantiation() && !HadError) {
8098 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8099 if (ShouldDeleteForTypeMismatch) {
8100 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8101 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8102 /*Diagnose*/ true) &&
8103 DefaultLoc.isValid()) {
8104 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8105 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8106 }
8107 }
8108 if (ShouldDeleteForTypeMismatch && !HadError) {
8109 Diag(Loc: MD->getLocation(),
8110 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8111 << CSM;
8112 }
8113 } else {
8114 // C++11 [dcl.fct.def.default]p4:
8115 // [For a] user-provided explicitly-defaulted function [...] if such a
8116 // function is implicitly defined as deleted, the program is ill-formed.
8117 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8118 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8119 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8120 HadError = true;
8121 }
8122 }
8123
8124 return HadError;
8125}
8126
8127namespace {
8128/// Helper class for building and checking a defaulted comparison.
8129///
8130/// Defaulted functions are built in two phases:
8131///
8132/// * First, the set of operations that the function will perform are
8133/// identified, and some of them are checked. If any of the checked
8134/// operations is invalid in certain ways, the comparison function is
8135/// defined as deleted and no body is built.
8136/// * Then, if the function is not defined as deleted, the body is built.
8137///
8138/// This is accomplished by performing two visitation steps over the eventual
8139/// body of the function.
8140template<typename Derived, typename ResultList, typename Result,
8141 typename Subobject>
8142class DefaultedComparisonVisitor {
8143public:
8144 using DefaultedComparisonKind = Sema::DefaultedComparisonKind;
8145
8146 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8147 DefaultedComparisonKind DCK)
8148 : S(S), RD(RD), FD(FD), DCK(DCK) {
8149 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8150 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8151 // UnresolvedSet to avoid this copy.
8152 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8153 E: Info->getUnqualifiedLookups().end());
8154 }
8155 }
8156
8157 ResultList visit() {
8158 // The type of an lvalue naming a parameter of this function.
8159 QualType ParamLvalType =
8160 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8161
8162 ResultList Results;
8163
8164 switch (DCK) {
8165 case DefaultedComparisonKind::None:
8166 llvm_unreachable("not a defaulted comparison");
8167
8168 case DefaultedComparisonKind::Equal:
8169 case DefaultedComparisonKind::ThreeWay:
8170 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8171 return Results;
8172
8173 case DefaultedComparisonKind::NotEqual:
8174 case DefaultedComparisonKind::Relational:
8175 Results.add(getDerived().visitExpandedSubobject(
8176 ParamLvalType, getDerived().getCompleteObject()));
8177 return Results;
8178 }
8179 llvm_unreachable("");
8180 }
8181
8182protected:
8183 Derived &getDerived() { return static_cast<Derived&>(*this); }
8184
8185 /// Visit the expanded list of subobjects of the given type, as specified in
8186 /// C++2a [class.compare.default].
8187 ///
8188 /// \return \c true if the ResultList object said we're done, \c false if not.
8189 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8190 Qualifiers Quals) {
8191 // C++2a [class.compare.default]p4:
8192 // The direct base class subobjects of C
8193 for (CXXBaseSpecifier &Base : Record->bases())
8194 if (Results.add(getDerived().visitSubobject(
8195 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8196 getDerived().getBase(&Base))))
8197 return true;
8198
8199 // followed by the non-static data members of C
8200 for (FieldDecl *Field : Record->fields()) {
8201 // C++23 [class.bit]p2:
8202 // Unnamed bit-fields are not members ...
8203 if (Field->isUnnamedBitField())
8204 continue;
8205 // Recursively expand anonymous structs.
8206 if (Field->isAnonymousStructOrUnion()) {
8207 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8208 Quals))
8209 return true;
8210 continue;
8211 }
8212
8213 // Figure out the type of an lvalue denoting this field.
8214 Qualifiers FieldQuals = Quals;
8215 if (Field->isMutable())
8216 FieldQuals.removeConst();
8217 QualType FieldType =
8218 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8219
8220 if (Results.add(getDerived().visitSubobject(
8221 FieldType, getDerived().getField(Field))))
8222 return true;
8223 }
8224
8225 // form a list of subobjects.
8226 return false;
8227 }
8228
8229 Result visitSubobject(QualType Type, Subobject Subobj) {
8230 // In that list, any subobject of array type is recursively expanded
8231 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8232 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8233 return getDerived().visitSubobjectArray(CAT->getElementType(),
8234 CAT->getSize(), Subobj);
8235 return getDerived().visitExpandedSubobject(Type, Subobj);
8236 }
8237
8238 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8239 Subobject Subobj) {
8240 return getDerived().visitSubobject(Type, Subobj);
8241 }
8242
8243protected:
8244 Sema &S;
8245 CXXRecordDecl *RD;
8246 FunctionDecl *FD;
8247 DefaultedComparisonKind DCK;
8248 UnresolvedSet<16> Fns;
8249};
8250
8251/// Information about a defaulted comparison, as determined by
8252/// DefaultedComparisonAnalyzer.
8253struct DefaultedComparisonInfo {
8254 bool Deleted = false;
8255 bool Constexpr = true;
8256 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8257
8258 static DefaultedComparisonInfo deleted() {
8259 DefaultedComparisonInfo Deleted;
8260 Deleted.Deleted = true;
8261 return Deleted;
8262 }
8263
8264 bool add(const DefaultedComparisonInfo &R) {
8265 Deleted |= R.Deleted;
8266 Constexpr &= R.Constexpr;
8267 Category = commonComparisonType(A: Category, B: R.Category);
8268 return Deleted;
8269 }
8270};
8271
8272/// An element in the expanded list of subobjects of a defaulted comparison, as
8273/// specified in C++2a [class.compare.default]p4.
8274struct DefaultedComparisonSubobject {
8275 enum { CompleteObject, Member, Base } Kind;
8276 NamedDecl *Decl;
8277 SourceLocation Loc;
8278};
8279
8280/// A visitor over the notional body of a defaulted comparison that determines
8281/// whether that body would be deleted or constexpr.
8282class DefaultedComparisonAnalyzer
8283 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8284 DefaultedComparisonInfo,
8285 DefaultedComparisonInfo,
8286 DefaultedComparisonSubobject> {
8287public:
8288 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8289
8290private:
8291 DiagnosticKind Diagnose;
8292
8293public:
8294 using Base = DefaultedComparisonVisitor;
8295 using Result = DefaultedComparisonInfo;
8296 using Subobject = DefaultedComparisonSubobject;
8297
8298 friend Base;
8299
8300 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8301 DefaultedComparisonKind DCK,
8302 DiagnosticKind Diagnose = NoDiagnostics)
8303 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8304
8305 Result visit() {
8306 if ((DCK == DefaultedComparisonKind::Equal ||
8307 DCK == DefaultedComparisonKind::ThreeWay) &&
8308 RD->hasVariantMembers()) {
8309 // C++2a [class.compare.default]p2 [P2002R0]:
8310 // A defaulted comparison operator function for class C is defined as
8311 // deleted if [...] C has variant members.
8312 if (Diagnose == ExplainDeleted) {
8313 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8314 << FD << RD->isUnion() << RD;
8315 }
8316 return Result::deleted();
8317 }
8318
8319 return Base::visit();
8320 }
8321
8322private:
8323 Subobject getCompleteObject() {
8324 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8325 }
8326
8327 Subobject getBase(CXXBaseSpecifier *Base) {
8328 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8329 .Loc: Base->getBaseTypeLoc()};
8330 }
8331
8332 Subobject getField(FieldDecl *Field) {
8333 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8334 }
8335
8336 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8337 // C++2a [class.compare.default]p2 [P2002R0]:
8338 // A defaulted <=> or == operator function for class C is defined as
8339 // deleted if any non-static data member of C is of reference type
8340 if (Type->isReferenceType()) {
8341 if (Diagnose == ExplainDeleted) {
8342 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8343 << FD << RD;
8344 }
8345 return Result::deleted();
8346 }
8347
8348 // [...] Let xi be an lvalue denoting the ith element [...]
8349 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8350 Expr *Args[] = {&Xi, &Xi};
8351
8352 // All operators start by trying to apply that same operator recursively.
8353 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8354 assert(OO != OO_None && "not an overloaded operator!");
8355 return visitBinaryOperator(OO, Args, Subobj);
8356 }
8357
8358 Result
8359 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8360 Subobject Subobj,
8361 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8362 // Note that there is no need to consider rewritten candidates here if
8363 // we've already found there is no viable 'operator<=>' candidate (and are
8364 // considering synthesizing a '<=>' from '==' and '<').
8365 OverloadCandidateSet CandidateSet(
8366 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8367 OverloadCandidateSet::OperatorRewriteInfo(
8368 OO, FD->getLocation(),
8369 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8370
8371 /// C++2a [class.compare.default]p1 [P2002R0]:
8372 /// [...] the defaulted function itself is never a candidate for overload
8373 /// resolution [...]
8374 CandidateSet.exclude(F: FD);
8375
8376 if (Args[0]->getType()->isOverloadableType())
8377 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8378 else
8379 // FIXME: We determine whether this is a valid expression by checking to
8380 // see if there's a viable builtin operator candidate for it. That isn't
8381 // really what the rules ask us to do, but should give the right results.
8382 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8383
8384 Result R;
8385
8386 OverloadCandidateSet::iterator Best;
8387 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8388 case OR_Success: {
8389 // C++2a [class.compare.secondary]p2 [P2002R0]:
8390 // The operator function [...] is defined as deleted if [...] the
8391 // candidate selected by overload resolution is not a rewritten
8392 // candidate.
8393 if ((DCK == DefaultedComparisonKind::NotEqual ||
8394 DCK == DefaultedComparisonKind::Relational) &&
8395 !Best->RewriteKind) {
8396 if (Diagnose == ExplainDeleted) {
8397 if (Best->Function) {
8398 S.Diag(Loc: Best->Function->getLocation(),
8399 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8400 << FD;
8401 } else {
8402 assert(Best->Conversions.size() == 2 &&
8403 Best->Conversions[0].isUserDefined() &&
8404 "non-user-defined conversion from class to built-in "
8405 "comparison");
8406 S.Diag(Loc: Best->Conversions[0]
8407 .UserDefined.FoundConversionFunction.getDecl()
8408 ->getLocation(),
8409 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8410 << FD;
8411 }
8412 }
8413 return Result::deleted();
8414 }
8415
8416 // Throughout C++2a [class.compare]: if overload resolution does not
8417 // result in a usable function, the candidate function is defined as
8418 // deleted. This requires that we selected an accessible function.
8419 //
8420 // Note that this only considers the access of the function when named
8421 // within the type of the subobject, and not the access path for any
8422 // derived-to-base conversion.
8423 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8424 if (ArgClass && Best->FoundDecl.getDecl() &&
8425 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8426 QualType ObjectType = Subobj.Kind == Subobject::Member
8427 ? Args[0]->getType()
8428 : S.Context.getCanonicalTagType(TD: RD);
8429 if (!S.isMemberAccessibleForDeletion(
8430 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8431 Diag: Diagnose == ExplainDeleted
8432 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8433 << FD << Subobj.Kind << Subobj.Decl
8434 : S.PDiag()))
8435 return Result::deleted();
8436 }
8437
8438 bool NeedsDeducing =
8439 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8440
8441 if (FunctionDecl *BestFD = Best->Function) {
8442 // C++2a [class.compare.default]p3 [P2002R0]:
8443 // A defaulted comparison function is constexpr-compatible if
8444 // [...] no overlod resolution performed [...] results in a
8445 // non-constexpr function.
8446 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8447 // If it's not constexpr, explain why not.
8448 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8449 if (Subobj.Kind != Subobject::CompleteObject)
8450 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8451 << Subobj.Kind << Subobj.Decl;
8452 S.Diag(Loc: BestFD->getLocation(),
8453 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8454 // Bail out after explaining; we don't want any more notes.
8455 return Result::deleted();
8456 }
8457 R.Constexpr &= BestFD->isConstexpr();
8458
8459 if (NeedsDeducing) {
8460 // If any callee has an undeduced return type, deduce it now.
8461 // FIXME: It's not clear how a failure here should be handled. For
8462 // now, we produce an eager diagnostic, because that is forward
8463 // compatible with most (all?) other reasonable options.
8464 if (BestFD->getReturnType()->isUndeducedType() &&
8465 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8466 /*Diagnose=*/false)) {
8467 // Don't produce a duplicate error when asked to explain why the
8468 // comparison is deleted: we diagnosed that when initially checking
8469 // the defaulted operator.
8470 if (Diagnose == NoDiagnostics) {
8471 S.Diag(
8472 Loc: FD->getLocation(),
8473 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8474 << Subobj.Kind << Subobj.Decl;
8475 S.Diag(
8476 Loc: Subobj.Loc,
8477 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8478 << Subobj.Kind << Subobj.Decl;
8479 S.Diag(Loc: BestFD->getLocation(),
8480 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8481 << Subobj.Kind << Subobj.Decl;
8482 }
8483 return Result::deleted();
8484 }
8485 auto *Info = S.Context.CompCategories.lookupInfoForType(
8486 Ty: BestFD->getCallResultType());
8487 if (!Info) {
8488 if (Diagnose == ExplainDeleted) {
8489 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8490 << Subobj.Kind << Subobj.Decl
8491 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8492 S.Diag(Loc: BestFD->getLocation(),
8493 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8494 << Subobj.Kind << Subobj.Decl;
8495 }
8496 return Result::deleted();
8497 }
8498 R.Category = Info->Kind;
8499 }
8500 } else {
8501 QualType T = Best->BuiltinParamTypes[0];
8502 assert(T == Best->BuiltinParamTypes[1] &&
8503 "builtin comparison for different types?");
8504 assert(Best->BuiltinParamTypes[2].isNull() &&
8505 "invalid builtin comparison");
8506
8507 // FIXME: If the type we deduced is a vector type, we mark the
8508 // comparison as deleted because we don't yet support this.
8509 if (isa<VectorType>(Val: T)) {
8510 if (Diagnose == ExplainDeleted) {
8511 S.Diag(Loc: FD->getLocation(),
8512 DiagID: diag::note_defaulted_comparison_vector_types)
8513 << FD;
8514 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8515 }
8516 return Result::deleted();
8517 }
8518
8519 if (NeedsDeducing) {
8520 std::optional<ComparisonCategoryType> Cat =
8521 getComparisonCategoryForBuiltinCmp(T);
8522 assert(Cat && "no category for builtin comparison?");
8523 R.Category = *Cat;
8524 }
8525 }
8526
8527 // Note that we might be rewriting to a different operator. That call is
8528 // not considered until we come to actually build the comparison function.
8529 break;
8530 }
8531
8532 case OR_Ambiguous:
8533 if (Diagnose == ExplainDeleted) {
8534 unsigned Kind = 0;
8535 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8536 Kind = OO == OO_EqualEqual ? 1 : 2;
8537 CandidateSet.NoteCandidates(
8538 PA: PartialDiagnosticAt(
8539 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8540 << FD << Kind << Subobj.Kind << Subobj.Decl),
8541 S, OCD: OCD_AmbiguousCandidates, Args);
8542 }
8543 R = Result::deleted();
8544 break;
8545
8546 case OR_Deleted:
8547 if (Diagnose == ExplainDeleted) {
8548 if ((DCK == DefaultedComparisonKind::NotEqual ||
8549 DCK == DefaultedComparisonKind::Relational) &&
8550 !Best->RewriteKind) {
8551 S.Diag(Loc: Best->Function->getLocation(),
8552 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8553 << FD;
8554 } else {
8555 S.Diag(Loc: Subobj.Loc,
8556 DiagID: diag::note_defaulted_comparison_calls_deleted)
8557 << FD << Subobj.Kind << Subobj.Decl;
8558 S.NoteDeletedFunction(FD: Best->Function);
8559 }
8560 }
8561 R = Result::deleted();
8562 break;
8563
8564 case OR_No_Viable_Function:
8565 // If there's no usable candidate, we're done unless we can rewrite a
8566 // '<=>' in terms of '==' and '<'.
8567 if (OO == OO_Spaceship &&
8568 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8569 // For any kind of comparison category return type, we need a usable
8570 // '==' and a usable '<'.
8571 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8572 SpaceshipCandidates: &CandidateSet)))
8573 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8574 break;
8575 }
8576
8577 if (Diagnose == ExplainDeleted) {
8578 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8579 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8580 << Subobj.Kind << Subobj.Decl;
8581
8582 // For a three-way comparison, list both the candidates for the
8583 // original operator and the candidates for the synthesized operator.
8584 if (SpaceshipCandidates) {
8585 SpaceshipCandidates->NoteCandidates(
8586 S, Args,
8587 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8588 Args, OpLoc: FD->getLocation()));
8589 S.Diag(Loc: Subobj.Loc,
8590 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8591 << (OO == OO_EqualEqual ? 0 : 1);
8592 }
8593
8594 CandidateSet.NoteCandidates(
8595 S, Args,
8596 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8597 OpLoc: FD->getLocation()));
8598 }
8599 R = Result::deleted();
8600 break;
8601 }
8602
8603 return R;
8604 }
8605};
8606
8607/// A list of statements.
8608struct StmtListResult {
8609 bool IsInvalid = false;
8610 llvm::SmallVector<Stmt*, 16> Stmts;
8611
8612 bool add(const StmtResult &S) {
8613 IsInvalid |= S.isInvalid();
8614 if (IsInvalid)
8615 return true;
8616 Stmts.push_back(Elt: S.get());
8617 return false;
8618 }
8619};
8620
8621/// A visitor over the notional body of a defaulted comparison that synthesizes
8622/// the actual body.
8623class DefaultedComparisonSynthesizer
8624 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8625 StmtListResult, StmtResult,
8626 std::pair<ExprResult, ExprResult>> {
8627 SourceLocation Loc;
8628 unsigned ArrayDepth = 0;
8629
8630public:
8631 using Base = DefaultedComparisonVisitor;
8632 using ExprPair = std::pair<ExprResult, ExprResult>;
8633
8634 friend Base;
8635
8636 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8637 DefaultedComparisonKind DCK,
8638 SourceLocation BodyLoc)
8639 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8640
8641 /// Build a suitable function body for this defaulted comparison operator.
8642 StmtResult build() {
8643 Sema::CompoundScopeRAII CompoundScope(S);
8644
8645 StmtListResult Stmts = visit();
8646 if (Stmts.IsInvalid)
8647 return StmtError();
8648
8649 ExprResult RetVal;
8650 switch (DCK) {
8651 case DefaultedComparisonKind::None:
8652 llvm_unreachable("not a defaulted comparison");
8653
8654 case DefaultedComparisonKind::Equal: {
8655 // C++2a [class.eq]p3:
8656 // [...] compar[e] the corresponding elements [...] until the first
8657 // index i where xi == yi yields [...] false. If no such index exists,
8658 // V is true. Otherwise, V is false.
8659 //
8660 // Join the comparisons with '&&'s and return the result. Use a right
8661 // fold (traversing the conditions right-to-left), because that
8662 // short-circuits more naturally.
8663 auto OldStmts = std::move(Stmts.Stmts);
8664 Stmts.Stmts.clear();
8665 ExprResult CmpSoFar;
8666 // Finish a particular comparison chain.
8667 auto FinishCmp = [&] {
8668 if (Expr *Prior = CmpSoFar.get()) {
8669 // Convert the last expression to 'return ...;'
8670 if (RetVal.isUnset() && Stmts.Stmts.empty())
8671 RetVal = CmpSoFar;
8672 // Convert any prior comparison to 'if (!(...)) return false;'
8673 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8674 return true;
8675 CmpSoFar = ExprResult();
8676 }
8677 return false;
8678 };
8679 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8680 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8681 if (!E) {
8682 // Found an array comparison.
8683 if (FinishCmp() || Stmts.add(S: EAsStmt))
8684 return StmtError();
8685 continue;
8686 }
8687
8688 if (CmpSoFar.isUnset()) {
8689 CmpSoFar = E;
8690 continue;
8691 }
8692 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8693 if (CmpSoFar.isInvalid())
8694 return StmtError();
8695 }
8696 if (FinishCmp())
8697 return StmtError();
8698 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8699 // If no such index exists, V is true.
8700 if (RetVal.isUnset())
8701 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8702 break;
8703 }
8704
8705 case DefaultedComparisonKind::ThreeWay: {
8706 // Per C++2a [class.spaceship]p3, as a fallback add:
8707 // return static_cast<R>(std::strong_ordering::equal);
8708 QualType StrongOrdering = S.CheckComparisonCategoryType(
8709 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8710 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8711 if (StrongOrdering.isNull())
8712 return StmtError();
8713 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8714 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8715 ->VD;
8716 RetVal = getDecl(VD: EqualVD);
8717 if (RetVal.isInvalid())
8718 return StmtError();
8719 RetVal = buildStaticCastToR(E: RetVal.get());
8720 break;
8721 }
8722
8723 case DefaultedComparisonKind::NotEqual:
8724 case DefaultedComparisonKind::Relational:
8725 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8726 break;
8727 }
8728
8729 // Build the final return statement.
8730 if (RetVal.isInvalid())
8731 return StmtError();
8732 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8733 if (ReturnStmt.isInvalid())
8734 return StmtError();
8735 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8736
8737 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8738 }
8739
8740private:
8741 ExprResult getDecl(ValueDecl *VD) {
8742 return S.BuildDeclarationNameExpr(
8743 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8744 }
8745
8746 ExprResult getParam(unsigned I) {
8747 ParmVarDecl *PD = FD->getParamDecl(i: I);
8748 return getDecl(VD: PD);
8749 }
8750
8751 ExprPair getCompleteObject() {
8752 unsigned Param = 0;
8753 ExprResult LHS;
8754 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8755 MD && MD->isImplicitObjectMemberFunction()) {
8756 // LHS is '*this'.
8757 LHS = S.ActOnCXXThis(Loc);
8758 if (!LHS.isInvalid())
8759 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8760 } else {
8761 LHS = getParam(I: Param++);
8762 }
8763 ExprResult RHS = getParam(I: Param++);
8764 assert(Param == FD->getNumParams());
8765 return {LHS, RHS};
8766 }
8767
8768 ExprPair getBase(CXXBaseSpecifier *Base) {
8769 ExprPair Obj = getCompleteObject();
8770 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8771 return {ExprError(), ExprError()};
8772 CXXCastPath Path = {Base};
8773 const auto CastToBase = [&](Expr *E) {
8774 QualType ToType = S.Context.getQualifiedType(
8775 T: Base->getType(), Qs: E->getType().getQualifiers());
8776 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8777 };
8778 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8779 }
8780
8781 ExprPair getField(FieldDecl *Field) {
8782 ExprPair Obj = getCompleteObject();
8783 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8784 return {ExprError(), ExprError()};
8785
8786 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8787 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8788 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8789 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8790 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8791 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8792 }
8793
8794 // FIXME: When expanding a subobject, register a note in the code synthesis
8795 // stack to say which subobject we're comparing.
8796
8797 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8798 if (Cond.isInvalid())
8799 return StmtError();
8800
8801 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8802 if (NotCond.isInvalid())
8803 return StmtError();
8804
8805 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8806 assert(!False.isInvalid() && "should never fail");
8807 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8808 if (ReturnFalse.isInvalid())
8809 return StmtError();
8810
8811 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8812 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8813 CK: Sema::ConditionKind::Boolean),
8814 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8815 }
8816
8817 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8818 ExprPair Subobj) {
8819 QualType SizeType = S.Context.getSizeType();
8820 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8821
8822 // Build 'size_t i$n = 0'.
8823 IdentifierInfo *IterationVarName = nullptr;
8824 {
8825 SmallString<8> Str;
8826 llvm::raw_svector_ostream OS(Str);
8827 OS << "i" << ArrayDepth;
8828 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8829 }
8830 VarDecl *IterationVar = VarDecl::Create(
8831 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8832 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8833 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8834 IterationVar->setInit(
8835 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8836 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8837
8838 auto IterRef = [&] {
8839 ExprResult Ref = S.BuildDeclarationNameExpr(
8840 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8841 D: IterationVar);
8842 assert(!Ref.isInvalid() && "can't reference our own variable?");
8843 return Ref.get();
8844 };
8845
8846 // Build 'i$n != Size'.
8847 ExprResult Cond = S.CreateBuiltinBinOp(
8848 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8849 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8850 assert(!Cond.isInvalid() && "should never fail");
8851
8852 // Build '++i$n'.
8853 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8854 assert(!Inc.isInvalid() && "should never fail");
8855
8856 // Build 'a[i$n]' and 'b[i$n]'.
8857 auto Index = [&](ExprResult E) {
8858 if (E.isInvalid())
8859 return ExprError();
8860 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8861 };
8862 Subobj.first = Index(Subobj.first);
8863 Subobj.second = Index(Subobj.second);
8864
8865 // Compare the array elements.
8866 ++ArrayDepth;
8867 StmtResult Substmt = visitSubobject(Type, Subobj);
8868 --ArrayDepth;
8869
8870 if (Substmt.isInvalid())
8871 return StmtError();
8872
8873 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8874 // For outer levels or for an 'operator<=>' we already have a suitable
8875 // statement that returns as necessary.
8876 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8877 assert(DCK == DefaultedComparisonKind::Equal &&
8878 "should have non-expression statement");
8879 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8880 if (Substmt.isInvalid())
8881 return StmtError();
8882 }
8883
8884 // Build 'for (...) ...'
8885 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8886 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8887 CK: Sema::ConditionKind::Boolean),
8888 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8889 Body: Substmt.get());
8890 }
8891
8892 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8893 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8894 return StmtError();
8895
8896 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8897 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8898 ExprResult Op;
8899 if (Type->isOverloadableType())
8900 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8901 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8902 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8903 else
8904 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8905 if (Op.isInvalid())
8906 return StmtError();
8907
8908 switch (DCK) {
8909 case DefaultedComparisonKind::None:
8910 llvm_unreachable("not a defaulted comparison");
8911
8912 case DefaultedComparisonKind::Equal:
8913 // Per C++2a [class.eq]p2, each comparison is individually contextually
8914 // converted to bool.
8915 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8916 if (Op.isInvalid())
8917 return StmtError();
8918 return Op.get();
8919
8920 case DefaultedComparisonKind::ThreeWay: {
8921 // Per C++2a [class.spaceship]p3, form:
8922 // if (R cmp = static_cast<R>(op); cmp != 0)
8923 // return cmp;
8924 QualType R = FD->getReturnType();
8925 Op = buildStaticCastToR(E: Op.get());
8926 if (Op.isInvalid())
8927 return StmtError();
8928
8929 // R cmp = ...;
8930 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8931 VarDecl *VD =
8932 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8933 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8934 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8935 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8936
8937 // cmp != 0
8938 ExprResult VDRef = getDecl(VD);
8939 if (VDRef.isInvalid())
8940 return StmtError();
8941 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8942 Expr *Zero =
8943 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8944 ExprResult Comp;
8945 if (VDRef.get()->getType()->isOverloadableType())
8946 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8947 AllowRewrittenCandidates: true, DefaultedFn: FD);
8948 else
8949 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8950 if (Comp.isInvalid())
8951 return StmtError();
8952 Sema::ConditionResult Cond = S.ActOnCondition(
8953 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8954 if (Cond.isInvalid())
8955 return StmtError();
8956
8957 // return cmp;
8958 VDRef = getDecl(VD);
8959 if (VDRef.isInvalid())
8960 return StmtError();
8961 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8962 if (ReturnStmt.isInvalid())
8963 return StmtError();
8964
8965 // if (...)
8966 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8967 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8968 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
8969 }
8970
8971 case DefaultedComparisonKind::NotEqual:
8972 case DefaultedComparisonKind::Relational:
8973 // C++2a [class.compare.secondary]p2:
8974 // Otherwise, the operator function yields x @ y.
8975 return Op.get();
8976 }
8977 llvm_unreachable("");
8978 }
8979
8980 /// Build "static_cast<R>(E)".
8981 ExprResult buildStaticCastToR(Expr *E) {
8982 QualType R = FD->getReturnType();
8983 assert(!R->isUndeducedType() && "type should have been deduced already");
8984
8985 // Don't bother forming a no-op cast in the common case.
8986 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
8987 return E;
8988 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
8989 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
8990 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
8991 }
8992};
8993}
8994
8995/// Perform the unqualified lookups that might be needed to form a defaulted
8996/// comparison function for the given operator.
8997static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
8998 UnresolvedSetImpl &Operators,
8999 OverloadedOperatorKind Op) {
9000 auto Lookup = [&](OverloadedOperatorKind OO) {
9001 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
9002 };
9003
9004 // Every defaulted operator looks up itself.
9005 Lookup(Op);
9006 // ... and the rewritten form of itself, if any.
9007 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
9008 Lookup(ExtraOp);
9009
9010 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9011 // synthesize a three-way comparison from '<' and '=='. In a dependent
9012 // context, we also need to look up '==' in case we implicitly declare a
9013 // defaulted 'operator=='.
9014 if (Op == OO_Spaceship) {
9015 Lookup(OO_ExclaimEqual);
9016 Lookup(OO_Less);
9017 Lookup(OO_EqualEqual);
9018 }
9019}
9020
9021bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
9022 DefaultedComparisonKind DCK) {
9023 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9024
9025 // Perform any unqualified lookups we're going to need to default this
9026 // function.
9027 if (S) {
9028 UnresolvedSet<32> Operators;
9029 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9030 Op: FD->getOverloadedOperator());
9031 FD->setDefaultedOrDeletedInfo(
9032 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9033 Context, Lookups: Operators.pairs()));
9034 }
9035
9036 // C++2a [class.compare.default]p1:
9037 // A defaulted comparison operator function for some class C shall be a
9038 // non-template function declared in the member-specification of C that is
9039 // -- a non-static const non-volatile member of C having one parameter of
9040 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9041 // -- a friend of C having two parameters of type const C& or two
9042 // parameters of type C.
9043
9044 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9045 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9046 if (IsMethod) {
9047 auto *MD = cast<CXXMethodDecl>(Val: FD);
9048 assert(!MD->isStatic() && "comparison function cannot be a static member");
9049
9050 if (MD->getRefQualifier() == RQ_RValue) {
9051 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9052
9053 // Remove the ref qualifier to recover.
9054 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9055 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9056 EPI.RefQualifier = RQ_None;
9057 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9058 Args: FPT->getParamTypes(), EPI));
9059 }
9060
9061 // If we're out-of-class, this is the class we're comparing.
9062 if (!RD)
9063 RD = MD->getParent();
9064 QualType T = MD->getFunctionObjectParameterReferenceType();
9065 if (!T.getNonReferenceType().isConstQualified() &&
9066 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9067 SourceLocation Loc, InsertLoc;
9068 if (MD->isExplicitObjectMemberFunction()) {
9069 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9070 InsertLoc = getLocForEndOfToken(
9071 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9072 } else {
9073 Loc = MD->getLocation();
9074 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9075 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9076 }
9077 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9078 // corresponding defaulted 'operator<=>' already.
9079 if (!MD->isImplicit()) {
9080 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9081 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9082 }
9083
9084 // Add the 'const' to the type to recover.
9085 if (MD->isExplicitObjectMemberFunction()) {
9086 assert(T->isLValueReferenceType());
9087 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9088 T: T.getNonReferenceType().withConst()));
9089 } else {
9090 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9091 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9092 EPI.TypeQuals.addConst();
9093 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9094 Args: FPT->getParamTypes(), EPI));
9095 }
9096 }
9097
9098 if (MD->isVolatile()) {
9099 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9100
9101 // Remove the 'volatile' from the type to recover.
9102 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9103 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9104 EPI.TypeQuals.removeVolatile();
9105 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9106 Args: FPT->getParamTypes(), EPI));
9107 }
9108 }
9109
9110 if ((FD->getNumParams() -
9111 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9112 (IsMethod ? 1 : 2)) {
9113 // Let's not worry about using a variadic template pack here -- who would do
9114 // such a thing?
9115 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9116 << int(IsMethod) << int(DCK);
9117 return true;
9118 }
9119
9120 const ParmVarDecl *KnownParm = nullptr;
9121 for (const ParmVarDecl *Param : FD->parameters()) {
9122 QualType ParmTy = Param->getType();
9123 if (!KnownParm) {
9124 auto CTy = ParmTy;
9125 // Is it `T const &`?
9126 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9127 QualType ExpectedTy;
9128 if (RD)
9129 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9130 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9131 CTy = Ref->getPointeeType();
9132 if (RD)
9133 ExpectedTy.addConst();
9134 Ok = true;
9135 }
9136
9137 // Is T a class?
9138 if (RD) {
9139 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9140 } else {
9141 RD = CTy->getAsCXXRecordDecl();
9142 Ok &= RD != nullptr;
9143 }
9144
9145 if (Ok) {
9146 KnownParm = Param;
9147 } else {
9148 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9149 // corresponding defaulted 'operator<=>' already.
9150 if (!FD->isImplicit()) {
9151 if (RD) {
9152 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9153 QualType RefTy =
9154 Context.getLValueReferenceType(T: PlainTy.withConst());
9155 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9156 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9157 << Param->getSourceRange();
9158 } else {
9159 assert(!IsMethod && "should know expected type for method");
9160 Diag(Loc: FD->getLocation(),
9161 DiagID: diag::err_defaulted_comparison_param_unknown)
9162 << int(DCK) << ParmTy << Param->getSourceRange();
9163 }
9164 }
9165 return true;
9166 }
9167 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9168 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9169 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9170 << ParmTy << Param->getSourceRange();
9171 return true;
9172 }
9173 }
9174
9175 assert(RD && "must have determined class");
9176 if (IsMethod) {
9177 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9178 // In-class, must be a friend decl.
9179 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9180 } else {
9181 // Out of class, require the defaulted comparison to be a friend (of a
9182 // complete type, per CWG2547).
9183 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9184 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9185 Args: int(1)))
9186 return true;
9187
9188 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9189 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9190 })) {
9191 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9192 << int(DCK) << int(0) << RD;
9193 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9194 return true;
9195 }
9196 }
9197
9198 // C++2a [class.eq]p1, [class.rel]p1:
9199 // A [defaulted comparison other than <=>] shall have a declared return
9200 // type bool.
9201 if (DCK != DefaultedComparisonKind::ThreeWay &&
9202 !FD->getDeclaredReturnType()->isDependentType() &&
9203 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9204 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9205 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9206 << FD->getReturnTypeSourceRange();
9207 return true;
9208 }
9209 // C++2a [class.spaceship]p2 [P2002R0]:
9210 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9211 // R shall not contain a placeholder type.
9212 if (QualType RT = FD->getDeclaredReturnType();
9213 DCK == DefaultedComparisonKind::ThreeWay &&
9214 RT->getContainedDeducedType() &&
9215 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9216 RT->getContainedAutoType()->isConstrained())) {
9217 Diag(Loc: FD->getLocation(),
9218 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9219 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9220 << FD->getReturnTypeSourceRange();
9221 return true;
9222 }
9223
9224 // For a defaulted function in a dependent class, defer all remaining checks
9225 // until instantiation.
9226 if (RD->isDependentType())
9227 return false;
9228
9229 // Determine whether the function should be defined as deleted.
9230 DefaultedComparisonInfo Info =
9231 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9232
9233 bool First = FD == FD->getCanonicalDecl();
9234
9235 if (!First) {
9236 if (Info.Deleted) {
9237 // C++11 [dcl.fct.def.default]p4:
9238 // [For a] user-provided explicitly-defaulted function [...] if such a
9239 // function is implicitly defined as deleted, the program is ill-formed.
9240 //
9241 // This is really just a consequence of the general rule that you can
9242 // only delete a function on its first declaration.
9243 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9244 << FD->isImplicit() << (int)DCK;
9245 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9246 DefaultedComparisonAnalyzer::ExplainDeleted)
9247 .visit();
9248 return true;
9249 }
9250 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9251 // C++20 [class.compare.default]p1:
9252 // [...] A definition of a comparison operator as defaulted that appears
9253 // in a class shall be the first declaration of that function.
9254 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9255 << (int)DCK;
9256 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9257 DiagID: diag::note_previous_declaration);
9258 return true;
9259 }
9260 }
9261
9262 // If we want to delete the function, then do so; there's nothing else to
9263 // check in that case.
9264 if (Info.Deleted) {
9265 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9266 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9267 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9268 << (int)DCK;
9269 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9270 DefaultedComparisonAnalyzer::ExplainDeleted)
9271 .visit();
9272 if (FD->getDefaultLoc().isValid())
9273 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9274 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9275 }
9276 return false;
9277 }
9278
9279 // C++2a [class.spaceship]p2:
9280 // The return type is deduced as the common comparison type of R0, R1, ...
9281 if (DCK == DefaultedComparisonKind::ThreeWay &&
9282 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9283 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9284 if (RetLoc.isInvalid())
9285 RetLoc = FD->getBeginLoc();
9286 // FIXME: Should we really care whether we have the complete type and the
9287 // 'enumerator' constants here? A forward declaration seems sufficient.
9288 QualType Cat = CheckComparisonCategoryType(
9289 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9290 if (Cat.isNull())
9291 return true;
9292 Context.adjustDeducedFunctionResultType(
9293 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9294 }
9295
9296 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9297 // An explicitly-defaulted function that is not defined as deleted may be
9298 // declared constexpr or consteval only if it is constexpr-compatible.
9299 // C++2a [class.compare.default]p3 [P2002R0]:
9300 // A defaulted comparison function is constexpr-compatible if it satisfies
9301 // the requirements for a constexpr function [...]
9302 // The only relevant requirements are that the parameter and return types are
9303 // literal types. The remaining conditions are checked by the analyzer.
9304 //
9305 // We support P2448R2 in language modes earlier than C++23 as an extension.
9306 // The concept of constexpr-compatible was removed.
9307 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9308 // A function explicitly defaulted on its first declaration is implicitly
9309 // inline, and is implicitly constexpr if it is constexpr-suitable.
9310 // C++23 [dcl.constexpr]p3
9311 // A function is constexpr-suitable if
9312 // - it is not a coroutine, and
9313 // - if the function is a constructor or destructor, its class does not
9314 // have any virtual base classes.
9315 if (FD->isConstexpr()) {
9316 if (!getLangOpts().CPlusPlus23 &&
9317 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9318 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9319 !Info.Constexpr) {
9320 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9321 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9322 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9323 DefaultedComparisonAnalyzer::ExplainConstexpr)
9324 .visit();
9325 }
9326 }
9327
9328 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9329 // If a constexpr-compatible function is explicitly defaulted on its first
9330 // declaration, it is implicitly considered to be constexpr.
9331 // FIXME: Only applying this to the first declaration seems problematic, as
9332 // simple reorderings can affect the meaning of the program.
9333 if (First && !FD->isConstexpr() && Info.Constexpr)
9334 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9335
9336 // C++2a [except.spec]p3:
9337 // If a declaration of a function does not have a noexcept-specifier
9338 // [and] is defaulted on its first declaration, [...] the exception
9339 // specification is as specified below
9340 if (FD->getExceptionSpecType() == EST_None) {
9341 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9342 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9343 EPI.ExceptionSpec.Type = EST_Unevaluated;
9344 EPI.ExceptionSpec.SourceDecl = FD;
9345 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9346 Args: FPT->getParamTypes(), EPI));
9347 }
9348
9349 return false;
9350}
9351
9352void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9353 FunctionDecl *Spaceship) {
9354 Sema::CodeSynthesisContext Ctx;
9355 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9356 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9357 Ctx.Entity = Spaceship;
9358 pushCodeSynthesisContext(Ctx);
9359
9360 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9361 EqualEqual->setImplicit();
9362
9363 popCodeSynthesisContext();
9364}
9365
9366void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9367 DefaultedComparisonKind DCK) {
9368 assert(FD->isDefaulted() && !FD->isDeleted() &&
9369 !FD->doesThisDeclarationHaveABody());
9370 if (FD->willHaveBody() || FD->isInvalidDecl())
9371 return;
9372
9373 SynthesizedFunctionScope Scope(*this, FD);
9374
9375 // Add a context note for diagnostics produced after this point.
9376 Scope.addContextNote(UseLoc);
9377
9378 {
9379 // Build and set up the function body.
9380 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9381 // the type of the class being compared.
9382 auto PT = FD->getParamDecl(i: 0)->getType();
9383 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9384 SourceLocation BodyLoc =
9385 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9386 StmtResult Body =
9387 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9388 if (Body.isInvalid()) {
9389 FD->setInvalidDecl();
9390 return;
9391 }
9392 FD->setBody(Body.get());
9393 FD->markUsed(C&: Context);
9394 }
9395
9396 // The exception specification is needed because we are defining the
9397 // function. Note that this will reuse the body we just built.
9398 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9399
9400 if (ASTMutationListener *L = getASTMutationListener())
9401 L->CompletedImplicitDefinition(D: FD);
9402}
9403
9404static Sema::ImplicitExceptionSpecification
9405ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9406 FunctionDecl *FD,
9407 Sema::DefaultedComparisonKind DCK) {
9408 ComputingExceptionSpec CES(S, FD, Loc);
9409 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9410
9411 if (FD->isInvalidDecl())
9412 return ExceptSpec;
9413
9414 // The common case is that we just defined the comparison function. In that
9415 // case, just look at whether the body can throw.
9416 if (FD->hasBody()) {
9417 ExceptSpec.CalledStmt(S: FD->getBody());
9418 } else {
9419 // Otherwise, build a body so we can check it. This should ideally only
9420 // happen when we're not actually marking the function referenced. (This is
9421 // only really important for efficiency: we don't want to build and throw
9422 // away bodies for comparison functions more than we strictly need to.)
9423
9424 // Pretend to synthesize the function body in an unevaluated context.
9425 // Note that we can't actually just go ahead and define the function here:
9426 // we are not permitted to mark its callees as referenced.
9427 Sema::SynthesizedFunctionScope Scope(S, FD);
9428 EnterExpressionEvaluationContext Context(
9429 S, Sema::ExpressionEvaluationContext::Unevaluated);
9430
9431 CXXRecordDecl *RD =
9432 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9433 ? FD->getDeclContext()
9434 : FD->getLexicalDeclContext());
9435 SourceLocation BodyLoc =
9436 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9437 StmtResult Body =
9438 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9439 if (!Body.isInvalid())
9440 ExceptSpec.CalledStmt(S: Body.get());
9441
9442 // FIXME: Can we hold onto this body and just transform it to potentially
9443 // evaluated when we're asked to define the function rather than rebuilding
9444 // it? Either that, or we should only build the bits of the body that we
9445 // need (the expressions, not the statements).
9446 }
9447
9448 return ExceptSpec;
9449}
9450
9451void Sema::CheckDelayedMemberExceptionSpecs() {
9452 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9453 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9454
9455 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9456 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9457
9458 // Perform any deferred checking of exception specifications for virtual
9459 // destructors.
9460 for (auto &Check : Overriding)
9461 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9462
9463 // Perform any deferred checking of exception specifications for befriended
9464 // special members.
9465 for (auto &Check : Equivalent)
9466 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9467}
9468
9469namespace {
9470/// CRTP base class for visiting operations performed by a special member
9471/// function (or inherited constructor).
9472template<typename Derived>
9473struct SpecialMemberVisitor {
9474 Sema &S;
9475 CXXMethodDecl *MD;
9476 CXXSpecialMemberKind CSM;
9477 Sema::InheritedConstructorInfo *ICI;
9478
9479 // Properties of the special member, computed for convenience.
9480 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9481
9482 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9483 Sema::InheritedConstructorInfo *ICI)
9484 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9485 switch (CSM) {
9486 case CXXSpecialMemberKind::DefaultConstructor:
9487 case CXXSpecialMemberKind::CopyConstructor:
9488 case CXXSpecialMemberKind::MoveConstructor:
9489 IsConstructor = true;
9490 break;
9491 case CXXSpecialMemberKind::CopyAssignment:
9492 case CXXSpecialMemberKind::MoveAssignment:
9493 IsAssignment = true;
9494 break;
9495 case CXXSpecialMemberKind::Destructor:
9496 break;
9497 case CXXSpecialMemberKind::Invalid:
9498 llvm_unreachable("invalid special member kind");
9499 }
9500
9501 if (MD->getNumExplicitParams()) {
9502 if (const ReferenceType *RT =
9503 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9504 ConstArg = RT->getPointeeType().isConstQualified();
9505 }
9506 }
9507
9508 Derived &getDerived() { return static_cast<Derived&>(*this); }
9509
9510 /// Is this a "move" special member?
9511 bool isMove() const {
9512 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9513 CSM == CXXSpecialMemberKind::MoveAssignment;
9514 }
9515
9516 /// Look up the corresponding special member in the given class.
9517 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9518 unsigned Quals, bool IsMutable) {
9519 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9520 ConstRHS: ConstArg && !IsMutable);
9521 }
9522
9523 /// Look up the constructor for the specified base class to see if it's
9524 /// overridden due to this being an inherited constructor.
9525 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9526 if (!ICI)
9527 return {};
9528 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9529 auto *BaseCtor =
9530 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9531 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9532 return MD;
9533 return {};
9534 }
9535
9536 /// A base or member subobject.
9537 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9538
9539 /// Get the location to use for a subobject in diagnostics.
9540 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9541 // FIXME: For an indirect virtual base, the direct base leading to
9542 // the indirect virtual base would be a more useful choice.
9543 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9544 return B->getBaseTypeLoc();
9545 else
9546 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9547 }
9548
9549 enum BasesToVisit {
9550 /// Visit all non-virtual (direct) bases.
9551 VisitNonVirtualBases,
9552 /// Visit all direct bases, virtual or not.
9553 VisitDirectBases,
9554 /// Visit all non-virtual bases, and all virtual bases if the class
9555 /// is not abstract.
9556 VisitPotentiallyConstructedBases,
9557 /// Visit all direct or virtual bases.
9558 VisitAllBases
9559 };
9560
9561 // Visit the bases and members of the class.
9562 bool visit(BasesToVisit Bases) {
9563 CXXRecordDecl *RD = MD->getParent();
9564
9565 if (Bases == VisitPotentiallyConstructedBases)
9566 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9567
9568 for (auto &B : RD->bases())
9569 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9570 getDerived().visitBase(&B))
9571 return true;
9572
9573 if (Bases == VisitAllBases)
9574 for (auto &B : RD->vbases())
9575 if (getDerived().visitBase(&B))
9576 return true;
9577
9578 for (auto *F : RD->fields())
9579 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9580 getDerived().visitField(F))
9581 return true;
9582
9583 return false;
9584 }
9585};
9586}
9587
9588namespace {
9589struct SpecialMemberDeletionInfo
9590 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9591 bool Diagnose;
9592
9593 SourceLocation Loc;
9594
9595 bool AllFieldsAreConst;
9596
9597 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9598 CXXSpecialMemberKind CSM,
9599 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9600 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9601 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9602
9603 bool inUnion() const { return MD->getParent()->isUnion(); }
9604
9605 CXXSpecialMemberKind getEffectiveCSM() {
9606 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9607 }
9608
9609 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9610
9611 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9612
9613 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9614 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9615
9616 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9617 bool shouldDeleteForField(FieldDecl *FD);
9618 bool shouldDeleteForAllConstMembers();
9619
9620 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9621 unsigned Quals);
9622 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9623 Sema::SpecialMemberOverloadResult SMOR,
9624 bool IsDtorCallInCtor);
9625
9626 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9627};
9628}
9629
9630/// Is the given special member inaccessible when used on the given
9631/// sub-object.
9632bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9633 CXXMethodDecl *target) {
9634 /// If we're operating on a base class, the object type is the
9635 /// type of this special member.
9636 CanQualType objectTy;
9637 AccessSpecifier access = target->getAccess();
9638 if (CXXBaseSpecifier *base = Subobj.dyn_cast<CXXBaseSpecifier*>()) {
9639 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9640 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9641
9642 // If we're operating on a field, the object type is the type of the field.
9643 } else {
9644 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9645 }
9646
9647 return S.isMemberAccessibleForDeletion(
9648 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9649}
9650
9651/// Check whether we should delete a special member due to the implicit
9652/// definition containing a call to a special member of a subobject.
9653bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9654 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9655 bool IsDtorCallInCtor) {
9656 CXXMethodDecl *Decl = SMOR.getMethod();
9657 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9658
9659 enum {
9660 NotSet = -1,
9661 NoDecl,
9662 DeletedDecl,
9663 MultipleDecl,
9664 InaccessibleDecl,
9665 NonTrivialDecl
9666 } DiagKind = NotSet;
9667
9668 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9669 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9670 Field->getParent()->isUnion()) {
9671 // [class.default.ctor]p2:
9672 // A defaulted default constructor for class X is defined as deleted if
9673 // - X is a union that has a variant member with a non-trivial default
9674 // constructor and no variant member of X has a default member
9675 // initializer
9676 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9677 if (RD->hasInClassInitializer())
9678 return false;
9679 }
9680 DiagKind = !Decl ? NoDecl : DeletedDecl;
9681 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9682 DiagKind = MultipleDecl;
9683 else if (!isAccessible(Subobj, target: Decl))
9684 DiagKind = InaccessibleDecl;
9685 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9686 !Decl->isTrivial()) {
9687 // A member of a union must have a trivial corresponding special member.
9688 // As a weird special case, a destructor call from a union's constructor
9689 // must be accessible and non-deleted, but need not be trivial. Such a
9690 // destructor is never actually called, but is semantically checked as
9691 // if it were.
9692 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9693 // [class.default.ctor]p2:
9694 // A defaulted default constructor for class X is defined as deleted if
9695 // - X is a union that has a variant member with a non-trivial default
9696 // constructor and no variant member of X has a default member
9697 // initializer
9698 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9699 if (!RD->hasInClassInitializer())
9700 DiagKind = NonTrivialDecl;
9701 } else {
9702 DiagKind = NonTrivialDecl;
9703 }
9704 }
9705
9706 if (DiagKind == NotSet)
9707 return false;
9708
9709 if (Diagnose) {
9710 if (Field) {
9711 S.Diag(Loc: Field->getLocation(),
9712 DiagID: diag::note_deleted_special_member_class_subobject)
9713 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9714 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9715 } else {
9716 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9717 S.Diag(Loc: Base->getBeginLoc(),
9718 DiagID: diag::note_deleted_special_member_class_subobject)
9719 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9720 << Base->getType() << DiagKind << IsDtorCallInCtor
9721 << /*IsObjCPtr*/ false;
9722 }
9723
9724 if (DiagKind == DeletedDecl)
9725 S.NoteDeletedFunction(FD: Decl);
9726 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9727 }
9728
9729 return true;
9730}
9731
9732/// Check whether we should delete a special member function due to having a
9733/// direct or virtual base class or non-static data member of class type M.
9734bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9735 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9736 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
9737 bool IsMutable = Field && Field->isMutable();
9738
9739 // C++11 [class.ctor]p5:
9740 // -- any direct or virtual base class, or non-static data member with no
9741 // brace-or-equal-initializer, has class type M (or array thereof) and
9742 // either M has no default constructor or overload resolution as applied
9743 // to M's default constructor results in an ambiguity or in a function
9744 // that is deleted or inaccessible
9745 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9746 // -- a direct or virtual base class B that cannot be copied/moved because
9747 // overload resolution, as applied to B's corresponding special member,
9748 // results in an ambiguity or a function that is deleted or inaccessible
9749 // from the defaulted special member
9750 // C++11 [class.dtor]p5:
9751 // -- any direct or virtual base class [...] has a type with a destructor
9752 // that is deleted or inaccessible
9753 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9754 Field->hasInClassInitializer()) &&
9755 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9756 IsDtorCallInCtor: false))
9757 return true;
9758
9759 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9760 // -- any direct or virtual base class or non-static data member has a
9761 // type with a destructor that is deleted or inaccessible
9762 if (IsConstructor) {
9763 Sema::SpecialMemberOverloadResult SMOR =
9764 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9765 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9766 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9767 return true;
9768 }
9769
9770 return false;
9771}
9772
9773bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9774 FieldDecl *FD, QualType FieldType) {
9775 // The defaulted special functions are defined as deleted if this is a variant
9776 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9777 // type under ARC.
9778 if (!FieldType.hasNonTrivialObjCLifetime())
9779 return false;
9780
9781 // Don't make the defaulted default constructor defined as deleted if the
9782 // member has an in-class initializer.
9783 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9784 FD->hasInClassInitializer())
9785 return false;
9786
9787 if (Diagnose) {
9788 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9789 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9790 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9791 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9792 }
9793
9794 return true;
9795}
9796
9797bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9798 const FieldDecl *FD) {
9799 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9800 // Copy/move constructors/assignment operators are deleted if the field has an
9801 // address-discriminated ptrauth qualifier.
9802 PointerAuthQualifier Q = FieldType.getPointerAuth();
9803
9804 if (!Q || !Q.isAddressDiscriminated())
9805 return false;
9806
9807 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9808 CSM == CXXSpecialMemberKind::Destructor)
9809 return false;
9810
9811 if (Diagnose) {
9812 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9813 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9814 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9815 << /*IsDtorCallInCtor*/ false << 2;
9816 }
9817
9818 return true;
9819}
9820
9821/// Check whether we should delete a special member function due to the class
9822/// having a particular direct or virtual base class.
9823bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9824 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9825 // If program is correct, BaseClass cannot be null, but if it is, the error
9826 // must be reported elsewhere.
9827 if (!BaseClass)
9828 return false;
9829 // If we have an inheriting constructor, check whether we're calling an
9830 // inherited constructor instead of a default constructor.
9831 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9832 if (auto *BaseCtor = SMOR.getMethod()) {
9833 // Note that we do not check access along this path; other than that,
9834 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9835 // FIXME: Check that the base has a usable destructor! Sink this into
9836 // shouldDeleteForClassSubobject.
9837 if (BaseCtor->isDeleted() && Diagnose) {
9838 S.Diag(Loc: Base->getBeginLoc(),
9839 DiagID: diag::note_deleted_special_member_class_subobject)
9840 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9841 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9842 << /*IsObjCPtr*/ false;
9843 S.NoteDeletedFunction(FD: BaseCtor);
9844 }
9845 return BaseCtor->isDeleted();
9846 }
9847 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9848}
9849
9850/// Check whether we should delete a special member function due to the class
9851/// having a particular non-static data member.
9852bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9853 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9854 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9855
9856 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9857 return true;
9858
9859 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9860 return true;
9861
9862 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9863 // For a default constructor, all references must be initialized in-class
9864 // and, if a union, it must have a non-const member.
9865 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9866 if (Diagnose)
9867 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9868 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9869 return true;
9870 }
9871 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9872 // data member of const-qualified type (or array thereof) with no
9873 // brace-or-equal-initializer is not const-default-constructible.
9874 if (!inUnion() && FieldType.isConstQualified() &&
9875 !FD->hasInClassInitializer() &&
9876 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9877 if (Diagnose)
9878 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9879 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9880 return true;
9881 }
9882
9883 if (inUnion() && !FieldType.isConstQualified())
9884 AllFieldsAreConst = false;
9885 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9886 // For a copy constructor, data members must not be of rvalue reference
9887 // type.
9888 if (FieldType->isRValueReferenceType()) {
9889 if (Diagnose)
9890 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9891 << MD->getParent() << FD << FieldType;
9892 return true;
9893 }
9894 } else if (IsAssignment) {
9895 // For an assignment operator, data members must not be of reference type.
9896 if (FieldType->isReferenceType()) {
9897 if (Diagnose)
9898 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9899 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9900 return true;
9901 }
9902 if (!FieldRecord && FieldType.isConstQualified()) {
9903 // C++11 [class.copy]p23:
9904 // -- a non-static data member of const non-class type (or array thereof)
9905 if (Diagnose)
9906 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9907 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9908 return true;
9909 }
9910 }
9911
9912 if (FieldRecord) {
9913 // Some additional restrictions exist on the variant members.
9914 if (!inUnion() && FieldRecord->isUnion() &&
9915 FieldRecord->isAnonymousStructOrUnion()) {
9916 bool AllVariantFieldsAreConst = true;
9917
9918 // FIXME: Handle anonymous unions declared within anonymous unions.
9919 for (auto *UI : FieldRecord->fields()) {
9920 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9921
9922 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9923 return true;
9924
9925 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9926 return true;
9927
9928 if (!UnionFieldType.isConstQualified())
9929 AllVariantFieldsAreConst = false;
9930
9931 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9932 if (UnionFieldRecord &&
9933 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9934 Quals: UnionFieldType.getCVRQualifiers()))
9935 return true;
9936 }
9937
9938 // At least one member in each anonymous union must be non-const
9939 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9940 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9941 if (Diagnose)
9942 S.Diag(Loc: FieldRecord->getLocation(),
9943 DiagID: diag::note_deleted_default_ctor_all_const)
9944 << !!ICI << MD->getParent() << /*anonymous union*/1;
9945 return true;
9946 }
9947
9948 // Don't check the implicit member of the anonymous union type.
9949 // This is technically non-conformant but supported, and we have a
9950 // diagnostic for this elsewhere.
9951 return false;
9952 }
9953
9954 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9955 Quals: FieldType.getCVRQualifiers()))
9956 return true;
9957 }
9958
9959 return false;
9960}
9961
9962/// C++11 [class.ctor] p5:
9963/// A defaulted default constructor for a class X is defined as deleted if
9964/// X is a union and all of its variant members are of const-qualified type.
9965bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9966 // This is a silly definition, because it gives an empty union a deleted
9967 // default constructor. Don't do that.
9968 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
9969 AllFieldsAreConst) {
9970 bool AnyFields = false;
9971 for (auto *F : MD->getParent()->fields())
9972 if ((AnyFields = !F->isUnnamedBitField()))
9973 break;
9974 if (!AnyFields)
9975 return false;
9976 if (Diagnose)
9977 S.Diag(Loc: MD->getParent()->getLocation(),
9978 DiagID: diag::note_deleted_default_ctor_all_const)
9979 << !!ICI << MD->getParent() << /*not anonymous union*/0;
9980 return true;
9981 }
9982 return false;
9983}
9984
9985/// Determine whether a defaulted special member function should be defined as
9986/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
9987/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
9988bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
9989 CXXSpecialMemberKind CSM,
9990 InheritedConstructorInfo *ICI,
9991 bool Diagnose) {
9992 if (MD->isInvalidDecl())
9993 return false;
9994 CXXRecordDecl *RD = MD->getParent();
9995 assert(!RD->isDependentType() && "do deletion after instantiation");
9996 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
9997 RD->isInvalidDecl())
9998 return false;
9999
10000 // C++11 [expr.lambda.prim]p19:
10001 // The closure type associated with a lambda-expression has a
10002 // deleted (8.4.3) default constructor and a deleted copy
10003 // assignment operator.
10004 // C++2a adds back these operators if the lambda has no lambda-capture.
10005 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
10006 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10007 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10008 if (Diagnose)
10009 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
10010 return true;
10011 }
10012
10013 // C++11 [class.copy]p7, p18:
10014 // If the class definition declares a move constructor or move assignment
10015 // operator, an implicitly declared copy constructor or copy assignment
10016 // operator is defined as deleted.
10017 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
10018 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10019 CXXMethodDecl *UserDeclaredMove = nullptr;
10020
10021 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10022 // deletion of the corresponding copy operation, not both copy operations.
10023 // MSVC 2015 has adopted the standards conforming behavior.
10024 bool DeletesOnlyMatchingCopy =
10025 getLangOpts().MSVCCompat &&
10026 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
10027
10028 if (RD->hasUserDeclaredMoveConstructor() &&
10029 (!DeletesOnlyMatchingCopy ||
10030 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10031 if (!Diagnose) return true;
10032
10033 // Find any user-declared move constructor.
10034 for (auto *I : RD->ctors()) {
10035 if (I->isMoveConstructor()) {
10036 UserDeclaredMove = I;
10037 break;
10038 }
10039 }
10040 assert(UserDeclaredMove);
10041 } else if (RD->hasUserDeclaredMoveAssignment() &&
10042 (!DeletesOnlyMatchingCopy ||
10043 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10044 if (!Diagnose) return true;
10045
10046 // Find any user-declared move assignment operator.
10047 for (auto *I : RD->methods()) {
10048 if (I->isMoveAssignmentOperator()) {
10049 UserDeclaredMove = I;
10050 break;
10051 }
10052 }
10053 assert(UserDeclaredMove);
10054 }
10055
10056 if (UserDeclaredMove) {
10057 Diag(Loc: UserDeclaredMove->getLocation(),
10058 DiagID: diag::note_deleted_copy_user_declared_move)
10059 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10060 << UserDeclaredMove->isMoveAssignmentOperator();
10061 return true;
10062 }
10063 }
10064
10065 // Do access control from the special member function
10066 ContextRAII MethodContext(*this, MD);
10067
10068 // C++11 [class.dtor]p5:
10069 // -- for a virtual destructor, lookup of the non-array deallocation function
10070 // results in an ambiguity or in a function that is deleted or inaccessible
10071 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10072 FunctionDecl *OperatorDelete = nullptr;
10073 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10074 DeclarationName Name =
10075 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10076 ImplicitDeallocationParameters IDP = {
10077 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10078 AlignedAllocationMode::No, SizedDeallocationMode::No};
10079 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10080 Operator&: OperatorDelete, IDP,
10081 /*Diagnose=*/false)) {
10082 if (Diagnose)
10083 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10084 return true;
10085 }
10086 }
10087
10088 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10089
10090 // Per DR1611, do not consider virtual bases of constructors of abstract
10091 // classes, since we are not going to construct them.
10092 // Per DR1658, do not consider virtual bases of destructors of abstract
10093 // classes either.
10094 // Per DR2180, for assignment operators we only assign (and thus only
10095 // consider) direct bases.
10096 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10097 : SMI.VisitPotentiallyConstructedBases))
10098 return true;
10099
10100 if (SMI.shouldDeleteForAllConstMembers())
10101 return true;
10102
10103 if (getLangOpts().CUDA) {
10104 // We should delete the special member in CUDA mode if target inference
10105 // failed.
10106 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10107 // is treated as certain special member, which may not reflect what special
10108 // member MD really is. However inferTargetForImplicitSpecialMember
10109 // expects CSM to match MD, therefore recalculate CSM.
10110 assert(ICI || CSM == getSpecialMember(MD));
10111 auto RealCSM = CSM;
10112 if (ICI)
10113 RealCSM = getSpecialMember(MD);
10114
10115 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10116 ConstRHS: SMI.ConstArg, Diagnose);
10117 }
10118
10119 return false;
10120}
10121
10122void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10123 DefaultedFunctionKind DFK = getDefaultedFunctionKind(FD);
10124 assert(DFK && "not a defaultable function");
10125 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10126
10127 if (DFK.isSpecialMember()) {
10128 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10129 ICI: nullptr, /*Diagnose=*/true);
10130 } else {
10131 DefaultedComparisonAnalyzer(
10132 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10133 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10134 .visit();
10135 }
10136}
10137
10138/// Perform lookup for a special member of the specified kind, and determine
10139/// whether it is trivial. If the triviality can be determined without the
10140/// lookup, skip it. This is intended for use when determining whether a
10141/// special member of a containing object is trivial, and thus does not ever
10142/// perform overload resolution for default constructors.
10143///
10144/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10145/// member that was most likely to be intended to be trivial, if any.
10146///
10147/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10148/// determine whether the special member is trivial.
10149static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10150 CXXSpecialMemberKind CSM, unsigned Quals,
10151 bool ConstRHS, TrivialABIHandling TAH,
10152 CXXMethodDecl **Selected) {
10153 if (Selected)
10154 *Selected = nullptr;
10155
10156 switch (CSM) {
10157 case CXXSpecialMemberKind::Invalid:
10158 llvm_unreachable("not a special member");
10159
10160 case CXXSpecialMemberKind::DefaultConstructor:
10161 // C++11 [class.ctor]p5:
10162 // A default constructor is trivial if:
10163 // - all the [direct subobjects] have trivial default constructors
10164 //
10165 // Note, no overload resolution is performed in this case.
10166 if (RD->hasTrivialDefaultConstructor())
10167 return true;
10168
10169 if (Selected) {
10170 // If there's a default constructor which could have been trivial, dig it
10171 // out. Otherwise, if there's any user-provided default constructor, point
10172 // to that as an example of why there's not a trivial one.
10173 CXXConstructorDecl *DefCtor = nullptr;
10174 if (RD->needsImplicitDefaultConstructor())
10175 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10176 for (auto *CI : RD->ctors()) {
10177 if (!CI->isDefaultConstructor())
10178 continue;
10179 DefCtor = CI;
10180 if (!DefCtor->isUserProvided())
10181 break;
10182 }
10183
10184 *Selected = DefCtor;
10185 }
10186
10187 return false;
10188
10189 case CXXSpecialMemberKind::Destructor:
10190 // C++11 [class.dtor]p5:
10191 // A destructor is trivial if:
10192 // - all the direct [subobjects] have trivial destructors
10193 if (RD->hasTrivialDestructor() ||
10194 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10195 RD->hasTrivialDestructorForCall()))
10196 return true;
10197
10198 if (Selected) {
10199 if (RD->needsImplicitDestructor())
10200 S.DeclareImplicitDestructor(ClassDecl: RD);
10201 *Selected = RD->getDestructor();
10202 }
10203
10204 return false;
10205
10206 case CXXSpecialMemberKind::CopyConstructor:
10207 // C++11 [class.copy]p12:
10208 // A copy constructor is trivial if:
10209 // - the constructor selected to copy each direct [subobject] is trivial
10210 if (RD->hasTrivialCopyConstructor() ||
10211 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10212 RD->hasTrivialCopyConstructorForCall())) {
10213 if (Quals == Qualifiers::Const)
10214 // We must either select the trivial copy constructor or reach an
10215 // ambiguity; no need to actually perform overload resolution.
10216 return true;
10217 } else if (!Selected) {
10218 return false;
10219 }
10220 // In C++98, we are not supposed to perform overload resolution here, but we
10221 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10222 // cases like B as having a non-trivial copy constructor:
10223 // struct A { template<typename T> A(T&); };
10224 // struct B { mutable A a; };
10225 goto NeedOverloadResolution;
10226
10227 case CXXSpecialMemberKind::CopyAssignment:
10228 // C++11 [class.copy]p25:
10229 // A copy assignment operator is trivial if:
10230 // - the assignment operator selected to copy each direct [subobject] is
10231 // trivial
10232 if (RD->hasTrivialCopyAssignment()) {
10233 if (Quals == Qualifiers::Const)
10234 return true;
10235 } else if (!Selected) {
10236 return false;
10237 }
10238 // In C++98, we are not supposed to perform overload resolution here, but we
10239 // treat that as a language defect.
10240 goto NeedOverloadResolution;
10241
10242 case CXXSpecialMemberKind::MoveConstructor:
10243 case CXXSpecialMemberKind::MoveAssignment:
10244 NeedOverloadResolution:
10245 Sema::SpecialMemberOverloadResult SMOR =
10246 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10247
10248 // The standard doesn't describe how to behave if the lookup is ambiguous.
10249 // We treat it as not making the member non-trivial, just like the standard
10250 // mandates for the default constructor. This should rarely matter, because
10251 // the member will also be deleted.
10252 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10253 return true;
10254
10255 if (!SMOR.getMethod()) {
10256 assert(SMOR.getKind() ==
10257 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10258 return false;
10259 }
10260
10261 // We deliberately don't check if we found a deleted special member. We're
10262 // not supposed to!
10263 if (Selected)
10264 *Selected = SMOR.getMethod();
10265
10266 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10267 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10268 CSM == CXXSpecialMemberKind::MoveConstructor))
10269 return SMOR.getMethod()->isTrivialForCall();
10270 return SMOR.getMethod()->isTrivial();
10271 }
10272
10273 llvm_unreachable("unknown special method kind");
10274}
10275
10276static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10277 for (auto *CI : RD->ctors())
10278 if (!CI->isImplicit())
10279 return CI;
10280
10281 // Look for constructor templates.
10282 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10283 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10284 if (CXXConstructorDecl *CD =
10285 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10286 return CD;
10287 }
10288
10289 return nullptr;
10290}
10291
10292/// The kind of subobject we are checking for triviality. The values of this
10293/// enumeration are used in diagnostics.
10294enum TrivialSubobjectKind {
10295 /// The subobject is a base class.
10296 TSK_BaseClass,
10297 /// The subobject is a non-static data member.
10298 TSK_Field,
10299 /// The object is actually the complete object.
10300 TSK_CompleteObject
10301};
10302
10303/// Check whether the special member selected for a given type would be trivial.
10304static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10305 QualType SubType, bool ConstRHS,
10306 CXXSpecialMemberKind CSM,
10307 TrivialSubobjectKind Kind,
10308 TrivialABIHandling TAH, bool Diagnose) {
10309 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10310 if (!SubRD)
10311 return true;
10312
10313 CXXMethodDecl *Selected;
10314 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10315 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10316 return true;
10317
10318 if (Diagnose) {
10319 if (ConstRHS)
10320 SubType.addConst();
10321
10322 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10323 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10324 << Kind << SubType.getUnqualifiedType();
10325 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10326 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10327 } else if (!Selected)
10328 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10329 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10330 else if (Selected->isUserProvided()) {
10331 if (Kind == TSK_CompleteObject)
10332 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10333 << Kind << SubType.getUnqualifiedType() << CSM;
10334 else {
10335 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10336 << Kind << SubType.getUnqualifiedType() << CSM;
10337 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10338 }
10339 } else {
10340 if (Kind != TSK_CompleteObject)
10341 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10342 << Kind << SubType.getUnqualifiedType() << CSM;
10343
10344 // Explain why the defaulted or deleted special member isn't trivial.
10345 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10346 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10347 }
10348 }
10349
10350 return false;
10351}
10352
10353/// Check whether the members of a class type allow a special member to be
10354/// trivial.
10355static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10356 CXXSpecialMemberKind CSM, bool ConstArg,
10357 TrivialABIHandling TAH, bool Diagnose) {
10358 for (const auto *FI : RD->fields()) {
10359 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10360 continue;
10361
10362 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10363
10364 // Pretend anonymous struct or union members are members of this class.
10365 if (FI->isAnonymousStructOrUnion()) {
10366 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10367 CSM, ConstArg, TAH, Diagnose))
10368 return false;
10369 continue;
10370 }
10371
10372 // C++11 [class.ctor]p5:
10373 // A default constructor is trivial if [...]
10374 // -- no non-static data member of its class has a
10375 // brace-or-equal-initializer
10376 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10377 FI->hasInClassInitializer()) {
10378 if (Diagnose)
10379 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10380 << FI;
10381 return false;
10382 }
10383
10384 // Objective C ARC 4.3.5:
10385 // [...] nontrivally ownership-qualified types are [...] not trivially
10386 // default constructible, copy constructible, move constructible, copy
10387 // assignable, move assignable, or destructible [...]
10388 if (FieldType.hasNonTrivialObjCLifetime()) {
10389 if (Diagnose)
10390 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10391 << RD << FieldType.getObjCLifetime();
10392 return false;
10393 }
10394
10395 bool ConstRHS = ConstArg && !FI->isMutable();
10396 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10397 CSM, Kind: TSK_Field, TAH, Diagnose))
10398 return false;
10399 }
10400
10401 return true;
10402}
10403
10404void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10405 CXXSpecialMemberKind CSM) {
10406 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10407
10408 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10409 CSM == CXXSpecialMemberKind::CopyAssignment);
10410 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10411 Kind: TSK_CompleteObject,
10412 TAH: TrivialABIHandling::IgnoreTrivialABI,
10413 /*Diagnose*/ true);
10414}
10415
10416bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10417 TrivialABIHandling TAH, bool Diagnose) {
10418 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10419 "not special enough");
10420
10421 CXXRecordDecl *RD = MD->getParent();
10422
10423 bool ConstArg = false;
10424
10425 // C++11 [class.copy]p12, p25: [DR1593]
10426 // A [special member] is trivial if [...] its parameter-type-list is
10427 // equivalent to the parameter-type-list of an implicit declaration [...]
10428 switch (CSM) {
10429 case CXXSpecialMemberKind::DefaultConstructor:
10430 case CXXSpecialMemberKind::Destructor:
10431 // Trivial default constructors and destructors cannot have parameters.
10432 break;
10433
10434 case CXXSpecialMemberKind::CopyConstructor:
10435 case CXXSpecialMemberKind::CopyAssignment: {
10436 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10437 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10438
10439 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10440 // if they are not user-provided and their parameter-type-list is equivalent
10441 // to the parameter-type-list of an implicit declaration. This maintains the
10442 // behavior before dr2171 was implemented.
10443 //
10444 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10445 // trivial, if they are not user-provided, regardless of the qualifiers on
10446 // the reference type.
10447 const bool ClangABICompat14 =
10448 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver14);
10449 if (!RT ||
10450 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10451 ClangABICompat14)) {
10452 if (Diagnose)
10453 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10454 << Param0->getSourceRange() << Param0->getType()
10455 << Context.getLValueReferenceType(
10456 T: Context.getCanonicalTagType(TD: RD).withConst());
10457 return false;
10458 }
10459
10460 ConstArg = RT->getPointeeType().isConstQualified();
10461 break;
10462 }
10463
10464 case CXXSpecialMemberKind::MoveConstructor:
10465 case CXXSpecialMemberKind::MoveAssignment: {
10466 // Trivial move operations always have non-cv-qualified parameters.
10467 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10468 const RValueReferenceType *RT =
10469 Param0->getType()->getAs<RValueReferenceType>();
10470 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10471 if (Diagnose)
10472 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10473 << Param0->getSourceRange() << Param0->getType()
10474 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10475 return false;
10476 }
10477 break;
10478 }
10479
10480 case CXXSpecialMemberKind::Invalid:
10481 llvm_unreachable("not a special member");
10482 }
10483
10484 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10485 if (Diagnose)
10486 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10487 DiagID: diag::note_nontrivial_default_arg)
10488 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10489 return false;
10490 }
10491 if (MD->isVariadic()) {
10492 if (Diagnose)
10493 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10494 return false;
10495 }
10496
10497 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10498 // A copy/move [constructor or assignment operator] is trivial if
10499 // -- the [member] selected to copy/move each direct base class subobject
10500 // is trivial
10501 //
10502 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10503 // A [default constructor or destructor] is trivial if
10504 // -- all the direct base classes have trivial [default constructors or
10505 // destructors]
10506 for (const auto &BI : RD->bases())
10507 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10508 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10509 return false;
10510
10511 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10512 // A copy/move [constructor or assignment operator] for a class X is
10513 // trivial if
10514 // -- for each non-static data member of X that is of class type (or array
10515 // thereof), the constructor selected to copy/move that member is
10516 // trivial
10517 //
10518 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10519 // A [default constructor or destructor] is trivial if
10520 // -- for all of the non-static data members of its class that are of class
10521 // type (or array thereof), each such class has a trivial [default
10522 // constructor or destructor]
10523 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10524 return false;
10525
10526 // C++11 [class.dtor]p5:
10527 // A destructor is trivial if [...]
10528 // -- the destructor is not virtual
10529 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10530 if (Diagnose)
10531 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10532 return false;
10533 }
10534
10535 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10536 // A [special member] for class X is trivial if [...]
10537 // -- class X has no virtual functions and no virtual base classes
10538 if (CSM != CXXSpecialMemberKind::Destructor &&
10539 MD->getParent()->isDynamicClass()) {
10540 if (!Diagnose)
10541 return false;
10542
10543 if (RD->getNumVBases()) {
10544 // Check for virtual bases. We already know that the corresponding
10545 // member in all bases is trivial, so vbases must all be direct.
10546 CXXBaseSpecifier &BS = *RD->vbases_begin();
10547 assert(BS.isVirtual());
10548 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10549 return false;
10550 }
10551
10552 // Must have a virtual method.
10553 for (const auto *MI : RD->methods()) {
10554 if (MI->isVirtual()) {
10555 SourceLocation MLoc = MI->getBeginLoc();
10556 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10557 return false;
10558 }
10559 }
10560
10561 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10562 }
10563
10564 // Looks like it's trivial!
10565 return true;
10566}
10567
10568namespace {
10569struct FindHiddenVirtualMethod {
10570 Sema *S;
10571 CXXMethodDecl *Method;
10572 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10573 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10574
10575private:
10576 /// Check whether any most overridden method from MD in Methods
10577 static bool CheckMostOverridenMethods(
10578 const CXXMethodDecl *MD,
10579 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10580 if (MD->size_overridden_methods() == 0)
10581 return Methods.count(Ptr: MD->getCanonicalDecl());
10582 for (const CXXMethodDecl *O : MD->overridden_methods())
10583 if (CheckMostOverridenMethods(MD: O, Methods))
10584 return true;
10585 return false;
10586 }
10587
10588public:
10589 /// Member lookup function that determines whether a given C++
10590 /// method overloads virtual methods in a base class without overriding any,
10591 /// to be used with CXXRecordDecl::lookupInBases().
10592 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10593 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10594 DeclarationName Name = Method->getDeclName();
10595 assert(Name.getNameKind() == DeclarationName::Identifier);
10596
10597 bool foundSameNameMethod = false;
10598 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10599 for (Path.Decls = BaseRecord->lookup(Name).begin();
10600 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10601 NamedDecl *D = *Path.Decls;
10602 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10603 MD = MD->getCanonicalDecl();
10604 foundSameNameMethod = true;
10605 // Interested only in hidden virtual methods.
10606 if (!MD->isVirtual())
10607 continue;
10608 // If the method we are checking overrides a method from its base
10609 // don't warn about the other overloaded methods. Clang deviates from
10610 // GCC by only diagnosing overloads of inherited virtual functions that
10611 // do not override any other virtual functions in the base. GCC's
10612 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10613 // function from a base class. These cases may be better served by a
10614 // warning (not specific to virtual functions) on call sites when the
10615 // call would select a different function from the base class, were it
10616 // visible.
10617 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10618 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10619 return true;
10620 // Collect the overload only if its hidden.
10621 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10622 overloadedMethods.push_back(Elt: MD);
10623 }
10624 }
10625
10626 if (foundSameNameMethod)
10627 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10628 in_end: overloadedMethods.end());
10629 return foundSameNameMethod;
10630 }
10631};
10632} // end anonymous namespace
10633
10634/// Add the most overridden methods from MD to Methods
10635static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10636 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10637 if (MD->size_overridden_methods() == 0)
10638 Methods.insert(Ptr: MD->getCanonicalDecl());
10639 else
10640 for (const CXXMethodDecl *O : MD->overridden_methods())
10641 AddMostOverridenMethods(MD: O, Methods);
10642}
10643
10644void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10645 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10646 if (!MD->getDeclName().isIdentifier())
10647 return;
10648
10649 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10650 /*bool RecordPaths=*/false,
10651 /*bool DetectVirtual=*/false);
10652 FindHiddenVirtualMethod FHVM;
10653 FHVM.Method = MD;
10654 FHVM.S = this;
10655
10656 // Keep the base methods that were overridden or introduced in the subclass
10657 // by 'using' in a set. A base method not in this set is hidden.
10658 CXXRecordDecl *DC = MD->getParent();
10659 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10660 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10661 ND = shad->getTargetDecl();
10662 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10663 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10664 }
10665
10666 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10667 OverloadedMethods = FHVM.OverloadedMethods;
10668}
10669
10670void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10671 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10672 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10673 PartialDiagnostic PD = PDiag(
10674 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10675 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10676 Diag(Loc: overloadedMD->getLocation(), PD);
10677 }
10678}
10679
10680void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10681 if (MD->isInvalidDecl())
10682 return;
10683
10684 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10685 return;
10686
10687 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10688 FindHiddenVirtualMethods(MD, OverloadedMethods);
10689 if (!OverloadedMethods.empty()) {
10690 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10691 << MD << (OverloadedMethods.size() > 1);
10692
10693 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10694 }
10695}
10696
10697void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10698 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10699 // No diagnostics if this is a template instantiation.
10700 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10701 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10702 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10703 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10704 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10705 }
10706 RD.dropAttr<TrivialABIAttr>();
10707 };
10708
10709 // Ill-formed if the struct has virtual functions.
10710 if (RD.isPolymorphic()) {
10711 PrintDiagAndRemoveAttr(1);
10712 return;
10713 }
10714
10715 for (const auto &B : RD.bases()) {
10716 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10717 // virtual base.
10718 if (!B.getType()->isDependentType() &&
10719 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10720 PrintDiagAndRemoveAttr(2);
10721 return;
10722 }
10723
10724 if (B.isVirtual()) {
10725 PrintDiagAndRemoveAttr(3);
10726 return;
10727 }
10728 }
10729
10730 for (const auto *FD : RD.fields()) {
10731 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10732 // non-trivial for the purpose of calls.
10733 QualType FT = FD->getType();
10734 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10735 PrintDiagAndRemoveAttr(4);
10736 return;
10737 }
10738
10739 // Ill-formed if the field is an address-discriminated value.
10740 if (FT.hasAddressDiscriminatedPointerAuth()) {
10741 PrintDiagAndRemoveAttr(6);
10742 return;
10743 }
10744
10745 if (const auto *RT =
10746 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10747 if (!RT->isDependentType() &&
10748 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10749 ->canPassInRegisters()) {
10750 PrintDiagAndRemoveAttr(5);
10751 return;
10752 }
10753 }
10754
10755 if (IsCXXTriviallyRelocatableType(RD))
10756 return;
10757
10758 // Ill-formed if the copy and move constructors are deleted.
10759 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10760 // If the type is dependent, then assume it might have
10761 // implicit copy or move ctor because we won't know yet at this point.
10762 if (RD.isDependentType())
10763 return true;
10764 if (RD.needsImplicitCopyConstructor() &&
10765 !RD.defaultedCopyConstructorIsDeleted())
10766 return true;
10767 if (RD.needsImplicitMoveConstructor() &&
10768 !RD.defaultedMoveConstructorIsDeleted())
10769 return true;
10770 for (const CXXConstructorDecl *CD : RD.ctors())
10771 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10772 return true;
10773 return false;
10774 };
10775
10776 if (!HasNonDeletedCopyOrMoveConstructor()) {
10777 PrintDiagAndRemoveAttr(0);
10778 return;
10779 }
10780}
10781
10782void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10783 CXXRecordDecl &RD) {
10784 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10785 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10786 return;
10787
10788 const CXXRecordDecl *PrimaryBase = &RD;
10789 if (PrimaryBase->hasAnyDependentBases())
10790 return;
10791
10792 while (1) {
10793 assert(PrimaryBase);
10794 const CXXRecordDecl *Base = nullptr;
10795 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10796 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10797 continue;
10798 Base = BasePtr.getType()->getAsCXXRecordDecl();
10799 break;
10800 }
10801 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10802 break;
10803 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10804 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10805 << &RD << Base;
10806 PrimaryBase = Base;
10807 }
10808
10809 if (!RD.isPolymorphic())
10810 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10811 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10812 << &RD;
10813}
10814
10815void Sema::ActOnFinishCXXMemberSpecification(
10816 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10817 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10818 if (!TagDecl)
10819 return;
10820
10821 AdjustDeclIfTemplate(Decl&: TagDecl);
10822
10823 for (const ParsedAttr &AL : AttrList) {
10824 if (AL.getKind() != ParsedAttr::AT_Visibility)
10825 continue;
10826 AL.setInvalid();
10827 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10828 }
10829
10830 ActOnFields(S, RecLoc: RLoc, TagDecl,
10831 Fields: llvm::ArrayRef(
10832 // strict aliasing violation!
10833 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10834 FieldCollector->getCurNumFields()),
10835 LBrac, RBrac, AttrList);
10836
10837 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10838}
10839
10840/// Find the equality comparison functions that should be implicitly declared
10841/// in a given class definition, per C++2a [class.compare.default]p3.
10842static void findImplicitlyDeclaredEqualityComparisons(
10843 ASTContext &Ctx, CXXRecordDecl *RD,
10844 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10845 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10846 if (!RD->lookup(Name: EqEq).empty())
10847 // Member operator== explicitly declared: no implicit operator==s.
10848 return;
10849
10850 // Traverse friends looking for an '==' or a '<=>'.
10851 for (FriendDecl *Friend : RD->friends()) {
10852 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10853 if (!FD) continue;
10854
10855 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10856 // Friend operator== explicitly declared: no implicit operator==s.
10857 Spaceships.clear();
10858 return;
10859 }
10860
10861 if (FD->getOverloadedOperator() == OO_Spaceship &&
10862 FD->isExplicitlyDefaulted())
10863 Spaceships.push_back(Elt: FD);
10864 }
10865
10866 // Look for members named 'operator<=>'.
10867 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10868 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10869 // Note that we could find a non-function here (either a function template
10870 // or a using-declaration). Neither case results in an implicit
10871 // 'operator=='.
10872 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10873 if (FD->isExplicitlyDefaulted())
10874 Spaceships.push_back(Elt: FD);
10875 }
10876}
10877
10878void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10879 // Don't add implicit special members to templated classes.
10880 // FIXME: This means unqualified lookups for 'operator=' within a class
10881 // template don't work properly.
10882 if (!ClassDecl->isDependentType()) {
10883 if (ClassDecl->needsImplicitDefaultConstructor()) {
10884 ++getASTContext().NumImplicitDefaultConstructors;
10885
10886 if (ClassDecl->hasInheritedConstructor())
10887 DeclareImplicitDefaultConstructor(ClassDecl);
10888 }
10889
10890 if (ClassDecl->needsImplicitCopyConstructor()) {
10891 ++getASTContext().NumImplicitCopyConstructors;
10892
10893 // If the properties or semantics of the copy constructor couldn't be
10894 // determined while the class was being declared, force a declaration
10895 // of it now.
10896 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10897 ClassDecl->hasInheritedConstructor())
10898 DeclareImplicitCopyConstructor(ClassDecl);
10899 // For the MS ABI we need to know whether the copy ctor is deleted. A
10900 // prerequisite for deleting the implicit copy ctor is that the class has
10901 // a move ctor or move assignment that is either user-declared or whose
10902 // semantics are inherited from a subobject. FIXME: We should provide a
10903 // more direct way for CodeGen to ask whether the constructor was deleted.
10904 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10905 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10906 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10907 ClassDecl->hasUserDeclaredMoveAssignment() ||
10908 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10909 DeclareImplicitCopyConstructor(ClassDecl);
10910 }
10911
10912 if (getLangOpts().CPlusPlus11 &&
10913 ClassDecl->needsImplicitMoveConstructor()) {
10914 ++getASTContext().NumImplicitMoveConstructors;
10915
10916 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10917 ClassDecl->hasInheritedConstructor())
10918 DeclareImplicitMoveConstructor(ClassDecl);
10919 }
10920
10921 if (ClassDecl->needsImplicitCopyAssignment()) {
10922 ++getASTContext().NumImplicitCopyAssignmentOperators;
10923
10924 // If we have a dynamic class, then the copy assignment operator may be
10925 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10926 // it shows up in the right place in the vtable and that we diagnose
10927 // problems with the implicit exception specification.
10928 if (ClassDecl->isDynamicClass() ||
10929 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10930 ClassDecl->hasInheritedAssignment())
10931 DeclareImplicitCopyAssignment(ClassDecl);
10932 }
10933
10934 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10935 ++getASTContext().NumImplicitMoveAssignmentOperators;
10936
10937 // Likewise for the move assignment operator.
10938 if (ClassDecl->isDynamicClass() ||
10939 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10940 ClassDecl->hasInheritedAssignment())
10941 DeclareImplicitMoveAssignment(ClassDecl);
10942 }
10943
10944 if (ClassDecl->needsImplicitDestructor()) {
10945 ++getASTContext().NumImplicitDestructors;
10946
10947 // If we have a dynamic class, then the destructor may be virtual, so we
10948 // have to declare the destructor immediately. This ensures that, e.g., it
10949 // shows up in the right place in the vtable and that we diagnose problems
10950 // with the implicit exception specification.
10951 if (ClassDecl->isDynamicClass() ||
10952 ClassDecl->needsOverloadResolutionForDestructor())
10953 DeclareImplicitDestructor(ClassDecl);
10954 }
10955 }
10956
10957 // C++2a [class.compare.default]p3:
10958 // If the member-specification does not explicitly declare any member or
10959 // friend named operator==, an == operator function is declared implicitly
10960 // for each defaulted three-way comparison operator function defined in
10961 // the member-specification
10962 // FIXME: Consider doing this lazily.
10963 // We do this during the initial parse for a class template, not during
10964 // instantiation, so that we can handle unqualified lookups for 'operator=='
10965 // when parsing the template.
10966 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
10967 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
10968 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
10969 Spaceships&: DefaultedSpaceships);
10970 for (auto *FD : DefaultedSpaceships)
10971 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
10972 }
10973}
10974
10975unsigned
10976Sema::ActOnReenterTemplateScope(Decl *D,
10977 llvm::function_ref<Scope *()> EnterScope) {
10978 if (!D)
10979 return 0;
10980 AdjustDeclIfTemplate(Decl&: D);
10981
10982 // In order to get name lookup right, reenter template scopes in order from
10983 // outermost to innermost.
10984 SmallVector<TemplateParameterList *, 4> ParameterLists;
10985 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
10986
10987 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
10988 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
10989 ParameterLists.push_back(Elt: TPL);
10990
10991 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
10992 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
10993 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
10994 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
10995 LookupDC = VD->getDeclContext();
10996
10997 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
10998 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
10999 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
11000 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11001 }
11002 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
11003 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11004 ParameterLists.push_back(Elt: TPL);
11005
11006 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
11007 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
11008 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
11009 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
11010 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11011 }
11012 }
11013 // FIXME: Alias declarations and concepts.
11014
11015 unsigned Count = 0;
11016 Scope *InnermostTemplateScope = nullptr;
11017 for (TemplateParameterList *Params : ParameterLists) {
11018 // Ignore explicit specializations; they don't contribute to the template
11019 // depth.
11020 if (Params->size() == 0)
11021 continue;
11022
11023 InnermostTemplateScope = EnterScope();
11024 for (NamedDecl *Param : *Params) {
11025 if (Param->getDeclName()) {
11026 InnermostTemplateScope->AddDecl(D: Param);
11027 IdResolver.AddDecl(D: Param);
11028 }
11029 }
11030 ++Count;
11031 }
11032
11033 // Associate the new template scopes with the corresponding entities.
11034 if (InnermostTemplateScope) {
11035 assert(LookupDC && "no enclosing DeclContext for template lookup");
11036 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11037 }
11038
11039 return Count;
11040}
11041
11042void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11043 if (!RecordD) return;
11044 AdjustDeclIfTemplate(Decl&: RecordD);
11045 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11046 PushDeclContext(S, DC: Record);
11047}
11048
11049void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11050 if (!RecordD) return;
11051 PopDeclContext();
11052}
11053
11054void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11055 if (!Param)
11056 return;
11057
11058 S->AddDecl(D: Param);
11059 if (Param->getDeclName())
11060 IdResolver.AddDecl(D: Param);
11061}
11062
11063void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11064}
11065
11066/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11067/// C++ method declaration. We're (re-)introducing the given
11068/// function parameter into scope for use in parsing later parts of
11069/// the method declaration. For example, we could see an
11070/// ActOnParamDefaultArgument event for this parameter.
11071void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11072 if (!ParamD)
11073 return;
11074
11075 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11076
11077 S->AddDecl(D: Param);
11078 if (Param->getDeclName())
11079 IdResolver.AddDecl(D: Param);
11080}
11081
11082void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11083 if (!MethodD)
11084 return;
11085
11086 AdjustDeclIfTemplate(Decl&: MethodD);
11087
11088 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11089
11090 // Now that we have our default arguments, check the constructor
11091 // again. It could produce additional diagnostics or affect whether
11092 // the class has implicitly-declared destructors, among other
11093 // things.
11094 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11095 CheckConstructor(Constructor);
11096
11097 // Check the default arguments, which we may have added.
11098 if (!Method->isInvalidDecl())
11099 CheckCXXDefaultArguments(FD: Method);
11100}
11101
11102// Emit the given diagnostic for each non-address-space qualifier.
11103// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11104static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11105 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11106 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11107 bool DiagOccurred = false;
11108 FTI.MethodQualifiers->forEachQualifier(
11109 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11110 SourceLocation SL) {
11111 // This diagnostic should be emitted on any qualifier except an addr
11112 // space qualifier. However, forEachQualifier currently doesn't visit
11113 // addr space qualifiers, so there's no way to write this condition
11114 // right now; we just diagnose on everything.
11115 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11116 DiagOccurred = true;
11117 });
11118 if (DiagOccurred)
11119 D.setInvalidType();
11120 }
11121}
11122
11123static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11124 unsigned Kind) {
11125 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11126 return;
11127
11128 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11129 if (Chunk.Kind == DeclaratorChunk::Paren ||
11130 Chunk.Kind == DeclaratorChunk::Function)
11131 return;
11132
11133 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11134 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11135 << Kind << Chunk.getSourceRange();
11136 D.setInvalidType();
11137}
11138
11139QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11140 StorageClass &SC) {
11141 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11142
11143 // C++ [class.ctor]p3:
11144 // A constructor shall not be virtual (10.3) or static (9.4). A
11145 // constructor can be invoked for a const, volatile or const
11146 // volatile object. A constructor shall not be declared const,
11147 // volatile, or const volatile (9.3.2).
11148 if (isVirtual) {
11149 if (!D.isInvalidType())
11150 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11151 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11152 << SourceRange(D.getIdentifierLoc());
11153 D.setInvalidType();
11154 }
11155 if (SC == SC_Static) {
11156 if (!D.isInvalidType())
11157 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11158 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11159 << SourceRange(D.getIdentifierLoc());
11160 D.setInvalidType();
11161 SC = SC_None;
11162 }
11163
11164 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11165 diagnoseIgnoredQualifiers(
11166 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11167 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11168 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11169 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11170 D.setInvalidType();
11171 }
11172
11173 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11174 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11175
11176 // C++0x [class.ctor]p4:
11177 // A constructor shall not be declared with a ref-qualifier.
11178 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11179 if (FTI.hasRefQualifier()) {
11180 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11181 << FTI.RefQualifierIsLValueRef
11182 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11183 D.setInvalidType();
11184 }
11185
11186 // Rebuild the function type "R" without any type qualifiers (in
11187 // case any of the errors above fired) and with "void" as the
11188 // return type, since constructors don't have return types.
11189 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11190 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11191 return R;
11192
11193 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11194 EPI.TypeQuals = Qualifiers();
11195 EPI.RefQualifier = RQ_None;
11196
11197 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11198}
11199
11200void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11201 CXXRecordDecl *ClassDecl
11202 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11203 if (!ClassDecl)
11204 return Constructor->setInvalidDecl();
11205
11206 // C++ [class.copy]p3:
11207 // A declaration of a constructor for a class X is ill-formed if
11208 // its first parameter is of type (optionally cv-qualified) X and
11209 // either there are no other parameters or else all other
11210 // parameters have default arguments.
11211 if (!Constructor->isInvalidDecl() &&
11212 Constructor->hasOneParamOrDefaultArgs() &&
11213 !Constructor->isFunctionTemplateSpecialization()) {
11214 CanQualType ParamType =
11215 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11216 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11217 if (ParamType == ClassTy) {
11218 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11219 const char *ConstRef
11220 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11221 : " const &";
11222 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11223 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11224
11225 // FIXME: Rather that making the constructor invalid, we should endeavor
11226 // to fix the type.
11227 Constructor->setInvalidDecl();
11228 }
11229 }
11230}
11231
11232bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11233 CXXRecordDecl *RD = Destructor->getParent();
11234
11235 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11236 SourceLocation Loc;
11237
11238 if (!Destructor->isImplicit())
11239 Loc = Destructor->getLocation();
11240 else
11241 Loc = RD->getLocation();
11242
11243 DeclarationName Name =
11244 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11245 // If we have a virtual destructor, look up the deallocation function
11246 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11247 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11248 Expr *ThisArg = nullptr;
11249
11250 // If the notional 'delete this' expression requires a non-trivial
11251 // conversion from 'this' to the type of a destroying operator delete's
11252 // first parameter, perform that conversion now.
11253 if (OperatorDelete->isDestroyingOperatorDelete()) {
11254 unsigned AddressParamIndex = 0;
11255 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11256 ++AddressParamIndex;
11257 QualType ParamType =
11258 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11259 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11260 // C++ [class.dtor]p13:
11261 // ... as if for the expression 'delete this' appearing in a
11262 // non-virtual destructor of the destructor's class.
11263 ContextRAII SwitchContext(*this, Destructor);
11264 ExprResult This = ActOnCXXThis(
11265 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11266 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11267 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11268 Action: AssignmentAction::Passing);
11269 if (This.isInvalid()) {
11270 // FIXME: Register this as a context note so that it comes out
11271 // in the right order.
11272 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11273 return true;
11274 }
11275 ThisArg = This.get();
11276 }
11277 }
11278
11279 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11280 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11281 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11282
11283 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11284 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11285 Context.getLangOpts())) {
11286 // In Microsoft ABI whenever a class has a defined operator delete,
11287 // scalar deleting destructors check the 3rd bit of the implicit
11288 // parameter and if it is set, then, global operator delete must be
11289 // called instead of the class-specific one. Find and save the global
11290 // operator delete for that case. Do not diagnose at this point because
11291 // the lack of a global operator delete is not an error if there are no
11292 // delete calls that require it.
11293 FunctionDecl *GlobalOperatorDelete =
11294 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11295 /*LookForGlobal*/ true, Name);
11296 if (GlobalOperatorDelete) {
11297 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11298 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11299 }
11300 }
11301
11302 if (Context.getTargetInfo().emitVectorDeletingDtors(
11303 Context.getLangOpts())) {
11304 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11305 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11306 DeclarationName VDeleteName =
11307 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11308 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11309 StartLoc: Loc, RD, /*Diagnose*/ false,
11310 /*LookForGlobal*/ false, Name: VDeleteName);
11311 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11312 FunctionDecl *GlobalArrOperatorDelete =
11313 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11314 /*LookForGlobal*/ true,
11315 Name: VDeleteName);
11316 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11317 if (GlobalArrOperatorDelete &&
11318 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11319 DestructorIsExported))
11320 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11321 } else if (!ArrOperatorDelete) {
11322 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11323 StartLoc: Loc, RD, /*Diagnose*/ false,
11324 /*LookForGlobal*/ true, Name: VDeleteName);
11325 }
11326 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11327 if (ArrOperatorDelete &&
11328 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11329 DestructorIsExported))
11330 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11331 }
11332 }
11333 }
11334
11335 return false;
11336}
11337
11338QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11339 StorageClass& SC) {
11340 // C++ [class.dtor]p1:
11341 // [...] A typedef-name that names a class is a class-name
11342 // (7.1.3); however, a typedef-name that names a class shall not
11343 // be used as the identifier in the declarator for a destructor
11344 // declaration.
11345 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11346 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11347 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11348 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11349 else if (const TemplateSpecializationType *TST =
11350 DeclaratorType->getAs<TemplateSpecializationType>())
11351 if (TST->isTypeAlias())
11352 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11353 << DeclaratorType << 1;
11354
11355 // C++ [class.dtor]p2:
11356 // A destructor is used to destroy objects of its class type. A
11357 // destructor takes no parameters, and no return type can be
11358 // specified for it (not even void). The address of a destructor
11359 // shall not be taken. A destructor shall not be static. A
11360 // destructor can be invoked for a const, volatile or const
11361 // volatile object. A destructor shall not be declared const,
11362 // volatile or const volatile (9.3.2).
11363 if (SC == SC_Static) {
11364 if (!D.isInvalidType())
11365 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11366 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11367 << SourceRange(D.getIdentifierLoc())
11368 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11369
11370 SC = SC_None;
11371 }
11372 if (!D.isInvalidType()) {
11373 // Destructors don't have return types, but the parser will
11374 // happily parse something like:
11375 //
11376 // class X {
11377 // float ~X();
11378 // };
11379 //
11380 // The return type will be eliminated later.
11381 if (D.getDeclSpec().hasTypeSpecifier())
11382 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11383 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11384 << SourceRange(D.getIdentifierLoc());
11385 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11386 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11387 FallbackLoc: SourceLocation(),
11388 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11389 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11390 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11391 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11392 D.setInvalidType();
11393 }
11394 }
11395
11396 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11397 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11398
11399 // C++0x [class.dtor]p2:
11400 // A destructor shall not be declared with a ref-qualifier.
11401 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11402 if (FTI.hasRefQualifier()) {
11403 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11404 << FTI.RefQualifierIsLValueRef
11405 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11406 D.setInvalidType();
11407 }
11408
11409 // Make sure we don't have any parameters.
11410 if (FTIHasNonVoidParameters(FTI)) {
11411 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11412
11413 // Delete the parameters.
11414 FTI.freeParams();
11415 D.setInvalidType();
11416 }
11417
11418 // Make sure the destructor isn't variadic.
11419 if (FTI.isVariadic) {
11420 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11421 D.setInvalidType();
11422 }
11423
11424 // Rebuild the function type "R" without any type qualifiers or
11425 // parameters (in case any of the errors above fired) and with
11426 // "void" as the return type, since destructors don't have return
11427 // types.
11428 if (!D.isInvalidType())
11429 return R;
11430
11431 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11432 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11433 EPI.Variadic = false;
11434 EPI.TypeQuals = Qualifiers();
11435 EPI.RefQualifier = RQ_None;
11436 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11437}
11438
11439static void extendLeft(SourceRange &R, SourceRange Before) {
11440 if (Before.isInvalid())
11441 return;
11442 R.setBegin(Before.getBegin());
11443 if (R.getEnd().isInvalid())
11444 R.setEnd(Before.getEnd());
11445}
11446
11447static void extendRight(SourceRange &R, SourceRange After) {
11448 if (After.isInvalid())
11449 return;
11450 if (R.getBegin().isInvalid())
11451 R.setBegin(After.getBegin());
11452 R.setEnd(After.getEnd());
11453}
11454
11455void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11456 StorageClass& SC) {
11457 // C++ [class.conv.fct]p1:
11458 // Neither parameter types nor return type can be specified. The
11459 // type of a conversion function (8.3.5) is "function taking no
11460 // parameter returning conversion-type-id."
11461 if (SC == SC_Static) {
11462 if (!D.isInvalidType())
11463 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11464 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11465 << D.getName().getSourceRange();
11466 D.setInvalidType();
11467 SC = SC_None;
11468 }
11469
11470 TypeSourceInfo *ConvTSI = nullptr;
11471 QualType ConvType =
11472 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11473
11474 const DeclSpec &DS = D.getDeclSpec();
11475 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11476 // Conversion functions don't have return types, but the parser will
11477 // happily parse something like:
11478 //
11479 // class X {
11480 // float operator bool();
11481 // };
11482 //
11483 // The return type will be changed later anyway.
11484 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11485 << SourceRange(DS.getTypeSpecTypeLoc())
11486 << SourceRange(D.getIdentifierLoc());
11487 D.setInvalidType();
11488 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11489 // It's also plausible that the user writes type qualifiers in the wrong
11490 // place, such as:
11491 // struct S { const operator int(); };
11492 // FIXME: we could provide a fixit to move the qualifiers onto the
11493 // conversion type.
11494 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11495 << SourceRange(D.getIdentifierLoc()) << 0;
11496 D.setInvalidType();
11497 }
11498 const auto *Proto = R->castAs<FunctionProtoType>();
11499 // Make sure we don't have any parameters.
11500 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11501 unsigned NumParam = Proto->getNumParams();
11502
11503 // [C++2b]
11504 // A conversion function shall have no non-object parameters.
11505 if (NumParam == 1) {
11506 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11507 if (const auto *First =
11508 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11509 First && First->isExplicitObjectParameter())
11510 NumParam--;
11511 }
11512
11513 if (NumParam != 0) {
11514 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11515 // Delete the parameters.
11516 FTI.freeParams();
11517 D.setInvalidType();
11518 } else if (Proto->isVariadic()) {
11519 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11520 D.setInvalidType();
11521 }
11522
11523 // Diagnose "&operator bool()" and other such nonsense. This
11524 // is actually a gcc extension which we don't support.
11525 if (Proto->getReturnType() != ConvType) {
11526 bool NeedsTypedef = false;
11527 SourceRange Before, After;
11528
11529 // Walk the chunks and extract information on them for our diagnostic.
11530 bool PastFunctionChunk = false;
11531 for (auto &Chunk : D.type_objects()) {
11532 switch (Chunk.Kind) {
11533 case DeclaratorChunk::Function:
11534 if (!PastFunctionChunk) {
11535 if (Chunk.Fun.HasTrailingReturnType) {
11536 TypeSourceInfo *TRT = nullptr;
11537 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11538 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11539 }
11540 PastFunctionChunk = true;
11541 break;
11542 }
11543 [[fallthrough]];
11544 case DeclaratorChunk::Array:
11545 NeedsTypedef = true;
11546 extendRight(R&: After, After: Chunk.getSourceRange());
11547 break;
11548
11549 case DeclaratorChunk::Pointer:
11550 case DeclaratorChunk::BlockPointer:
11551 case DeclaratorChunk::Reference:
11552 case DeclaratorChunk::MemberPointer:
11553 case DeclaratorChunk::Pipe:
11554 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11555 break;
11556
11557 case DeclaratorChunk::Paren:
11558 extendLeft(R&: Before, Before: Chunk.Loc);
11559 extendRight(R&: After, After: Chunk.EndLoc);
11560 break;
11561 }
11562 }
11563
11564 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11565 After.isValid() ? After.getBegin() :
11566 D.getIdentifierLoc();
11567 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11568 DB << Before << After;
11569
11570 if (!NeedsTypedef) {
11571 DB << /*don't need a typedef*/0;
11572
11573 // If we can provide a correct fix-it hint, do so.
11574 if (After.isInvalid() && ConvTSI) {
11575 SourceLocation InsertLoc =
11576 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11577 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11578 << FixItHint::CreateInsertionFromRange(
11579 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11580 << FixItHint::CreateRemoval(RemoveRange: Before);
11581 }
11582 } else if (!Proto->getReturnType()->isDependentType()) {
11583 DB << /*typedef*/1 << Proto->getReturnType();
11584 } else if (getLangOpts().CPlusPlus11) {
11585 DB << /*alias template*/2 << Proto->getReturnType();
11586 } else {
11587 DB << /*might not be fixable*/3;
11588 }
11589
11590 // Recover by incorporating the other type chunks into the result type.
11591 // Note, this does *not* change the name of the function. This is compatible
11592 // with the GCC extension:
11593 // struct S { &operator int(); } s;
11594 // int &r = s.operator int(); // ok in GCC
11595 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11596 ConvType = Proto->getReturnType();
11597 }
11598
11599 // C++ [class.conv.fct]p4:
11600 // The conversion-type-id shall not represent a function type nor
11601 // an array type.
11602 if (ConvType->isArrayType()) {
11603 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11604 ConvType = Context.getPointerType(T: ConvType);
11605 D.setInvalidType();
11606 } else if (ConvType->isFunctionType()) {
11607 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11608 ConvType = Context.getPointerType(T: ConvType);
11609 D.setInvalidType();
11610 }
11611
11612 // Rebuild the function type "R" without any parameters (in case any
11613 // of the errors above fired) and with the conversion type as the
11614 // return type.
11615 if (D.isInvalidType())
11616 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11617
11618 // C++0x explicit conversion operators.
11619 if (DS.hasExplicitSpecifier() && !getLangOpts().CPlusPlus20)
11620 Diag(Loc: DS.getExplicitSpecLoc(),
11621 DiagID: getLangOpts().CPlusPlus11
11622 ? diag::warn_cxx98_compat_explicit_conversion_functions
11623 : diag::ext_explicit_conversion_functions)
11624 << SourceRange(DS.getExplicitSpecRange());
11625}
11626
11627Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11628 assert(Conversion && "Expected to receive a conversion function declaration");
11629
11630 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11631
11632 // Make sure we aren't redeclaring the conversion function.
11633 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11634 // C++ [class.conv.fct]p1:
11635 // [...] A conversion function is never used to convert a
11636 // (possibly cv-qualified) object to the (possibly cv-qualified)
11637 // same object type (or a reference to it), to a (possibly
11638 // cv-qualified) base class of that type (or a reference to it),
11639 // or to (possibly cv-qualified) void.
11640 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11641 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11642 ConvType = ConvTypeRef->getPointeeType();
11643 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11644 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11645 /* Suppress diagnostics for instantiations. */;
11646 else if (Conversion->size_overridden_methods() != 0)
11647 /* Suppress diagnostics for overriding virtual function in a base class. */;
11648 else if (ConvType->isRecordType()) {
11649 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11650 if (ConvType == ClassType)
11651 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11652 << ClassType;
11653 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11654 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11655 << ClassType << ConvType;
11656 } else if (ConvType->isVoidType()) {
11657 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11658 << ClassType << ConvType;
11659 }
11660
11661 if (FunctionTemplateDecl *ConversionTemplate =
11662 Conversion->getDescribedFunctionTemplate()) {
11663 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11664 ConvType = ConvTypePtr->getPointeeType();
11665 }
11666 if (ConvType->isUndeducedAutoType()) {
11667 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11668 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11669 << ConvType->castAs<AutoType>()->getKeyword()
11670 << /* in declaration of conversion function template= */ 24;
11671 }
11672
11673 return ConversionTemplate;
11674 }
11675
11676 return Conversion;
11677}
11678
11679void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11680 DeclarationName Name, QualType R) {
11681 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11682}
11683
11684void Sema::CheckExplicitObjectLambda(Declarator &D) {
11685 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11686}
11687
11688void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11689 DeclarationName Name, QualType R,
11690 bool IsLambda, DeclContext *DC) {
11691 if (!D.isFunctionDeclarator())
11692 return;
11693
11694 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11695 if (FTI.NumParams == 0)
11696 return;
11697 ParmVarDecl *ExplicitObjectParam = nullptr;
11698 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11699 const auto &ParamInfo = FTI.Params[Idx];
11700 if (!ParamInfo.Param)
11701 continue;
11702 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11703 if (!Param->isExplicitObjectParameter())
11704 continue;
11705 if (Idx == 0) {
11706 ExplicitObjectParam = Param;
11707 continue;
11708 } else {
11709 Diag(Loc: Param->getLocation(),
11710 DiagID: diag::err_explicit_object_parameter_must_be_first)
11711 << IsLambda << Param->getSourceRange();
11712 }
11713 }
11714 if (!ExplicitObjectParam)
11715 return;
11716
11717 if (ExplicitObjectParam->hasDefaultArg()) {
11718 Diag(Loc: ExplicitObjectParam->getLocation(),
11719 DiagID: diag::err_explicit_object_default_arg)
11720 << ExplicitObjectParam->getSourceRange();
11721 D.setInvalidType();
11722 }
11723
11724 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11725 (D.getContext() == clang::DeclaratorContext::Member &&
11726 D.isStaticMember())) {
11727 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11728 DiagID: diag::err_explicit_object_parameter_nonmember)
11729 << D.getSourceRange() << /*static=*/0 << IsLambda;
11730 D.setInvalidType();
11731 }
11732
11733 if (D.getDeclSpec().isVirtualSpecified()) {
11734 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11735 DiagID: diag::err_explicit_object_parameter_nonmember)
11736 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11737 D.setInvalidType();
11738 }
11739
11740 // Friend declarations require some care. Consider:
11741 //
11742 // namespace N {
11743 // struct A{};
11744 // int f(A);
11745 // }
11746 //
11747 // struct S {
11748 // struct T {
11749 // int f(this T);
11750 // };
11751 //
11752 // friend int T::f(this T); // Allow this.
11753 // friend int f(this S); // But disallow this.
11754 // friend int N::f(this A); // And disallow this.
11755 // };
11756 //
11757 // Here, it seems to suffice to check whether the scope
11758 // specifier designates a class type.
11759 if (D.getDeclSpec().isFriendSpecified() &&
11760 !isa_and_present<CXXRecordDecl>(
11761 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11762 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11763 DiagID: diag::err_explicit_object_parameter_nonmember)
11764 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11765 D.setInvalidType();
11766 }
11767
11768 if (IsLambda && FTI.hasMutableQualifier()) {
11769 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11770 DiagID: diag::err_explicit_object_parameter_mutable)
11771 << D.getSourceRange();
11772 }
11773
11774 if (IsLambda)
11775 return;
11776
11777 if (!DC || !DC->isRecord()) {
11778 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11779 "should have been diagnosed already");
11780 return;
11781 }
11782
11783 // CWG2674: constructors and destructors cannot have explicit parameters.
11784 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11785 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11786 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11787 DiagID: diag::err_explicit_object_parameter_constructor)
11788 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11789 << D.getSourceRange();
11790 D.setInvalidType();
11791 }
11792}
11793
11794namespace {
11795/// Utility class to accumulate and print a diagnostic listing the invalid
11796/// specifier(s) on a declaration.
11797struct BadSpecifierDiagnoser {
11798 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11799 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11800 ~BadSpecifierDiagnoser() {
11801 Diagnostic << Specifiers;
11802 }
11803
11804 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11805 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11806 }
11807 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11808 return check(SpecLoc,
11809 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11810 }
11811 void check(SourceLocation SpecLoc, const char *Spec) {
11812 if (SpecLoc.isInvalid()) return;
11813 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11814 if (!Specifiers.empty()) Specifiers += " ";
11815 Specifiers += Spec;
11816 }
11817
11818 Sema &S;
11819 Sema::SemaDiagnosticBuilder Diagnostic;
11820 std::string Specifiers;
11821};
11822}
11823
11824bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11825 StorageClass &SC) {
11826 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11827 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11828 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11829
11830 // C++ [temp.deduct.guide]p3:
11831 // A deduction-gide shall be declared in the same scope as the
11832 // corresponding class template.
11833 if (!CurContext->getRedeclContext()->Equals(
11834 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11835 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11836 << GuidedTemplateDecl;
11837 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11838 }
11839
11840 auto &DS = D.getMutableDeclSpec();
11841 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11842 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11843 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11844 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11845 BadSpecifierDiagnoser Diagnoser(
11846 *this, D.getIdentifierLoc(),
11847 diag::err_deduction_guide_invalid_specifier);
11848
11849 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11850 DS.ClearStorageClassSpecs();
11851 SC = SC_None;
11852
11853 // 'explicit' is permitted.
11854 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11855 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11856 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11857 DS.ClearConstexprSpec();
11858
11859 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11860 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11861 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11862 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11863 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11864 DS.ClearTypeQualifiers();
11865
11866 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11867 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11868 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11869 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11870 DS.ClearTypeSpecType();
11871 }
11872
11873 if (D.isInvalidType())
11874 return true;
11875
11876 // Check the declarator is simple enough.
11877 bool FoundFunction = false;
11878 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11879 if (Chunk.Kind == DeclaratorChunk::Paren)
11880 continue;
11881 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11882 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11883 DiagID: diag::err_deduction_guide_with_complex_decl)
11884 << D.getSourceRange();
11885 break;
11886 }
11887 if (!Chunk.Fun.hasTrailingReturnType())
11888 return Diag(Loc: D.getName().getBeginLoc(),
11889 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11890
11891 // Check that the return type is written as a specialization of
11892 // the template specified as the deduction-guide's name.
11893 // The template name may not be qualified. [temp.deduct.guide]
11894 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11895 TypeSourceInfo *TSI = nullptr;
11896 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11897 assert(TSI && "deduction guide has valid type but invalid return type?");
11898 bool AcceptableReturnType = false;
11899 bool MightInstantiateToSpecialization = false;
11900 if (auto RetTST =
11901 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11902 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11903 bool TemplateMatches = Context.hasSameTemplateName(
11904 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11905
11906 const QualifiedTemplateName *Qualifiers =
11907 SpecifiedName.getAsQualifiedTemplateName();
11908 assert(Qualifiers && "expected QualifiedTemplate");
11909 bool SimplyWritten =
11910 !Qualifiers->hasTemplateKeyword() && !Qualifiers->getQualifier();
11911 if (SimplyWritten && TemplateMatches)
11912 AcceptableReturnType = true;
11913 else {
11914 // This could still instantiate to the right type, unless we know it
11915 // names the wrong class template.
11916 auto *TD = SpecifiedName.getAsTemplateDecl();
11917 MightInstantiateToSpecialization =
11918 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11919 }
11920 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11921 MightInstantiateToSpecialization = true;
11922 }
11923
11924 if (!AcceptableReturnType)
11925 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11926 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11927 << GuidedTemplate << TSI->getType()
11928 << MightInstantiateToSpecialization
11929 << TSI->getTypeLoc().getSourceRange();
11930
11931 // Keep going to check that we don't have any inner declarator pieces (we
11932 // could still have a function returning a pointer to a function).
11933 FoundFunction = true;
11934 }
11935
11936 if (D.isFunctionDefinition())
11937 // we can still create a valid deduction guide here.
11938 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11939 return false;
11940}
11941
11942//===----------------------------------------------------------------------===//
11943// Namespace Handling
11944//===----------------------------------------------------------------------===//
11945
11946/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11947/// reopened.
11948static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11949 SourceLocation Loc,
11950 IdentifierInfo *II, bool *IsInline,
11951 NamespaceDecl *PrevNS) {
11952 assert(*IsInline != PrevNS->isInline());
11953
11954 // 'inline' must appear on the original definition, but not necessarily
11955 // on all extension definitions, so the note should point to the first
11956 // definition to avoid confusion.
11957 PrevNS = PrevNS->getFirstDecl();
11958
11959 if (PrevNS->isInline())
11960 // The user probably just forgot the 'inline', so suggest that it
11961 // be added back.
11962 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11963 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11964 else
11965 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11966
11967 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
11968 *IsInline = PrevNS->isInline();
11969}
11970
11971/// ActOnStartNamespaceDef - This is called at the start of a namespace
11972/// definition.
11973Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
11974 SourceLocation InlineLoc,
11975 SourceLocation NamespaceLoc,
11976 SourceLocation IdentLoc, IdentifierInfo *II,
11977 SourceLocation LBrace,
11978 const ParsedAttributesView &AttrList,
11979 UsingDirectiveDecl *&UD, bool IsNested) {
11980 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
11981 // For anonymous namespace, take the location of the left brace.
11982 SourceLocation Loc = II ? IdentLoc : LBrace;
11983 bool IsInline = InlineLoc.isValid();
11984 bool IsInvalid = false;
11985 bool IsStd = false;
11986 bool AddToKnown = false;
11987 Scope *DeclRegionScope = NamespcScope->getParent();
11988
11989 NamespaceDecl *PrevNS = nullptr;
11990 if (II) {
11991 // C++ [namespace.std]p7:
11992 // A translation unit shall not declare namespace std to be an inline
11993 // namespace (9.8.2).
11994 //
11995 // Precondition: the std namespace is in the file scope and is declared to
11996 // be inline
11997 auto DiagnoseInlineStdNS = [&]() {
11998 assert(IsInline && II->isStr("std") &&
11999 CurContext->getRedeclContext()->isTranslationUnit() &&
12000 "Precondition of DiagnoseInlineStdNS not met");
12001 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
12002 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
12003 IsInline = false;
12004 };
12005 // C++ [namespace.def]p2:
12006 // The identifier in an original-namespace-definition shall not
12007 // have been previously defined in the declarative region in
12008 // which the original-namespace-definition appears. The
12009 // identifier in an original-namespace-definition is the name of
12010 // the namespace. Subsequently in that declarative region, it is
12011 // treated as an original-namespace-name.
12012 //
12013 // Since namespace names are unique in their scope, and we don't
12014 // look through using directives, just look for any ordinary names
12015 // as if by qualified name lookup.
12016 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12017 RedeclarationKind::ForExternalRedeclaration);
12018 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
12019 NamedDecl *PrevDecl =
12020 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12021 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
12022
12023 if (PrevNS) {
12024 // This is an extended namespace definition.
12025 if (IsInline && II->isStr(Str: "std") &&
12026 CurContext->getRedeclContext()->isTranslationUnit())
12027 DiagnoseInlineStdNS();
12028 else if (IsInline != PrevNS->isInline())
12029 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12030 IsInline: &IsInline, PrevNS);
12031 } else if (PrevDecl) {
12032 // This is an invalid name redefinition.
12033 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12034 << II;
12035 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12036 IsInvalid = true;
12037 // Continue on to push Namespc as current DeclContext and return it.
12038 } else if (II->isStr(Str: "std") &&
12039 CurContext->getRedeclContext()->isTranslationUnit()) {
12040 if (IsInline)
12041 DiagnoseInlineStdNS();
12042 // This is the first "real" definition of the namespace "std", so update
12043 // our cache of the "std" namespace to point at this definition.
12044 PrevNS = getStdNamespace();
12045 IsStd = true;
12046 AddToKnown = !IsInline;
12047 } else {
12048 // We've seen this namespace for the first time.
12049 AddToKnown = !IsInline;
12050 }
12051 } else {
12052 // Anonymous namespaces.
12053
12054 // Determine whether the parent already has an anonymous namespace.
12055 DeclContext *Parent = CurContext->getRedeclContext();
12056 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12057 PrevNS = TU->getAnonymousNamespace();
12058 } else {
12059 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12060 PrevNS = ND->getAnonymousNamespace();
12061 }
12062
12063 if (PrevNS && IsInline != PrevNS->isInline())
12064 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12065 IsInline: &IsInline, PrevNS);
12066 }
12067
12068 NamespaceDecl *Namespc = NamespaceDecl::Create(
12069 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12070 if (IsInvalid)
12071 Namespc->setInvalidDecl();
12072
12073 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12074 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12075 ProcessAPINotes(D: Namespc);
12076
12077 // FIXME: Should we be merging attributes?
12078 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12079 PushNamespaceVisibilityAttr(Attr, Loc);
12080
12081 if (IsStd)
12082 StdNamespace = Namespc;
12083 if (AddToKnown)
12084 KnownNamespaces[Namespc] = false;
12085
12086 if (II) {
12087 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12088 } else {
12089 // Link the anonymous namespace into its parent.
12090 DeclContext *Parent = CurContext->getRedeclContext();
12091 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12092 TU->setAnonymousNamespace(Namespc);
12093 } else {
12094 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12095 }
12096
12097 CurContext->addDecl(D: Namespc);
12098
12099 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12100 // behaves as if it were replaced by
12101 // namespace unique { /* empty body */ }
12102 // using namespace unique;
12103 // namespace unique { namespace-body }
12104 // where all occurrences of 'unique' in a translation unit are
12105 // replaced by the same identifier and this identifier differs
12106 // from all other identifiers in the entire program.
12107
12108 // We just create the namespace with an empty name and then add an
12109 // implicit using declaration, just like the standard suggests.
12110 //
12111 // CodeGen enforces the "universally unique" aspect by giving all
12112 // declarations semantically contained within an anonymous
12113 // namespace internal linkage.
12114
12115 if (!PrevNS) {
12116 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12117 /* 'using' */ UsingLoc: LBrace,
12118 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12119 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12120 /* identifier */ IdentLoc: SourceLocation(),
12121 Nominated: Namespc,
12122 /* Ancestor */ CommonAncestor: Parent);
12123 UD->setImplicit();
12124 Parent->addDecl(D: UD);
12125 }
12126 }
12127
12128 ActOnDocumentableDecl(D: Namespc);
12129
12130 // Although we could have an invalid decl (i.e. the namespace name is a
12131 // redefinition), push it as current DeclContext and try to continue parsing.
12132 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12133 // for the namespace has the declarations that showed up in that particular
12134 // namespace definition.
12135 PushDeclContext(S: NamespcScope, DC: Namespc);
12136 return Namespc;
12137}
12138
12139/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12140/// is a namespace alias, returns the namespace it points to.
12141static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12142 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12143 return AD->getNamespace();
12144 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12145}
12146
12147void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12148 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12149 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12150 Namespc->setRBraceLoc(RBrace);
12151 PopDeclContext();
12152 if (Namespc->hasAttr<VisibilityAttr>())
12153 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12154 // If this namespace contains an export-declaration, export it now.
12155 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12156 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12157}
12158
12159CXXRecordDecl *Sema::getStdBadAlloc() const {
12160 return cast_or_null<CXXRecordDecl>(
12161 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12162}
12163
12164EnumDecl *Sema::getStdAlignValT() const {
12165 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12166}
12167
12168NamespaceDecl *Sema::getStdNamespace() const {
12169 return cast_or_null<NamespaceDecl>(
12170 Val: StdNamespace.get(Source: Context.getExternalSource()));
12171}
12172
12173namespace {
12174
12175enum UnsupportedSTLSelect {
12176 USS_InvalidMember,
12177 USS_MissingMember,
12178 USS_NonTrivial,
12179 USS_Other
12180};
12181
12182struct InvalidSTLDiagnoser {
12183 Sema &S;
12184 SourceLocation Loc;
12185 QualType TyForDiags;
12186
12187 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12188 const VarDecl *VD = nullptr) {
12189 {
12190 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12191 << TyForDiags << ((int)Sel);
12192 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12193 assert(!Name.empty());
12194 D << Name;
12195 }
12196 }
12197 if (Sel == USS_InvalidMember) {
12198 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12199 << VD << VD->getSourceRange();
12200 }
12201 return QualType();
12202 }
12203};
12204} // namespace
12205
12206QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12207 SourceLocation Loc,
12208 ComparisonCategoryUsage Usage) {
12209 assert(getLangOpts().CPlusPlus &&
12210 "Looking for comparison category type outside of C++.");
12211
12212 // Use an elaborated type for diagnostics which has a name containing the
12213 // prepended 'std' namespace but not any inline namespace names.
12214 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12215 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12216 /*Prefix=*/std::nullopt);
12217 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12218 TD: Info->Record,
12219 /*OwnsTag=*/false);
12220 };
12221
12222 // Check if we've already successfully checked the comparison category type
12223 // before. If so, skip checking it again.
12224 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12225 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12226 // The only thing we need to check is that the type has a reachable
12227 // definition in the current context.
12228 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12229 return QualType();
12230
12231 return Info->getType();
12232 }
12233
12234 // If lookup failed
12235 if (!Info) {
12236 std::string NameForDiags = "std::";
12237 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12238 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12239 << NameForDiags << (int)Usage;
12240 return QualType();
12241 }
12242
12243 assert(Info->Kind == Kind);
12244 assert(Info->Record);
12245
12246 // Update the Record decl in case we encountered a forward declaration on our
12247 // first pass. FIXME: This is a bit of a hack.
12248 if (Info->Record->hasDefinition())
12249 Info->Record = Info->Record->getDefinition();
12250
12251 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12252 return QualType();
12253
12254 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12255
12256 if (!Info->Record->isTriviallyCopyable())
12257 return UnsupportedSTLError(USS_NonTrivial);
12258
12259 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12260 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12261 // Tolerate empty base classes.
12262 if (Base->isEmpty())
12263 continue;
12264 // Reject STL implementations which have at least one non-empty base.
12265 return UnsupportedSTLError();
12266 }
12267
12268 // Check that the STL has implemented the types using a single integer field.
12269 // This expectation allows better codegen for builtin operators. We require:
12270 // (1) The class has exactly one field.
12271 // (2) The field is an integral or enumeration type.
12272 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12273 if (std::distance(first: FIt, last: FEnd) != 1 ||
12274 !FIt->getType()->isIntegralOrEnumerationType()) {
12275 return UnsupportedSTLError();
12276 }
12277
12278 // Build each of the require values and store them in Info.
12279 for (ComparisonCategoryResult CCR :
12280 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12281 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12282 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12283
12284 if (!ValInfo)
12285 return UnsupportedSTLError(USS_MissingMember, MemName);
12286
12287 VarDecl *VD = ValInfo->VD;
12288 assert(VD && "should not be null!");
12289
12290 // Attempt to diagnose reasons why the STL definition of this type
12291 // might be foobar, including it failing to be a constant expression.
12292 // TODO Handle more ways the lookup or result can be invalid.
12293 if (!VD->isStaticDataMember() ||
12294 !VD->isUsableInConstantExpressions(C: Context))
12295 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12296
12297 // Attempt to evaluate the var decl as a constant expression and extract
12298 // the value of its first field as a ICE. If this fails, the STL
12299 // implementation is not supported.
12300 if (!ValInfo->hasValidIntValue())
12301 return UnsupportedSTLError();
12302
12303 MarkVariableReferenced(Loc, Var: VD);
12304 }
12305
12306 // We've successfully built the required types and expressions. Update
12307 // the cache and return the newly cached value.
12308 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12309 return Info->getType();
12310}
12311
12312NamespaceDecl *Sema::getOrCreateStdNamespace() {
12313 if (!StdNamespace) {
12314 // The "std" namespace has not yet been defined, so build one implicitly.
12315 StdNamespace = NamespaceDecl::Create(
12316 C&: Context, DC: Context.getTranslationUnitDecl(),
12317 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12318 Id: &PP.getIdentifierTable().get(Name: "std"),
12319 /*PrevDecl=*/nullptr, /*Nested=*/false);
12320 getStdNamespace()->setImplicit(true);
12321 // We want the created NamespaceDecl to be available for redeclaration
12322 // lookups, but not for regular name lookups.
12323 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12324 getStdNamespace()->clearIdentifierNamespace();
12325 }
12326
12327 return getStdNamespace();
12328}
12329
12330static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12331 const char *ClassName,
12332 ClassTemplateDecl **CachedDecl,
12333 const Decl **MalformedDecl) {
12334 // We're looking for implicit instantiations of
12335 // template <typename U> class std::{ClassName}.
12336
12337 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12338 // it.
12339 return false;
12340
12341 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12342 if (!MalformedDecl)
12343 return;
12344 if (!D)
12345 D = SugaredType->getAsTagDecl();
12346 if (!D || !D->isInStdNamespace())
12347 return;
12348 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12349 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12350 *MalformedDecl = D;
12351 };
12352
12353 ClassTemplateDecl *Template = nullptr;
12354 ArrayRef<TemplateArgument> Arguments;
12355 if (const TemplateSpecializationType *TST =
12356 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12357 Template = dyn_cast_or_null<ClassTemplateDecl>(
12358 Val: TST->getTemplateName().getAsTemplateDecl());
12359 Arguments = TST->template_arguments();
12360 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12361 Template = TT->getTemplateDecl();
12362 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12363 }
12364
12365 if (!Template) {
12366 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12367 return false;
12368 }
12369
12370 if (!*CachedDecl) {
12371 // Haven't recognized std::{ClassName} yet, maybe this is it.
12372 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12373 // semantics of this are slightly different, most notably the existing
12374 // "lookup" semantics explicitly diagnose an invalid definition as an
12375 // error.
12376 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12377 if (TemplateClass->getIdentifier() !=
12378 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12379 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12380 NS: TemplateClass->getNonTransparentDeclContext()))
12381 return false;
12382 // This is a template called std::{ClassName}, but is it the right
12383 // template?
12384 TemplateParameterList *Params = Template->getTemplateParameters();
12385 if (Params->getMinRequiredArguments() != 1 ||
12386 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12387 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12388 if (MalformedDecl)
12389 *MalformedDecl = TemplateClass;
12390 return false;
12391 }
12392
12393 // It's the right template.
12394 *CachedDecl = Template;
12395 }
12396
12397 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12398 return false;
12399
12400 // This is an instance of std::{ClassName}. Find the argument type.
12401 if (TypeArg) {
12402 QualType ArgType = Arguments[0].getAsType();
12403 // FIXME: Since TST only has as-written arguments, we have to perform the
12404 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12405 // - If an explicitly-specified template argument type is a lifetime type
12406 // with no lifetime qualifier, the __strong lifetime qualifier is
12407 // inferred.
12408 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12409 !ArgType.getObjCLifetime()) {
12410 Qualifiers Qs;
12411 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12412 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12413 }
12414 *TypeArg = ArgType;
12415 }
12416
12417 return true;
12418}
12419
12420bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12421 assert(getLangOpts().CPlusPlus &&
12422 "Looking for std::initializer_list outside of C++.");
12423
12424 // We're looking for implicit instantiations of
12425 // template <typename E> class std::initializer_list.
12426
12427 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12428 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12429}
12430
12431bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12432 const Decl **MalformedDecl) {
12433 assert(getLangOpts().CPlusPlus &&
12434 "Looking for std::type_identity outside of C++.");
12435
12436 // We're looking for implicit instantiations of
12437 // template <typename T> struct std::type_identity.
12438
12439 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12440 CachedDecl: &StdTypeIdentity, MalformedDecl);
12441}
12442
12443static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12444 const char *ClassName,
12445 bool *WasMalformed) {
12446 if (!S.StdNamespace)
12447 return nullptr;
12448
12449 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12450 Sema::LookupOrdinaryName);
12451 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12452 return nullptr;
12453
12454 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12455 if (!Template) {
12456 Result.suppressDiagnostics();
12457 // We found something weird. Complain about the first thing we found.
12458 NamedDecl *Found = *Result.begin();
12459 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12460 << ClassName;
12461 if (WasMalformed)
12462 *WasMalformed = true;
12463 return nullptr;
12464 }
12465
12466 // We found some template with the correct name. Now verify that it's
12467 // correct.
12468 TemplateParameterList *Params = Template->getTemplateParameters();
12469 if (Params->getMinRequiredArguments() != 1 ||
12470 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12471 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12472 << ClassName;
12473 if (WasMalformed)
12474 *WasMalformed = true;
12475 return nullptr;
12476 }
12477
12478 return Template;
12479}
12480
12481static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12482 QualType TypeParam, SourceLocation Loc) {
12483 assert(S.getStdNamespace());
12484 TemplateArgumentListInfo Args(Loc, Loc);
12485 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12486 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12487
12488 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12489 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12490 /*ForNestedNameSpecifier=*/false);
12491}
12492
12493QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12494 if (!StdInitializerList) {
12495 bool WasMalformed = false;
12496 StdInitializerList =
12497 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12498 if (!StdInitializerList) {
12499 if (!WasMalformed)
12500 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12501 return QualType();
12502 }
12503 }
12504 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12505}
12506
12507QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12508 if (!StdTypeIdentity) {
12509 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12510 /*WasMalformed=*/nullptr);
12511 if (!StdTypeIdentity)
12512 return QualType();
12513 }
12514 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12515}
12516
12517bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12518 // C++ [dcl.init.list]p2:
12519 // A constructor is an initializer-list constructor if its first parameter
12520 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12521 // std::initializer_list<E> for some type E, and either there are no other
12522 // parameters or else all other parameters have default arguments.
12523 if (!Ctor->hasOneParamOrDefaultArgs())
12524 return false;
12525
12526 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12527 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12528 ArgType = RT->getPointeeType().getUnqualifiedType();
12529
12530 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12531}
12532
12533/// Determine whether a using statement is in a context where it will be
12534/// apply in all contexts.
12535static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12536 switch (CurContext->getDeclKind()) {
12537 case Decl::TranslationUnit:
12538 return true;
12539 case Decl::LinkageSpec:
12540 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12541 default:
12542 return false;
12543 }
12544}
12545
12546namespace {
12547
12548// Callback to only accept typo corrections that are namespaces.
12549class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12550public:
12551 bool ValidateCandidate(const TypoCorrection &candidate) override {
12552 if (NamedDecl *ND = candidate.getCorrectionDecl())
12553 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12554 return false;
12555 }
12556
12557 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12558 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12559 }
12560};
12561
12562}
12563
12564static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12565 Sema &S) {
12566 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12567 Module *M = ND->getOwningModule();
12568 assert(M && "hidden namespace definition not in a module?");
12569
12570 if (M->isExplicitGlobalModule())
12571 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12572 DiagID: diag::err_module_unimported_use_header)
12573 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12574 << /*Header Name*/ false;
12575 else
12576 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12577 DiagID: diag::err_module_unimported_use)
12578 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12579 << M->getTopLevelModuleName();
12580}
12581
12582static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12583 CXXScopeSpec &SS,
12584 SourceLocation IdentLoc,
12585 IdentifierInfo *Ident) {
12586 R.clear();
12587 NamespaceValidatorCCC CCC{};
12588 if (TypoCorrection Corrected =
12589 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12590 Mode: CorrectTypoKind::ErrorRecovery)) {
12591 // Generally we find it is confusing more than helpful to diagnose the
12592 // invisible namespace.
12593 // See https://github.com/llvm/llvm-project/issues/73893.
12594 //
12595 // However, we should diagnose when the users are trying to using an
12596 // invisible namespace. So we handle the case specially here.
12597 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12598 Corrected.requiresImport()) {
12599 DiagnoseInvisibleNamespace(Corrected, S);
12600 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12601 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12602 bool DroppedSpecifier =
12603 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12604 S.diagnoseTypo(Correction: Corrected,
12605 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12606 << Ident << DC << DroppedSpecifier << SS.getRange(),
12607 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12608 } else {
12609 S.diagnoseTypo(Correction: Corrected,
12610 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12611 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12612 }
12613 R.addDecl(D: Corrected.getFoundDecl());
12614 return true;
12615 }
12616 return false;
12617}
12618
12619Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12620 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12621 SourceLocation IdentLoc,
12622 IdentifierInfo *NamespcName,
12623 const ParsedAttributesView &AttrList) {
12624 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12625 assert(NamespcName && "Invalid NamespcName.");
12626 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12627
12628 // Get the innermost enclosing declaration scope.
12629 S = S->getDeclParent();
12630
12631 UsingDirectiveDecl *UDir = nullptr;
12632 NestedNameSpecifier Qualifier = SS.getScopeRep();
12633
12634 // Lookup namespace name.
12635 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12636 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12637 if (R.isAmbiguous())
12638 return nullptr;
12639
12640 if (R.empty()) {
12641 R.clear();
12642 // Allow "using namespace std;" or "using namespace ::std;" even if
12643 // "std" hasn't been defined yet, for GCC compatibility.
12644 if ((!Qualifier ||
12645 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12646 NamespcName->isStr(Str: "std")) {
12647 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12648 R.addDecl(D: getOrCreateStdNamespace());
12649 R.resolveKind();
12650 }
12651 // Otherwise, attempt typo correction.
12652 else
12653 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12654 }
12655
12656 if (!R.empty()) {
12657 NamedDecl *Named = R.getRepresentativeDecl();
12658 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12659 assert(NS && "expected namespace decl");
12660
12661 // The use of a nested name specifier may trigger deprecation warnings.
12662 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12663
12664 // C++ [namespace.udir]p1:
12665 // A using-directive specifies that the names in the nominated
12666 // namespace can be used in the scope in which the
12667 // using-directive appears after the using-directive. During
12668 // unqualified name lookup (3.4.1), the names appear as if they
12669 // were declared in the nearest enclosing namespace which
12670 // contains both the using-directive and the nominated
12671 // namespace. [Note: in this context, "contains" means "contains
12672 // directly or indirectly". ]
12673
12674 // Find enclosing context containing both using-directive and
12675 // nominated namespace.
12676 DeclContext *CommonAncestor = NS;
12677 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12678 CommonAncestor = CommonAncestor->getParent();
12679
12680 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12681 QualifierLoc: SS.getWithLocInContext(Context),
12682 IdentLoc, Nominated: Named, CommonAncestor);
12683
12684 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12685 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12686 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12687 }
12688
12689 PushUsingDirective(S, UDir);
12690 } else {
12691 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12692 }
12693
12694 if (UDir) {
12695 ProcessDeclAttributeList(S, D: UDir, AttrList);
12696 ProcessAPINotes(D: UDir);
12697 }
12698
12699 return UDir;
12700}
12701
12702void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12703 // If the scope has an associated entity and the using directive is at
12704 // namespace or translation unit scope, add the UsingDirectiveDecl into
12705 // its lookup structure so qualified name lookup can find it.
12706 DeclContext *Ctx = S->getEntity();
12707 if (Ctx && !Ctx->isFunctionOrMethod())
12708 Ctx->addDecl(D: UDir);
12709 else
12710 // Otherwise, it is at block scope. The using-directives will affect lookup
12711 // only to the end of the scope.
12712 S->PushUsingDirective(UDir);
12713}
12714
12715Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12716 SourceLocation UsingLoc,
12717 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12718 UnqualifiedId &Name,
12719 SourceLocation EllipsisLoc,
12720 const ParsedAttributesView &AttrList) {
12721 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12722
12723 if (SS.isEmpty()) {
12724 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12725 return nullptr;
12726 }
12727
12728 switch (Name.getKind()) {
12729 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12730 case UnqualifiedIdKind::IK_Identifier:
12731 case UnqualifiedIdKind::IK_OperatorFunctionId:
12732 case UnqualifiedIdKind::IK_LiteralOperatorId:
12733 case UnqualifiedIdKind::IK_ConversionFunctionId:
12734 break;
12735
12736 case UnqualifiedIdKind::IK_ConstructorName:
12737 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12738 // C++11 inheriting constructors.
12739 Diag(Loc: Name.getBeginLoc(),
12740 DiagID: getLangOpts().CPlusPlus11
12741 ? diag::warn_cxx98_compat_using_decl_constructor
12742 : diag::err_using_decl_constructor)
12743 << SS.getRange();
12744
12745 if (getLangOpts().CPlusPlus11) break;
12746
12747 return nullptr;
12748
12749 case UnqualifiedIdKind::IK_DestructorName:
12750 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12751 return nullptr;
12752
12753 case UnqualifiedIdKind::IK_TemplateId:
12754 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12755 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12756 return nullptr;
12757
12758 case UnqualifiedIdKind::IK_DeductionGuideName:
12759 llvm_unreachable("cannot parse qualified deduction guide name");
12760 }
12761
12762 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12763 DeclarationName TargetName = TargetNameInfo.getName();
12764 if (!TargetName)
12765 return nullptr;
12766
12767 // Warn about access declarations.
12768 if (UsingLoc.isInvalid()) {
12769 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12770 ? diag::err_access_decl
12771 : diag::warn_access_decl_deprecated)
12772 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12773 }
12774
12775 if (EllipsisLoc.isInvalid()) {
12776 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12777 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12778 return nullptr;
12779 } else {
12780 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12781 !TargetNameInfo.containsUnexpandedParameterPack()) {
12782 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12783 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12784 EllipsisLoc = SourceLocation();
12785 }
12786 }
12787
12788 NamedDecl *UD =
12789 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12790 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12791 /*IsInstantiation*/ false,
12792 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12793 if (UD)
12794 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12795
12796 return UD;
12797}
12798
12799Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12800 SourceLocation UsingLoc,
12801 SourceLocation EnumLoc, SourceRange TyLoc,
12802 const IdentifierInfo &II, ParsedType Ty,
12803 const CXXScopeSpec &SS) {
12804 TypeSourceInfo *TSI = nullptr;
12805 SourceLocation IdentLoc = TyLoc.getBegin();
12806 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12807 if (EnumTy.isNull()) {
12808 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12809 ? diag::err_using_enum_is_dependent
12810 : diag::err_unknown_typename)
12811 << II.getName()
12812 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12813 TyLoc.getEnd());
12814 return nullptr;
12815 }
12816
12817 if (EnumTy->isDependentType()) {
12818 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12819 return nullptr;
12820 }
12821
12822 auto *Enum = EnumTy->getAsEnumDecl();
12823 if (!Enum) {
12824 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12825 return nullptr;
12826 }
12827
12828 if (TSI == nullptr)
12829 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12830
12831 auto *UD =
12832 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12833
12834 if (UD)
12835 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12836
12837 return UD;
12838}
12839
12840/// Determine whether a using declaration considers the given
12841/// declarations as "equivalent", e.g., if they are redeclarations of
12842/// the same entity or are both typedefs of the same type.
12843static bool
12844IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12845 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12846 return true;
12847
12848 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12849 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12850 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12851 T2: TD2->getUnderlyingType());
12852
12853 // Two using_if_exists using-declarations are equivalent if both are
12854 // unresolved.
12855 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12856 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12857 return true;
12858
12859 return false;
12860}
12861
12862bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12863 const LookupResult &Previous,
12864 UsingShadowDecl *&PrevShadow) {
12865 // Diagnose finding a decl which is not from a base class of the
12866 // current class. We do this now because there are cases where this
12867 // function will silently decide not to build a shadow decl, which
12868 // will pre-empt further diagnostics.
12869 //
12870 // We don't need to do this in C++11 because we do the check once on
12871 // the qualifier.
12872 //
12873 // FIXME: diagnose the following if we care enough:
12874 // struct A { int foo; };
12875 // struct B : A { using A::foo; };
12876 // template <class T> struct C : A {};
12877 // template <class T> struct D : C<T> { using B::foo; } // <---
12878 // This is invalid (during instantiation) in C++03 because B::foo
12879 // resolves to the using decl in B, which is not a base class of D<T>.
12880 // We can't diagnose it immediately because C<T> is an unknown
12881 // specialization. The UsingShadowDecl in D<T> then points directly
12882 // to A::foo, which will look well-formed when we instantiate.
12883 // The right solution is to not collapse the shadow-decl chain.
12884 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12885 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12886 DeclContext *OrigDC = Orig->getDeclContext();
12887
12888 // Handle enums and anonymous structs.
12889 if (isa<EnumDecl>(Val: OrigDC))
12890 OrigDC = OrigDC->getParent();
12891 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12892 while (OrigRec->isAnonymousStructOrUnion())
12893 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12894
12895 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12896 if (OrigDC == CurContext) {
12897 Diag(Loc: Using->getLocation(),
12898 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12899 << Using->getQualifierLoc().getSourceRange();
12900 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12901 Using->setInvalidDecl();
12902 return true;
12903 }
12904
12905 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12906 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12907 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12908 << Using->getQualifierLoc().getSourceRange();
12909 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12910 Using->setInvalidDecl();
12911 return true;
12912 }
12913 }
12914
12915 if (Previous.empty()) return false;
12916
12917 NamedDecl *Target = Orig;
12918 if (isa<UsingShadowDecl>(Val: Target))
12919 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12920
12921 // If the target happens to be one of the previous declarations, we
12922 // don't have a conflict.
12923 //
12924 // FIXME: but we might be increasing its access, in which case we
12925 // should redeclare it.
12926 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12927 bool FoundEquivalentDecl = false;
12928 for (NamedDecl *Element : Previous) {
12929 NamedDecl *D = Element->getUnderlyingDecl();
12930 // We can have UsingDecls in our Previous results because we use the same
12931 // LookupResult for checking whether the UsingDecl itself is a valid
12932 // redeclaration.
12933 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12934 continue;
12935
12936 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12937 // C++ [class.mem]p19:
12938 // If T is the name of a class, then [every named member other than
12939 // a non-static data member] shall have a name different from T
12940 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12941 !isa<IndirectFieldDecl>(Val: Target) &&
12942 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12943 DiagnoseClassNameShadow(
12944 DC: CurContext,
12945 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12946 return true;
12947 }
12948
12949 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12950 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12951 PrevShadow = Shadow;
12952 FoundEquivalentDecl = true;
12953 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12954 // We don't conflict with an existing using shadow decl of an equivalent
12955 // declaration, but we're not a redeclaration of it.
12956 FoundEquivalentDecl = true;
12957 }
12958
12959 if (isVisible(D))
12960 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12961 }
12962
12963 if (FoundEquivalentDecl)
12964 return false;
12965
12966 // Always emit a diagnostic for a mismatch between an unresolved
12967 // using_if_exists and a resolved using declaration in either direction.
12968 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
12969 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
12970 if (!NonTag && !Tag)
12971 return false;
12972 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12973 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
12974 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
12975 DiagID: diag::note_using_decl_conflict);
12976 BUD->setInvalidDecl();
12977 return true;
12978 }
12979
12980 if (FunctionDecl *FD = Target->getAsFunction()) {
12981 NamedDecl *OldDecl = nullptr;
12982 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
12983 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
12984 case OverloadKind::Overload:
12985 return false;
12986
12987 case OverloadKind::NonFunction:
12988 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
12989 break;
12990
12991 // We found a decl with the exact signature.
12992 case OverloadKind::Match:
12993 // If we're in a record, we want to hide the target, so we
12994 // return true (without a diagnostic) to tell the caller not to
12995 // build a shadow decl.
12996 if (CurContext->isRecord())
12997 return true;
12998
12999 // If we're not in a record, this is an error.
13000 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13001 break;
13002 }
13003
13004 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13005 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
13006 BUD->setInvalidDecl();
13007 return true;
13008 }
13009
13010 // Target is not a function.
13011
13012 if (isa<TagDecl>(Val: Target)) {
13013 // No conflict between a tag and a non-tag.
13014 if (!Tag) return false;
13015
13016 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13017 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13018 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
13019 BUD->setInvalidDecl();
13020 return true;
13021 }
13022
13023 // No conflict between a tag and a non-tag.
13024 if (!NonTag) return false;
13025
13026 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13027 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13028 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13029 BUD->setInvalidDecl();
13030 return true;
13031}
13032
13033/// Determine whether a direct base class is a virtual base class.
13034static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13035 if (!Derived->getNumVBases())
13036 return false;
13037 for (auto &B : Derived->bases())
13038 if (B.getType()->getAsCXXRecordDecl() == Base)
13039 return B.isVirtual();
13040 llvm_unreachable("not a direct base class");
13041}
13042
13043UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13044 NamedDecl *Orig,
13045 UsingShadowDecl *PrevDecl) {
13046 // If we resolved to another shadow declaration, just coalesce them.
13047 NamedDecl *Target = Orig;
13048 if (isa<UsingShadowDecl>(Val: Target)) {
13049 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13050 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13051 }
13052
13053 NamedDecl *NonTemplateTarget = Target;
13054 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13055 NonTemplateTarget = TargetTD->getTemplatedDecl();
13056
13057 UsingShadowDecl *Shadow;
13058 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13059 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13060 bool IsVirtualBase =
13061 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13062 Base: Using->getQualifier().getAsRecordDecl());
13063 Shadow = ConstructorUsingShadowDecl::Create(
13064 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13065 } else {
13066 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13067 Name: Target->getDeclName(), Introducer: BUD, Target);
13068 }
13069 BUD->addShadowDecl(S: Shadow);
13070
13071 Shadow->setAccess(BUD->getAccess());
13072 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13073 Shadow->setInvalidDecl();
13074
13075 Shadow->setPreviousDecl(PrevDecl);
13076
13077 if (S)
13078 PushOnScopeChains(D: Shadow, S);
13079 else
13080 CurContext->addDecl(D: Shadow);
13081
13082
13083 return Shadow;
13084}
13085
13086void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13087 if (Shadow->getDeclName().getNameKind() ==
13088 DeclarationName::CXXConversionFunctionName)
13089 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13090
13091 // Remove it from the DeclContext...
13092 Shadow->getDeclContext()->removeDecl(D: Shadow);
13093
13094 // ...and the scope, if applicable...
13095 if (S) {
13096 S->RemoveDecl(D: Shadow);
13097 IdResolver.RemoveDecl(D: Shadow);
13098 }
13099
13100 // ...and the using decl.
13101 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13102
13103 // TODO: complain somehow if Shadow was used. It shouldn't
13104 // be possible for this to happen, because...?
13105}
13106
13107/// Find the base specifier for a base class with the given type.
13108static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13109 QualType DesiredBase,
13110 bool &AnyDependentBases) {
13111 // Check whether the named type is a direct base class.
13112 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13113 for (auto &Base : Derived->bases()) {
13114 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13115 if (CanonicalDesiredBase == BaseType)
13116 return &Base;
13117 if (BaseType->isDependentType())
13118 AnyDependentBases = true;
13119 }
13120 return nullptr;
13121}
13122
13123namespace {
13124class UsingValidatorCCC final : public CorrectionCandidateCallback {
13125public:
13126 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13127 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13128 : HasTypenameKeyword(HasTypenameKeyword),
13129 IsInstantiation(IsInstantiation), OldNNS(NNS),
13130 RequireMemberOf(RequireMemberOf) {}
13131
13132 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13133 NamedDecl *ND = Candidate.getCorrectionDecl();
13134
13135 // Keywords are not valid here.
13136 if (!ND || isa<NamespaceDecl>(Val: ND))
13137 return false;
13138
13139 // Completely unqualified names are invalid for a 'using' declaration.
13140 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13141 return false;
13142
13143 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13144 // reject.
13145
13146 if (RequireMemberOf) {
13147 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13148 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13149 // No-one ever wants a using-declaration to name an injected-class-name
13150 // of a base class, unless they're declaring an inheriting constructor.
13151 ASTContext &Ctx = ND->getASTContext();
13152 if (!Ctx.getLangOpts().CPlusPlus11)
13153 return false;
13154 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13155
13156 // Check that the injected-class-name is named as a member of its own
13157 // type; we don't want to suggest 'using Derived::Base;', since that
13158 // means something else.
13159 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13160 ? Candidate.getCorrectionSpecifier()
13161 : OldNNS;
13162 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13163 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13164 return false;
13165
13166 // Check that this inheriting constructor declaration actually names a
13167 // direct base class of the current class.
13168 bool AnyDependentBases = false;
13169 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13170 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13171 AnyDependentBases) &&
13172 !AnyDependentBases)
13173 return false;
13174 } else {
13175 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13176 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13177 return false;
13178
13179 // FIXME: Check that the base class member is accessible?
13180 }
13181 } else {
13182 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13183 if (FoundRecord && FoundRecord->isInjectedClassName())
13184 return false;
13185 }
13186
13187 if (isa<TypeDecl>(Val: ND))
13188 return HasTypenameKeyword || !IsInstantiation;
13189
13190 return !HasTypenameKeyword;
13191 }
13192
13193 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13194 return std::make_unique<UsingValidatorCCC>(args&: *this);
13195 }
13196
13197private:
13198 bool HasTypenameKeyword;
13199 bool IsInstantiation;
13200 NestedNameSpecifier OldNNS;
13201 CXXRecordDecl *RequireMemberOf;
13202};
13203} // end anonymous namespace
13204
13205void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13206 // It is really dumb that we have to do this.
13207 LookupResult::Filter F = Previous.makeFilter();
13208 while (F.hasNext()) {
13209 NamedDecl *D = F.next();
13210 if (!isDeclInScope(D, Ctx: CurContext, S))
13211 F.erase();
13212 // If we found a local extern declaration that's not ordinarily visible,
13213 // and this declaration is being added to a non-block scope, ignore it.
13214 // We're only checking for scope conflicts here, not also for violations
13215 // of the linkage rules.
13216 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13217 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13218 F.erase();
13219 }
13220 F.done();
13221}
13222
13223NamedDecl *Sema::BuildUsingDeclaration(
13224 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13225 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13226 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13227 const ParsedAttributesView &AttrList, bool IsInstantiation,
13228 bool IsUsingIfExists) {
13229 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13230 SourceLocation IdentLoc = NameInfo.getLoc();
13231 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13232
13233 // FIXME: We ignore attributes for now.
13234
13235 // For an inheriting constructor declaration, the name of the using
13236 // declaration is the name of a constructor in this class, not in the
13237 // base class.
13238 DeclarationNameInfo UsingName = NameInfo;
13239 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13240 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13241 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13242 Ty: Context.getCanonicalTagType(TD: RD)));
13243
13244 // Do the redeclaration lookup in the current scope.
13245 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13246 RedeclarationKind::ForVisibleRedeclaration);
13247 Previous.setHideTags(false);
13248 if (S) {
13249 LookupName(R&: Previous, S);
13250
13251 FilterUsingLookup(S, Previous);
13252 } else {
13253 assert(IsInstantiation && "no scope in non-instantiation");
13254 if (CurContext->isRecord())
13255 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13256 else {
13257 // No redeclaration check is needed here; in non-member contexts we
13258 // diagnosed all possible conflicts with other using-declarations when
13259 // building the template:
13260 //
13261 // For a dependent non-type using declaration, the only valid case is
13262 // if we instantiate to a single enumerator. We check for conflicts
13263 // between shadow declarations we introduce, and we check in the template
13264 // definition for conflicts between a non-type using declaration and any
13265 // other declaration, which together covers all cases.
13266 //
13267 // A dependent typename using declaration will never successfully
13268 // instantiate, since it will always name a class member, so we reject
13269 // that in the template definition.
13270 }
13271 }
13272
13273 // Check for invalid redeclarations.
13274 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13275 SS, NameLoc: IdentLoc, Previous))
13276 return nullptr;
13277
13278 // 'using_if_exists' doesn't make sense on an inherited constructor.
13279 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13280 DeclarationName::CXXConstructorName) {
13281 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13282 return nullptr;
13283 }
13284
13285 DeclContext *LookupContext = computeDeclContext(SS);
13286 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13287 if (!LookupContext || EllipsisLoc.isValid()) {
13288 NamedDecl *D;
13289 // Dependent scope, or an unexpanded pack
13290 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13291 SS, NameInfo, NameLoc: IdentLoc))
13292 return nullptr;
13293
13294 if (Previous.isSingleResult() &&
13295 Previous.getFoundDecl()->isTemplateParameter())
13296 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13297
13298 if (HasTypenameKeyword) {
13299 // FIXME: not all declaration name kinds are legal here
13300 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13301 UsingLoc, TypenameLoc,
13302 QualifierLoc,
13303 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13304 EllipsisLoc);
13305 } else {
13306 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13307 QualifierLoc, NameInfo, EllipsisLoc);
13308 }
13309 D->setAccess(AS);
13310 CurContext->addDecl(D);
13311 ProcessDeclAttributeList(S, D, AttrList);
13312 return D;
13313 }
13314
13315 auto Build = [&](bool Invalid) {
13316 UsingDecl *UD =
13317 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13318 NameInfo: UsingName, HasTypenameKeyword);
13319 UD->setAccess(AS);
13320 CurContext->addDecl(D: UD);
13321 ProcessDeclAttributeList(S, D: UD, AttrList);
13322 UD->setInvalidDecl(Invalid);
13323 return UD;
13324 };
13325 auto BuildInvalid = [&]{ return Build(true); };
13326 auto BuildValid = [&]{ return Build(false); };
13327
13328 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13329 return BuildInvalid();
13330
13331 // Look up the target name.
13332 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13333
13334 // Unlike most lookups, we don't always want to hide tag
13335 // declarations: tag names are visible through the using declaration
13336 // even if hidden by ordinary names, *except* in a dependent context
13337 // where they may be used by two-phase lookup.
13338 if (!IsInstantiation)
13339 R.setHideTags(false);
13340
13341 // For the purposes of this lookup, we have a base object type
13342 // equal to that of the current context.
13343 if (CurContext->isRecord()) {
13344 R.setBaseObjectType(
13345 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13346 }
13347
13348 LookupQualifiedName(R, LookupCtx: LookupContext);
13349
13350 // Validate the context, now we have a lookup
13351 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13352 NameLoc: IdentLoc, R: &R))
13353 return nullptr;
13354
13355 if (R.empty() && IsUsingIfExists)
13356 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13357 Name: UsingName.getName()),
13358 AS: AS_public);
13359
13360 // Try to correct typos if possible. If constructor name lookup finds no
13361 // results, that means the named class has no explicit constructors, and we
13362 // suppressed declaring implicit ones (probably because it's dependent or
13363 // invalid).
13364 if (R.empty() &&
13365 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13366 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13367 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13368 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13369 auto *II = NameInfo.getName().getAsIdentifierInfo();
13370 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13371 CurContext->isStdNamespace() &&
13372 isa<TranslationUnitDecl>(Val: LookupContext) &&
13373 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13374 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13375 return nullptr;
13376 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13377 dyn_cast<CXXRecordDecl>(Val: CurContext));
13378 if (TypoCorrection Corrected =
13379 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13380 Mode: CorrectTypoKind::ErrorRecovery)) {
13381 // We reject candidates where DroppedSpecifier == true, hence the
13382 // literal '0' below.
13383 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13384 << NameInfo.getName() << LookupContext << 0
13385 << SS.getRange());
13386
13387 // If we picked a correction with no attached Decl we can't do anything
13388 // useful with it, bail out.
13389 NamedDecl *ND = Corrected.getCorrectionDecl();
13390 if (!ND)
13391 return BuildInvalid();
13392
13393 // If we corrected to an inheriting constructor, handle it as one.
13394 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13395 if (RD && RD->isInjectedClassName()) {
13396 // The parent of the injected class name is the class itself.
13397 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13398
13399 // Fix up the information we'll use to build the using declaration.
13400 if (Corrected.WillReplaceSpecifier()) {
13401 NestedNameSpecifierLocBuilder Builder;
13402 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13403 R: QualifierLoc.getSourceRange());
13404 QualifierLoc = Builder.getWithLocInContext(Context);
13405 }
13406
13407 // In this case, the name we introduce is the name of a derived class
13408 // constructor.
13409 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13410 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13411 Ty: Context.getCanonicalTagType(TD: CurClass)));
13412 UsingName.setNamedTypeInfo(nullptr);
13413 for (auto *Ctor : LookupConstructors(Class: RD))
13414 R.addDecl(D: Ctor);
13415 R.resolveKind();
13416 } else {
13417 // FIXME: Pick up all the declarations if we found an overloaded
13418 // function.
13419 UsingName.setName(ND->getDeclName());
13420 R.addDecl(D: ND);
13421 }
13422 } else {
13423 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13424 << NameInfo.getName() << LookupContext << SS.getRange();
13425 return BuildInvalid();
13426 }
13427 }
13428
13429 if (R.isAmbiguous())
13430 return BuildInvalid();
13431
13432 if (HasTypenameKeyword) {
13433 // If we asked for a typename and got a non-type decl, error out.
13434 if (!R.getAsSingle<TypeDecl>() &&
13435 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13436 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13437 for (const NamedDecl *D : R)
13438 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13439 DiagID: diag::note_using_decl_target);
13440 return BuildInvalid();
13441 }
13442 } else {
13443 // If we asked for a non-typename and we got a type, error out,
13444 // but only if this is an instantiation of an unresolved using
13445 // decl. Otherwise just silently find the type name.
13446 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13447 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13448 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13449 return BuildInvalid();
13450 }
13451 }
13452
13453 // C++14 [namespace.udecl]p6:
13454 // A using-declaration shall not name a namespace.
13455 if (R.getAsSingle<NamespaceDecl>()) {
13456 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13457 << SS.getRange();
13458 // Suggest using 'using namespace ...' instead.
13459 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13460 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13461 return BuildInvalid();
13462 }
13463
13464 UsingDecl *UD = BuildValid();
13465
13466 // Some additional rules apply to inheriting constructors.
13467 if (UsingName.getName().getNameKind() ==
13468 DeclarationName::CXXConstructorName) {
13469 // Suppress access diagnostics; the access check is instead performed at the
13470 // point of use for an inheriting constructor.
13471 R.suppressDiagnostics();
13472 if (CheckInheritingConstructorUsingDecl(UD))
13473 return UD;
13474 }
13475
13476 for (NamedDecl *D : R) {
13477 UsingShadowDecl *PrevDecl = nullptr;
13478 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13479 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13480 }
13481
13482 return UD;
13483}
13484
13485NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13486 SourceLocation UsingLoc,
13487 SourceLocation EnumLoc,
13488 SourceLocation NameLoc,
13489 TypeSourceInfo *EnumType,
13490 EnumDecl *ED) {
13491 bool Invalid = false;
13492
13493 if (CurContext->getRedeclContext()->isRecord()) {
13494 /// In class scope, check if this is a duplicate, for better a diagnostic.
13495 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13496 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13497 RedeclarationKind::ForVisibleRedeclaration);
13498
13499 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13500
13501 for (NamedDecl *D : Previous)
13502 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13503 if (UED->getEnumDecl() == ED) {
13504 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13505 << SourceRange(EnumLoc, NameLoc);
13506 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13507 Invalid = true;
13508 break;
13509 }
13510 }
13511
13512 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13513 Invalid = true;
13514
13515 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13516 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13517 UD->setAccess(AS);
13518 CurContext->addDecl(D: UD);
13519
13520 if (Invalid) {
13521 UD->setInvalidDecl();
13522 return UD;
13523 }
13524
13525 // Create the shadow decls for each enumerator
13526 for (EnumConstantDecl *EC : ED->enumerators()) {
13527 UsingShadowDecl *PrevDecl = nullptr;
13528 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13529 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13530 RedeclarationKind::ForVisibleRedeclaration);
13531 LookupName(R&: Previous, S);
13532 FilterUsingLookup(S, Previous);
13533
13534 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13535 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13536 }
13537
13538 return UD;
13539}
13540
13541NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13542 ArrayRef<NamedDecl *> Expansions) {
13543 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13544 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13545 isa<UsingPackDecl>(InstantiatedFrom));
13546
13547 auto *UPD =
13548 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13549 UPD->setAccess(InstantiatedFrom->getAccess());
13550 CurContext->addDecl(D: UPD);
13551 return UPD;
13552}
13553
13554bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13555 assert(!UD->hasTypename() && "expecting a constructor name");
13556
13557 QualType SourceType(UD->getQualifier().getAsType(), 0);
13558 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13559
13560 // Check whether the named type is a direct base class.
13561 bool AnyDependentBases = false;
13562 auto *Base =
13563 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13564 if (!Base && !AnyDependentBases) {
13565 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13566 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13567 UD->setInvalidDecl();
13568 return true;
13569 }
13570
13571 if (Base)
13572 Base->setInheritConstructors();
13573
13574 return false;
13575}
13576
13577bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13578 bool HasTypenameKeyword,
13579 const CXXScopeSpec &SS,
13580 SourceLocation NameLoc,
13581 const LookupResult &Prev) {
13582 NestedNameSpecifier Qual = SS.getScopeRep();
13583
13584 // C++03 [namespace.udecl]p8:
13585 // C++0x [namespace.udecl]p10:
13586 // A using-declaration is a declaration and can therefore be used
13587 // repeatedly where (and only where) multiple declarations are
13588 // allowed.
13589 //
13590 // That's in non-member contexts.
13591 if (!CurContext->getRedeclContext()->isRecord()) {
13592 // A dependent qualifier outside a class can only ever resolve to an
13593 // enumeration type. Therefore it conflicts with any other non-type
13594 // declaration in the same scope.
13595 // FIXME: How should we check for dependent type-type conflicts at block
13596 // scope?
13597 if (Qual.isDependent() && !HasTypenameKeyword) {
13598 for (auto *D : Prev) {
13599 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13600 bool OldCouldBeEnumerator =
13601 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13602 Diag(Loc: NameLoc,
13603 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13604 : diag::err_redefinition_different_kind)
13605 << Prev.getLookupName();
13606 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13607 return true;
13608 }
13609 }
13610 }
13611 return false;
13612 }
13613
13614 NestedNameSpecifier CNNS = Qual.getCanonical();
13615 for (const NamedDecl *D : Prev) {
13616 bool DTypename;
13617 NestedNameSpecifier DQual = std::nullopt;
13618 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13619 DTypename = UD->hasTypename();
13620 DQual = UD->getQualifier();
13621 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13622 DTypename = false;
13623 DQual = UD->getQualifier();
13624 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13625 DTypename = true;
13626 DQual = UD->getQualifier();
13627 } else
13628 continue;
13629
13630 // using decls differ if one says 'typename' and the other doesn't.
13631 // FIXME: non-dependent using decls?
13632 if (HasTypenameKeyword != DTypename) continue;
13633
13634 // using decls differ if they name different scopes (but note that
13635 // template instantiation can cause this check to trigger when it
13636 // didn't before instantiation).
13637 if (CNNS != DQual.getCanonical())
13638 continue;
13639
13640 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13641 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13642 return true;
13643 }
13644
13645 return false;
13646}
13647
13648bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13649 const CXXScopeSpec &SS,
13650 const DeclarationNameInfo &NameInfo,
13651 SourceLocation NameLoc,
13652 const LookupResult *R, const UsingDecl *UD) {
13653 DeclContext *NamedContext = computeDeclContext(SS);
13654 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13655 "resolvable context must have exactly one set of decls");
13656
13657 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13658 // relationship.
13659 bool Cxx20Enumerator = false;
13660 if (NamedContext) {
13661 EnumConstantDecl *EC = nullptr;
13662 if (R)
13663 EC = R->getAsSingle<EnumConstantDecl>();
13664 else if (UD && UD->shadow_size() == 1)
13665 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13666 if (EC)
13667 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13668
13669 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13670 // C++14 [namespace.udecl]p7:
13671 // A using-declaration shall not name a scoped enumerator.
13672 // C++20 p1099 permits enumerators.
13673 if (EC && R && ED->isScoped())
13674 Diag(Loc: SS.getBeginLoc(),
13675 DiagID: getLangOpts().CPlusPlus20
13676 ? diag::warn_cxx17_compat_using_decl_scoped_enumerator
13677 : diag::ext_using_decl_scoped_enumerator)
13678 << SS.getRange();
13679
13680 // We want to consider the scope of the enumerator
13681 NamedContext = ED->getDeclContext();
13682 }
13683 }
13684
13685 if (!CurContext->isRecord()) {
13686 // C++03 [namespace.udecl]p3:
13687 // C++0x [namespace.udecl]p8:
13688 // A using-declaration for a class member shall be a member-declaration.
13689 // C++20 [namespace.udecl]p7
13690 // ... other than an enumerator ...
13691
13692 // If we weren't able to compute a valid scope, it might validly be a
13693 // dependent class or enumeration scope. If we have a 'typename' keyword,
13694 // the scope must resolve to a class type.
13695 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13696 : !HasTypename)
13697 return false; // OK
13698
13699 Diag(Loc: NameLoc,
13700 DiagID: Cxx20Enumerator
13701 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13702 : diag::err_using_decl_can_not_refer_to_class_member)
13703 << SS.getRange();
13704
13705 if (Cxx20Enumerator)
13706 return false; // OK
13707
13708 auto *RD = NamedContext
13709 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13710 : nullptr;
13711 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13712 // See if there's a helpful fixit
13713
13714 if (!R) {
13715 // We will have already diagnosed the problem on the template
13716 // definition, Maybe we should do so again?
13717 } else if (R->getAsSingle<TypeDecl>()) {
13718 if (getLangOpts().CPlusPlus11) {
13719 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13720 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13721 << diag::MemClassWorkaround::AliasDecl
13722 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13723 Code: NameInfo.getName().getAsString() +
13724 " = ");
13725 } else {
13726 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13727 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13728 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13729 << diag::MemClassWorkaround::TypedefDecl
13730 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13731 << FixItHint::CreateInsertion(
13732 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13733 }
13734 } else if (R->getAsSingle<VarDecl>()) {
13735 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13736 // repeating the type of the static data member here.
13737 FixItHint FixIt;
13738 if (getLangOpts().CPlusPlus11) {
13739 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13740 FixIt = FixItHint::CreateReplacement(
13741 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13742 }
13743
13744 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13745 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13746 } else if (R->getAsSingle<EnumConstantDecl>()) {
13747 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13748 // repeating the type of the enumeration here, and we can't do so if
13749 // the type is anonymous.
13750 FixItHint FixIt;
13751 if (getLangOpts().CPlusPlus11) {
13752 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13753 FixIt = FixItHint::CreateReplacement(
13754 RemoveRange: UsingLoc,
13755 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13756 }
13757
13758 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13759 << (getLangOpts().CPlusPlus11
13760 ? diag::MemClassWorkaround::ConstexprVar
13761 : diag::MemClassWorkaround::ConstVar)
13762 << FixIt;
13763 }
13764 }
13765
13766 return true; // Fail
13767 }
13768
13769 // If the named context is dependent, we can't decide much.
13770 if (!NamedContext) {
13771 // FIXME: in C++0x, we can diagnose if we can prove that the
13772 // nested-name-specifier does not refer to a base class, which is
13773 // still possible in some cases.
13774
13775 // Otherwise we have to conservatively report that things might be
13776 // okay.
13777 return false;
13778 }
13779
13780 // The current scope is a record.
13781 if (!NamedContext->isRecord()) {
13782 // Ideally this would point at the last name in the specifier,
13783 // but we don't have that level of source info.
13784 Diag(Loc: SS.getBeginLoc(),
13785 DiagID: Cxx20Enumerator
13786 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13787 : diag::err_using_decl_nested_name_specifier_is_not_class)
13788 << SS.getScopeRep() << SS.getRange();
13789
13790 if (Cxx20Enumerator)
13791 return false; // OK
13792
13793 return true;
13794 }
13795
13796 if (!NamedContext->isDependentContext() &&
13797 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13798 return true;
13799
13800 // C++26 [namespace.udecl]p3:
13801 // In a using-declaration used as a member-declaration, each
13802 // using-declarator shall either name an enumerator or have a
13803 // nested-name-specifier naming a base class of the current class
13804 // ([expr.prim.this]). ...
13805 // "have a nested-name-specifier naming a base class of the current class"
13806 // was introduced by CWG400.
13807
13808 if (cast<CXXRecordDecl>(Val: CurContext)
13809 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13810
13811 if (Cxx20Enumerator) {
13812 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13813 << SS.getScopeRep() << SS.getRange();
13814 return false;
13815 }
13816
13817 if (CurContext == NamedContext) {
13818 Diag(Loc: SS.getBeginLoc(),
13819 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13820 << SS.getRange();
13821 return true;
13822 }
13823
13824 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13825 Diag(Loc: SS.getBeginLoc(),
13826 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13827 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13828 << SS.getRange();
13829 }
13830 return true;
13831 }
13832
13833 return false;
13834}
13835
13836Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13837 MultiTemplateParamsArg TemplateParamLists,
13838 SourceLocation UsingLoc, UnqualifiedId &Name,
13839 const ParsedAttributesView &AttrList,
13840 TypeResult Type, Decl *DeclFromDeclSpec) {
13841
13842 if (Type.isInvalid())
13843 return nullptr;
13844
13845 bool Invalid = false;
13846 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13847 TypeSourceInfo *TInfo = nullptr;
13848 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13849
13850 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13851 return nullptr;
13852
13853 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13854 UPPC: UPPC_DeclarationType)) {
13855 Invalid = true;
13856 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13857 Loc: TInfo->getTypeLoc().getBeginLoc());
13858 }
13859
13860 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13861 TemplateParamLists.size()
13862 ? forRedeclarationInCurContext()
13863 : RedeclarationKind::ForVisibleRedeclaration);
13864 LookupName(R&: Previous, S);
13865
13866 // Warn about shadowing the name of a template parameter.
13867 if (Previous.isSingleResult() &&
13868 Previous.getFoundDecl()->isTemplateParameter()) {
13869 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13870 Previous.clear();
13871 }
13872
13873 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13874 "name in alias declaration must be an identifier");
13875 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13876 IdLoc: Name.StartLocation,
13877 Id: Name.Identifier, TInfo);
13878
13879 NewTD->setAccess(AS);
13880
13881 if (Invalid)
13882 NewTD->setInvalidDecl();
13883
13884 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13885 AddPragmaAttributes(S, D: NewTD);
13886 ProcessAPINotes(D: NewTD);
13887
13888 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13889 Invalid |= NewTD->isInvalidDecl();
13890
13891 // Get the innermost enclosing declaration scope.
13892 S = S->getDeclParent();
13893
13894 bool Redeclaration = false;
13895
13896 NamedDecl *NewND;
13897 if (TemplateParamLists.size()) {
13898 TypeAliasTemplateDecl *OldDecl = nullptr;
13899 TemplateParameterList *OldTemplateParams = nullptr;
13900
13901 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13902 if (TemplateParamLists.size() != 1) {
13903 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13904 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13905 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13906 Invalid = true;
13907
13908 // Recover by picking the last non-empty template parameter list.
13909 auto It = llvm::find_if(
13910 Range: llvm::reverse(C&: TemplateParamLists),
13911 P: [](TemplateParameterList *TPL) { return !TPL->empty(); });
13912 assert(It != TemplateParamLists.rend() &&
13913 "if all template parameter lists were empty, this should have "
13914 "been rejected as an explicit specialization");
13915 TemplateParams = *It;
13916 }
13917
13918 // Check that we can declare a template here.
13919 if (CheckTemplateDeclScope(S, TemplateParams))
13920 return nullptr;
13921
13922 // Only consider previous declarations in the same scope.
13923 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13924 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13925 if (!Previous.empty()) {
13926 Redeclaration = true;
13927
13928 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13929 if (!OldDecl && !Invalid) {
13930 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13931 << Name.Identifier;
13932
13933 NamedDecl *OldD = Previous.getRepresentativeDecl();
13934 if (OldD->getLocation().isValid())
13935 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13936
13937 Invalid = true;
13938 }
13939
13940 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13941 if (TemplateParameterListsAreEqual(New: TemplateParams,
13942 Old: OldDecl->getTemplateParameters(),
13943 /*Complain=*/true,
13944 Kind: TPL_TemplateMatch))
13945 OldTemplateParams =
13946 OldDecl->getMostRecentDecl()->getTemplateParameters();
13947 else
13948 Invalid = true;
13949
13950 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13951 if (!Invalid &&
13952 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13953 T2: NewTD->getUnderlyingType())) {
13954 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13955 // but we can't reasonably accept it.
13956 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13957 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13958 if (OldTD->getLocation().isValid())
13959 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13960 Invalid = true;
13961 }
13962 }
13963 }
13964
13965 // Merge any previous default template arguments into our parameters,
13966 // and check the parameter list.
13967 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13968 TPC: TPC_Other))
13969 return nullptr;
13970
13971 TypeAliasTemplateDecl *NewDecl =
13972 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
13973 Name: Name.Identifier, Params: TemplateParams,
13974 Decl: NewTD);
13975 NewTD->setDescribedAliasTemplate(NewDecl);
13976
13977 NewDecl->setAccess(AS);
13978
13979 if (Invalid)
13980 NewDecl->setInvalidDecl();
13981 else if (OldDecl) {
13982 NewDecl->setPreviousDecl(OldDecl);
13983 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
13984 }
13985
13986 NewND = NewDecl;
13987 } else {
13988 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
13989 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
13990 handleTagNumbering(Tag: TD, TagScope: S);
13991 }
13992 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
13993 NewND = NewTD;
13994 }
13995
13996 PushOnScopeChains(D: NewND, S);
13997 ActOnDocumentableDecl(D: NewND);
13998 return NewND;
13999}
14000
14001Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
14002 SourceLocation AliasLoc,
14003 IdentifierInfo *Alias, CXXScopeSpec &SS,
14004 SourceLocation IdentLoc,
14005 IdentifierInfo *Ident) {
14006
14007 // Lookup the namespace name.
14008 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14009 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
14010
14011 if (R.isAmbiguous())
14012 return nullptr;
14013
14014 if (R.empty()) {
14015 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
14016 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
14017 return nullptr;
14018 }
14019 }
14020 assert(!R.isAmbiguous() && !R.empty());
14021 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
14022
14023 // Check if we have a previous declaration with the same name.
14024 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14025 RedeclarationKind::ForVisibleRedeclaration);
14026 LookupName(R&: PrevR, S);
14027
14028 // Check we're not shadowing a template parameter.
14029 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14030 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
14031 PrevR.clear();
14032 }
14033
14034 // Filter out any other lookup result from an enclosing scope.
14035 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14036 /*AllowInlineNamespace*/false);
14037
14038 // Find the previous declaration and check that we can redeclare it.
14039 NamespaceAliasDecl *Prev = nullptr;
14040 if (PrevR.isSingleResult()) {
14041 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14042 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14043 // We already have an alias with the same name that points to the same
14044 // namespace; check that it matches.
14045 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14046 Prev = AD;
14047 } else if (isVisible(D: PrevDecl)) {
14048 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14049 << Alias;
14050 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14051 << AD->getNamespace();
14052 return nullptr;
14053 }
14054 } else if (isVisible(D: PrevDecl)) {
14055 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14056 ? diag::err_redefinition
14057 : diag::err_redefinition_different_kind;
14058 Diag(Loc: AliasLoc, DiagID) << Alias;
14059 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14060 return nullptr;
14061 }
14062 }
14063
14064 // The use of a nested name specifier may trigger deprecation warnings.
14065 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14066
14067 NamespaceAliasDecl *AliasDecl =
14068 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14069 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14070 IdentLoc, Namespace: ND);
14071 if (Prev)
14072 AliasDecl->setPreviousDecl(Prev);
14073
14074 PushOnScopeChains(D: AliasDecl, S);
14075 return AliasDecl;
14076}
14077
14078namespace {
14079struct SpecialMemberExceptionSpecInfo
14080 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14081 SourceLocation Loc;
14082 Sema::ImplicitExceptionSpecification ExceptSpec;
14083
14084 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14085 CXXSpecialMemberKind CSM,
14086 Sema::InheritedConstructorInfo *ICI,
14087 SourceLocation Loc)
14088 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14089
14090 bool visitBase(CXXBaseSpecifier *Base);
14091 bool visitField(FieldDecl *FD);
14092
14093 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14094 unsigned Quals);
14095
14096 void visitSubobjectCall(Subobject Subobj,
14097 Sema::SpecialMemberOverloadResult SMOR);
14098};
14099}
14100
14101bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14102 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14103 if (!BaseClass)
14104 return false;
14105
14106 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14107 if (auto *BaseCtor = SMOR.getMethod()) {
14108 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14109 return false;
14110 }
14111
14112 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14113 return false;
14114}
14115
14116bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14117 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14118 FD->hasInClassInitializer()) {
14119 Expr *E = FD->getInClassInitializer();
14120 if (!E)
14121 // FIXME: It's a little wasteful to build and throw away a
14122 // CXXDefaultInitExpr here.
14123 // FIXME: We should have a single context note pointing at Loc, and
14124 // this location should be MD->getLocation() instead, since that's
14125 // the location where we actually use the default init expression.
14126 E = S.BuildCXXDefaultInitExpr(Loc, Field: FD).get();
14127 if (E)
14128 ExceptSpec.CalledExpr(E);
14129 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14130 ->getAsCXXRecordDecl()) {
14131 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14132 }
14133 return false;
14134}
14135
14136void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14137 Subobject Subobj,
14138 unsigned Quals) {
14139 FieldDecl *Field = Subobj.dyn_cast<FieldDecl*>();
14140 bool IsMutable = Field && Field->isMutable();
14141 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14142}
14143
14144void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14145 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14146 // Note, if lookup fails, it doesn't matter what exception specification we
14147 // choose because the special member will be deleted.
14148 if (CXXMethodDecl *MD = SMOR.getMethod())
14149 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14150}
14151
14152bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14153 llvm::APSInt Result;
14154 ExprResult Converted = CheckConvertedConstantExpression(
14155 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14156 ExplicitSpec.setExpr(Converted.get());
14157 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14158 ExplicitSpec.setKind(Result.getBoolValue()
14159 ? ExplicitSpecKind::ResolvedTrue
14160 : ExplicitSpecKind::ResolvedFalse);
14161 return true;
14162 }
14163 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14164 return false;
14165}
14166
14167ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14168 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14169 if (!ExplicitExpr->isTypeDependent())
14170 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14171 return ES;
14172}
14173
14174static Sema::ImplicitExceptionSpecification
14175ComputeDefaultedSpecialMemberExceptionSpec(
14176 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14177 Sema::InheritedConstructorInfo *ICI) {
14178 ComputingExceptionSpec CES(S, MD, Loc);
14179
14180 CXXRecordDecl *ClassDecl = MD->getParent();
14181
14182 // C++ [except.spec]p14:
14183 // An implicitly declared special member function (Clause 12) shall have an
14184 // exception-specification. [...]
14185 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14186 if (ClassDecl->isInvalidDecl())
14187 return Info.ExceptSpec;
14188
14189 // FIXME: If this diagnostic fires, we're probably missing a check for
14190 // attempting to resolve an exception specification before it's known
14191 // at a higher level.
14192 if (S.RequireCompleteType(Loc: MD->getLocation(),
14193 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14194 DiagID: diag::err_exception_spec_incomplete_type))
14195 return Info.ExceptSpec;
14196
14197 // C++1z [except.spec]p7:
14198 // [Look for exceptions thrown by] a constructor selected [...] to
14199 // initialize a potentially constructed subobject,
14200 // C++1z [except.spec]p8:
14201 // The exception specification for an implicitly-declared destructor, or a
14202 // destructor without a noexcept-specifier, is potentially-throwing if and
14203 // only if any of the destructors for any of its potentially constructed
14204 // subojects is potentially throwing.
14205 // FIXME: We respect the first rule but ignore the "potentially constructed"
14206 // in the second rule to resolve a core issue (no number yet) that would have
14207 // us reject:
14208 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14209 // struct B : A {};
14210 // struct C : B { void f(); };
14211 // ... due to giving B::~B() a non-throwing exception specification.
14212 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14213 : Info.VisitAllBases);
14214
14215 return Info.ExceptSpec;
14216}
14217
14218namespace {
14219/// RAII object to register a special member as being currently declared.
14220struct DeclaringSpecialMember {
14221 Sema &S;
14222 Sema::SpecialMemberDecl D;
14223 Sema::ContextRAII SavedContext;
14224 bool WasAlreadyBeingDeclared;
14225
14226 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14227 : S(S), D(RD, CSM), SavedContext(S, RD) {
14228 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14229 if (WasAlreadyBeingDeclared)
14230 // This almost never happens, but if it does, ensure that our cache
14231 // doesn't contain a stale result.
14232 S.SpecialMemberCache.clear();
14233 else {
14234 // Register a note to be produced if we encounter an error while
14235 // declaring the special member.
14236 Sema::CodeSynthesisContext Ctx;
14237 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14238 // FIXME: We don't have a location to use here. Using the class's
14239 // location maintains the fiction that we declare all special members
14240 // with the class, but (1) it's not clear that lying about that helps our
14241 // users understand what's going on, and (2) there may be outer contexts
14242 // on the stack (some of which are relevant) and printing them exposes
14243 // our lies.
14244 Ctx.PointOfInstantiation = RD->getLocation();
14245 Ctx.Entity = RD;
14246 Ctx.SpecialMember = CSM;
14247 S.pushCodeSynthesisContext(Ctx);
14248 }
14249 }
14250 ~DeclaringSpecialMember() {
14251 if (!WasAlreadyBeingDeclared) {
14252 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14253 S.popCodeSynthesisContext();
14254 }
14255 }
14256
14257 /// Are we already trying to declare this special member?
14258 bool isAlreadyBeingDeclared() const {
14259 return WasAlreadyBeingDeclared;
14260 }
14261};
14262}
14263
14264void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14265 // Look up any existing declarations, but don't trigger declaration of all
14266 // implicit special members with this name.
14267 DeclarationName Name = FD->getDeclName();
14268 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14269 RedeclarationKind::ForExternalRedeclaration);
14270 for (auto *D : FD->getParent()->lookup(Name))
14271 if (auto *Acceptable = R.getAcceptableDecl(D))
14272 R.addDecl(D: Acceptable);
14273 R.resolveKind();
14274 R.suppressDiagnostics();
14275
14276 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14277 DeclIsDefn: FD->isThisDeclarationADefinition());
14278}
14279
14280void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14281 QualType ResultTy,
14282 ArrayRef<QualType> Args) {
14283 // Build an exception specification pointing back at this constructor.
14284 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14285
14286 LangAS AS = getDefaultCXXMethodAddrSpace();
14287 if (AS != LangAS::Default) {
14288 EPI.TypeQuals.addAddressSpace(space: AS);
14289 }
14290
14291 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14292 SpecialMem->setType(QT);
14293
14294 // During template instantiation of implicit special member functions we need
14295 // a reliable TypeSourceInfo for the function prototype in order to allow
14296 // functions to be substituted.
14297 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14298 TypeSourceInfo *TSI =
14299 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14300 SpecialMem->setTypeSourceInfo(TSI);
14301 }
14302}
14303
14304CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14305 CXXRecordDecl *ClassDecl) {
14306 // C++ [class.ctor]p5:
14307 // A default constructor for a class X is a constructor of class X
14308 // that can be called without an argument. If there is no
14309 // user-declared constructor for class X, a default constructor is
14310 // implicitly declared. An implicitly-declared default constructor
14311 // is an inline public member of its class.
14312 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14313 "Should not build implicit default constructor!");
14314
14315 DeclaringSpecialMember DSM(*this, ClassDecl,
14316 CXXSpecialMemberKind::DefaultConstructor);
14317 if (DSM.isAlreadyBeingDeclared())
14318 return nullptr;
14319
14320 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14321 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14322
14323 // Create the actual constructor declaration.
14324 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14325 SourceLocation ClassLoc = ClassDecl->getLocation();
14326 DeclarationName Name
14327 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14328 DeclarationNameInfo NameInfo(Name, ClassLoc);
14329 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14330 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14331 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14332 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14333 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14334 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14335 : ConstexprSpecKind::Unspecified);
14336 DefaultCon->setAccess(AS_public);
14337 DefaultCon->setDefaulted();
14338
14339 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14340
14341 if (getLangOpts().CUDA)
14342 CUDA().inferTargetForImplicitSpecialMember(
14343 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14344 /* ConstRHS */ false,
14345 /* Diagnose */ false);
14346
14347 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14348 // constructors is easy to compute.
14349 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14350
14351 // Note that we have declared this constructor.
14352 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14353
14354 Scope *S = getScopeForContext(Ctx: ClassDecl);
14355 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14356
14357 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14358 CSM: CXXSpecialMemberKind::DefaultConstructor))
14359 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14360
14361 if (S)
14362 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14363 ClassDecl->addDecl(D: DefaultCon);
14364
14365 return DefaultCon;
14366}
14367
14368void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14369 CXXConstructorDecl *Constructor) {
14370 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14371 !Constructor->doesThisDeclarationHaveABody() &&
14372 !Constructor->isDeleted()) &&
14373 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14374 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14375 return;
14376
14377 CXXRecordDecl *ClassDecl = Constructor->getParent();
14378 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14379 if (ClassDecl->isInvalidDecl()) {
14380 return;
14381 }
14382
14383 SynthesizedFunctionScope Scope(*this, Constructor);
14384
14385 // The exception specification is needed because we are defining the
14386 // function.
14387 ResolveExceptionSpec(Loc: CurrentLocation,
14388 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14389 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14390
14391 // Add a context note for diagnostics produced after this point.
14392 Scope.addContextNote(UseLoc: CurrentLocation);
14393
14394 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14395 Constructor->setInvalidDecl();
14396 return;
14397 }
14398
14399 SourceLocation Loc = Constructor->getEndLoc().isValid()
14400 ? Constructor->getEndLoc()
14401 : Constructor->getLocation();
14402 Constructor->setBody(new (Context) CompoundStmt(Loc));
14403 Constructor->markUsed(C&: Context);
14404
14405 if (ASTMutationListener *L = getASTMutationListener()) {
14406 L->CompletedImplicitDefinition(D: Constructor);
14407 }
14408
14409 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14410
14411 // The synthesized body applies the class's NSDMIs and never reaches the
14412 // normal IssueWarnings path, so run lifetime safety on it here.
14413 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14414}
14415
14416void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14417 // Perform any delayed checks on exception specifications.
14418 CheckDelayedMemberExceptionSpecs();
14419}
14420
14421/// Find or create the fake constructor we synthesize to model constructing an
14422/// object of a derived class via a constructor of a base class.
14423CXXConstructorDecl *
14424Sema::findInheritingConstructor(SourceLocation Loc,
14425 CXXConstructorDecl *BaseCtor,
14426 ConstructorUsingShadowDecl *Shadow) {
14427 CXXRecordDecl *Derived = Shadow->getParent();
14428 SourceLocation UsingLoc = Shadow->getLocation();
14429
14430 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14431 // For now we use the name of the base class constructor as a member of the
14432 // derived class to indicate a (fake) inherited constructor name.
14433 DeclarationName Name = BaseCtor->getDeclName();
14434
14435 // Check to see if we already have a fake constructor for this inherited
14436 // constructor call.
14437 for (NamedDecl *Ctor : Derived->lookup(Name))
14438 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14439 ->getInheritedConstructor()
14440 .getConstructor(),
14441 D2: BaseCtor))
14442 return cast<CXXConstructorDecl>(Val: Ctor);
14443
14444 DeclarationNameInfo NameInfo(Name, UsingLoc);
14445 TypeSourceInfo *TInfo =
14446 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14447 FunctionProtoTypeLoc ProtoLoc =
14448 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14449
14450 // Check the inherited constructor is valid and find the list of base classes
14451 // from which it was inherited.
14452 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14453
14454 bool Constexpr = BaseCtor->isConstexpr() &&
14455 defaultedSpecialMemberIsConstexpr(
14456 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14457 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14458
14459 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14460 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14461 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14462 /*isInline=*/true,
14463 /*isImplicitlyDeclared=*/true,
14464 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14465 Inherited: InheritedConstructor(Shadow, BaseCtor),
14466 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14467 if (Shadow->isInvalidDecl())
14468 DerivedCtor->setInvalidDecl();
14469
14470 // Build an unevaluated exception specification for this fake constructor.
14471 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14472 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14473 EPI.ExceptionSpec.Type = EST_Unevaluated;
14474 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14475 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14476 Args: FPT->getParamTypes(), EPI));
14477
14478 // Build the parameter declarations.
14479 SmallVector<ParmVarDecl *, 16> ParamDecls;
14480 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14481 TypeSourceInfo *TInfo =
14482 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14483 ParmVarDecl *PD = ParmVarDecl::Create(
14484 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14485 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14486 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14487 PD->setImplicit();
14488 // Ensure attributes are propagated onto parameters (this matters for
14489 // format, pass_object_size, ...).
14490 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14491 ParamDecls.push_back(Elt: PD);
14492 ProtoLoc.setParam(i: I, VD: PD);
14493 }
14494
14495 // Set up the new constructor.
14496 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14497 DerivedCtor->setAccess(BaseCtor->getAccess());
14498 DerivedCtor->setParams(ParamDecls);
14499 Derived->addDecl(D: DerivedCtor);
14500
14501 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14502 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14503 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14504
14505 return DerivedCtor;
14506}
14507
14508void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14509 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14510 Ctor->getInheritedConstructor().getShadowDecl());
14511 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14512 ICI: &ICI,
14513 /*Diagnose*/ true);
14514}
14515
14516void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14517 CXXConstructorDecl *Constructor) {
14518 CXXRecordDecl *ClassDecl = Constructor->getParent();
14519 assert(Constructor->getInheritedConstructor() &&
14520 !Constructor->doesThisDeclarationHaveABody() &&
14521 !Constructor->isDeleted());
14522 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14523 return;
14524
14525 // Initializations are performed "as if by a defaulted default constructor",
14526 // so enter the appropriate scope.
14527 SynthesizedFunctionScope Scope(*this, Constructor);
14528
14529 // The exception specification is needed because we are defining the
14530 // function.
14531 ResolveExceptionSpec(Loc: CurrentLocation,
14532 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14533 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14534
14535 // Add a context note for diagnostics produced after this point.
14536 Scope.addContextNote(UseLoc: CurrentLocation);
14537
14538 ConstructorUsingShadowDecl *Shadow =
14539 Constructor->getInheritedConstructor().getShadowDecl();
14540 CXXConstructorDecl *InheritedCtor =
14541 Constructor->getInheritedConstructor().getConstructor();
14542
14543 // [class.inhctor.init]p1:
14544 // initialization proceeds as if a defaulted default constructor is used to
14545 // initialize the D object and each base class subobject from which the
14546 // constructor was inherited
14547
14548 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14549 CXXRecordDecl *RD = Shadow->getParent();
14550 SourceLocation InitLoc = Shadow->getLocation();
14551
14552 // Build explicit initializers for all base classes from which the
14553 // constructor was inherited.
14554 SmallVector<CXXCtorInitializer*, 8> Inits;
14555 for (bool VBase : {false, true}) {
14556 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14557 if (B.isVirtual() != VBase)
14558 continue;
14559
14560 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14561 if (!BaseRD)
14562 continue;
14563
14564 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14565 if (!BaseCtor.first)
14566 continue;
14567
14568 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14569 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14570 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14571
14572 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14573 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14574 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14575 SourceLocation()));
14576 }
14577 }
14578
14579 // We now proceed as if for a defaulted default constructor, with the relevant
14580 // initializers replaced.
14581
14582 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14583 Constructor->setInvalidDecl();
14584 return;
14585 }
14586
14587 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14588 Constructor->markUsed(C&: Context);
14589
14590 if (ASTMutationListener *L = getASTMutationListener()) {
14591 L->CompletedImplicitDefinition(D: Constructor);
14592 }
14593
14594 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14595
14596 // The synthesized body applies the class's NSDMIs and never reaches the
14597 // normal IssueWarnings path, so run lifetime safety on it here.
14598 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14599}
14600
14601CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14602 // C++ [class.dtor]p2:
14603 // If a class has no user-declared destructor, a destructor is
14604 // declared implicitly. An implicitly-declared destructor is an
14605 // inline public member of its class.
14606 assert(ClassDecl->needsImplicitDestructor());
14607
14608 DeclaringSpecialMember DSM(*this, ClassDecl,
14609 CXXSpecialMemberKind::Destructor);
14610 if (DSM.isAlreadyBeingDeclared())
14611 return nullptr;
14612
14613 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14614 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14615
14616 // Create the actual destructor declaration.
14617 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14618 SourceLocation ClassLoc = ClassDecl->getLocation();
14619 DeclarationName Name
14620 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14621 DeclarationNameInfo NameInfo(Name, ClassLoc);
14622 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14623 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14624 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14625 /*isInline=*/true,
14626 /*isImplicitlyDeclared=*/true,
14627 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14628 : ConstexprSpecKind::Unspecified);
14629 Destructor->setAccess(AS_public);
14630 Destructor->setDefaulted();
14631
14632 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14633
14634 if (getLangOpts().CUDA)
14635 CUDA().inferTargetForImplicitSpecialMember(
14636 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14637 /* ConstRHS */ false,
14638 /* Diagnose */ false);
14639
14640 // We don't need to use SpecialMemberIsTrivial here; triviality for
14641 // destructors is easy to compute.
14642 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14643 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14644 ClassDecl->hasTrivialDestructorForCall());
14645
14646 // Note that we have declared this destructor.
14647 ++getASTContext().NumImplicitDestructorsDeclared;
14648
14649 Scope *S = getScopeForContext(Ctx: ClassDecl);
14650 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14651
14652 // We can't check whether an implicit destructor is deleted before we complete
14653 // the definition of the class, because its validity depends on the alignment
14654 // of the class. We'll check this from ActOnFields once the class is complete.
14655 if (ClassDecl->isCompleteDefinition() &&
14656 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14657 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14658
14659 // Introduce this destructor into its scope.
14660 if (S)
14661 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14662 ClassDecl->addDecl(D: Destructor);
14663
14664 return Destructor;
14665}
14666
14667void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14668 CXXDestructorDecl *Destructor) {
14669 assert((Destructor->isDefaulted() &&
14670 !Destructor->doesThisDeclarationHaveABody() &&
14671 !Destructor->isDeleted()) &&
14672 "DefineImplicitDestructor - call it for implicit default dtor");
14673 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14674 return;
14675
14676 CXXRecordDecl *ClassDecl = Destructor->getParent();
14677 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14678
14679 SynthesizedFunctionScope Scope(*this, Destructor);
14680
14681 // The exception specification is needed because we are defining the
14682 // function.
14683 ResolveExceptionSpec(Loc: CurrentLocation,
14684 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14685 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14686
14687 // Add a context note for diagnostics produced after this point.
14688 Scope.addContextNote(UseLoc: CurrentLocation);
14689
14690 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14691 ClassDecl: Destructor->getParent());
14692
14693 if (CheckDestructor(Destructor)) {
14694 Destructor->setInvalidDecl();
14695 return;
14696 }
14697
14698 SourceLocation Loc = Destructor->getEndLoc().isValid()
14699 ? Destructor->getEndLoc()
14700 : Destructor->getLocation();
14701 Destructor->setBody(new (Context) CompoundStmt(Loc));
14702 Destructor->markUsed(C&: Context);
14703
14704 if (ASTMutationListener *L = getASTMutationListener()) {
14705 L->CompletedImplicitDefinition(D: Destructor);
14706 }
14707}
14708
14709void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14710 CXXDestructorDecl *Destructor) {
14711 if (Destructor->isInvalidDecl())
14712 return;
14713
14714 CXXRecordDecl *ClassDecl = Destructor->getParent();
14715 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14716 "implicit complete dtors unneeded outside MS ABI");
14717 assert(ClassDecl->getNumVBases() > 0 &&
14718 "complete dtor only exists for classes with vbases");
14719
14720 SynthesizedFunctionScope Scope(*this, Destructor);
14721
14722 // Add a context note for diagnostics produced after this point.
14723 Scope.addContextNote(UseLoc: CurrentLocation);
14724
14725 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14726}
14727
14728void Sema::ActOnFinishCXXMemberDecls() {
14729 // If the context is an invalid C++ class, just suppress these checks.
14730 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14731 if (Record->isInvalidDecl()) {
14732 DelayedOverridingExceptionSpecChecks.clear();
14733 DelayedEquivalentExceptionSpecChecks.clear();
14734 return;
14735 }
14736 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14737 }
14738}
14739
14740void Sema::ActOnFinishCXXNonNestedClass() {
14741 referenceDLLExportedClassMethods();
14742
14743 if (!DelayedDllExportMemberFunctions.empty()) {
14744 SmallVector<CXXMethodDecl*, 4> WorkList;
14745 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14746 for (CXXMethodDecl *M : WorkList) {
14747 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14748
14749 // Pass the method to the consumer to get emitted. This is not necessary
14750 // for explicit instantiation definitions, as they will get emitted
14751 // anyway.
14752 if (M->getParent()->getTemplateSpecializationKind() !=
14753 TSK_ExplicitInstantiationDefinition)
14754 ActOnFinishInlineFunctionDef(D: M);
14755 }
14756 }
14757}
14758
14759void Sema::referenceDLLExportedClassMethods() {
14760 if (!DelayedDllExportClasses.empty()) {
14761 // Calling ReferenceDllExportedMembers might cause the current function to
14762 // be called again, so use a local copy of DelayedDllExportClasses.
14763 SmallVector<CXXRecordDecl *, 4> WorkList;
14764 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14765 for (CXXRecordDecl *Class : WorkList)
14766 ReferenceDllExportedMembers(S&: *this, Class);
14767 }
14768}
14769
14770void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14771 assert(getLangOpts().CPlusPlus11 &&
14772 "adjusting dtor exception specs was introduced in c++11");
14773
14774 if (Destructor->isDependentContext())
14775 return;
14776
14777 // C++11 [class.dtor]p3:
14778 // A declaration of a destructor that does not have an exception-
14779 // specification is implicitly considered to have the same exception-
14780 // specification as an implicit declaration.
14781 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14782 if (DtorType->hasExceptionSpec())
14783 return;
14784
14785 // Replace the destructor's type, building off the existing one. Fortunately,
14786 // the only thing of interest in the destructor type is its extended info.
14787 // The return and arguments are fixed.
14788 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14789 EPI.ExceptionSpec.Type = EST_Unevaluated;
14790 EPI.ExceptionSpec.SourceDecl = Destructor;
14791 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14792
14793 // FIXME: If the destructor has a body that could throw, and the newly created
14794 // spec doesn't allow exceptions, we should emit a warning, because this
14795 // change in behavior can break conforming C++03 programs at runtime.
14796 // However, we don't have a body or an exception specification yet, so it
14797 // needs to be done somewhere else.
14798}
14799
14800namespace {
14801/// An abstract base class for all helper classes used in building the
14802// copy/move operators. These classes serve as factory functions and help us
14803// avoid using the same Expr* in the AST twice.
14804class ExprBuilder {
14805 ExprBuilder(const ExprBuilder&) = delete;
14806 ExprBuilder &operator=(const ExprBuilder&) = delete;
14807
14808protected:
14809 static Expr *assertNotNull(Expr *E) {
14810 assert(E && "Expression construction must not fail.");
14811 return E;
14812 }
14813
14814public:
14815 ExprBuilder() {}
14816 virtual ~ExprBuilder() {}
14817
14818 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14819};
14820
14821class RefBuilder: public ExprBuilder {
14822 VarDecl *Var;
14823 QualType VarType;
14824
14825public:
14826 Expr *build(Sema &S, SourceLocation Loc) const override {
14827 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14828 }
14829
14830 RefBuilder(VarDecl *Var, QualType VarType)
14831 : Var(Var), VarType(VarType) {}
14832};
14833
14834class ThisBuilder: public ExprBuilder {
14835public:
14836 Expr *build(Sema &S, SourceLocation Loc) const override {
14837 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14838 }
14839};
14840
14841class CastBuilder: public ExprBuilder {
14842 const ExprBuilder &Builder;
14843 QualType Type;
14844 ExprValueKind Kind;
14845 const CXXCastPath &Path;
14846
14847public:
14848 Expr *build(Sema &S, SourceLocation Loc) const override {
14849 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14850 CK: CK_UncheckedDerivedToBase, VK: Kind,
14851 BasePath: &Path).get());
14852 }
14853
14854 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14855 const CXXCastPath &Path)
14856 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14857};
14858
14859class DerefBuilder: public ExprBuilder {
14860 const ExprBuilder &Builder;
14861
14862public:
14863 Expr *build(Sema &S, SourceLocation Loc) const override {
14864 return assertNotNull(
14865 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14866 }
14867
14868 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14869};
14870
14871class MemberBuilder: public ExprBuilder {
14872 const ExprBuilder &Builder;
14873 QualType Type;
14874 CXXScopeSpec SS;
14875 bool IsArrow;
14876 LookupResult &MemberLookup;
14877
14878public:
14879 Expr *build(Sema &S, SourceLocation Loc) const override {
14880 return assertNotNull(E: S.BuildMemberReferenceExpr(
14881 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14882 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14883 }
14884
14885 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14886 LookupResult &MemberLookup)
14887 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14888 MemberLookup(MemberLookup) {}
14889};
14890
14891class MoveCastBuilder: public ExprBuilder {
14892 const ExprBuilder &Builder;
14893
14894public:
14895 Expr *build(Sema &S, SourceLocation Loc) const override {
14896 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14897 }
14898
14899 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14900};
14901
14902class LvalueConvBuilder: public ExprBuilder {
14903 const ExprBuilder &Builder;
14904
14905public:
14906 Expr *build(Sema &S, SourceLocation Loc) const override {
14907 return assertNotNull(
14908 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14909 }
14910
14911 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14912};
14913
14914class SubscriptBuilder: public ExprBuilder {
14915 const ExprBuilder &Base;
14916 const ExprBuilder &Index;
14917
14918public:
14919 Expr *build(Sema &S, SourceLocation Loc) const override {
14920 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14921 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14922 }
14923
14924 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14925 : Base(Base), Index(Index) {}
14926};
14927
14928} // end anonymous namespace
14929
14930/// When generating a defaulted copy or move assignment operator, if a field
14931/// should be copied with __builtin_memcpy rather than via explicit assignments,
14932/// do so. This optimization only applies for arrays of scalars, and for arrays
14933/// of class type where the selected copy/move-assignment operator is trivial.
14934static StmtResult
14935buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14936 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14937 // Compute the size of the memory buffer to be copied.
14938 QualType SizeType = S.Context.getSizeType();
14939 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14940 S.Context.getTypeSizeInChars(T).getQuantity());
14941
14942 // Take the address of the field references for "from" and "to". We
14943 // directly construct UnaryOperators here because semantic analysis
14944 // does not permit us to take the address of an xvalue.
14945 Expr *From = FromB.build(S, Loc);
14946 From = UnaryOperator::Create(
14947 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14948 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14949 Expr *To = ToB.build(S, Loc);
14950 To = UnaryOperator::Create(
14951 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14952 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14953
14954 bool NeedsCollectableMemCpy = false;
14955 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14956 NeedsCollectableMemCpy = RD->hasObjectMember();
14957
14958 // Create a reference to the __builtin_objc_memmove_collectable function
14959 StringRef MemCpyName = NeedsCollectableMemCpy ?
14960 "__builtin_objc_memmove_collectable" :
14961 "__builtin_memcpy";
14962 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14963 Sema::LookupOrdinaryName);
14964 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14965
14966 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14967 if (!MemCpy)
14968 // Something went horribly wrong earlier, and we will have complained
14969 // about it.
14970 return StmtError();
14971
14972 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
14973 VK: VK_PRValue, Loc, SS: nullptr);
14974 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
14975
14976 Expr *CallArgs[] = {
14977 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
14978 };
14979 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
14980 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
14981
14982 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
14983 return Call.getAs<Stmt>();
14984}
14985
14986/// Builds a statement that copies/moves the given entity from \p From to
14987/// \c To.
14988///
14989/// This routine is used to copy/move the members of a class with an
14990/// implicitly-declared copy/move assignment operator. When the entities being
14991/// copied are arrays, this routine builds for loops to copy them.
14992///
14993/// \param S The Sema object used for type-checking.
14994///
14995/// \param Loc The location where the implicit copy/move is being generated.
14996///
14997/// \param T The type of the expressions being copied/moved. Both expressions
14998/// must have this type.
14999///
15000/// \param To The expression we are copying/moving to.
15001///
15002/// \param From The expression we are copying/moving from.
15003///
15004/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15005/// Otherwise, it's a non-static member subobject.
15006///
15007/// \param Copying Whether we're copying or moving.
15008///
15009/// \param Depth Internal parameter recording the depth of the recursion.
15010///
15011/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15012/// if a memcpy should be used instead.
15013static StmtResult
15014buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
15015 const ExprBuilder &To, const ExprBuilder &From,
15016 bool CopyingBaseSubobject, bool Copying,
15017 unsigned Depth = 0) {
15018 // C++11 [class.copy]p28:
15019 // Each subobject is assigned in the manner appropriate to its type:
15020 //
15021 // - if the subobject is of class type, as if by a call to operator= with
15022 // the subobject as the object expression and the corresponding
15023 // subobject of x as a single function argument (as if by explicit
15024 // qualification; that is, ignoring any possible virtual overriding
15025 // functions in more derived classes);
15026 //
15027 // C++03 [class.copy]p13:
15028 // - if the subobject is of class type, the copy assignment operator for
15029 // the class is used (as if by explicit qualification; that is,
15030 // ignoring any possible virtual overriding functions in more derived
15031 // classes);
15032 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15033 // Look for operator=.
15034 DeclarationName Name
15035 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15036 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15037 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
15038
15039 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15040 // operator.
15041 if (!S.getLangOpts().CPlusPlus11) {
15042 LookupResult::Filter F = OpLookup.makeFilter();
15043 while (F.hasNext()) {
15044 NamedDecl *D = F.next();
15045 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15046 if (Method->isCopyAssignmentOperator() ||
15047 (!Copying && Method->isMoveAssignmentOperator()))
15048 continue;
15049
15050 F.erase();
15051 }
15052 F.done();
15053 }
15054
15055 // Suppress the protected check (C++ [class.protected]) for each of the
15056 // assignment operators we found. This strange dance is required when
15057 // we're assigning via a base classes's copy-assignment operator. To
15058 // ensure that we're getting the right base class subobject (without
15059 // ambiguities), we need to cast "this" to that subobject type; to
15060 // ensure that we don't go through the virtual call mechanism, we need
15061 // to qualify the operator= name with the base class (see below). However,
15062 // this means that if the base class has a protected copy assignment
15063 // operator, the protected member access check will fail. So, we
15064 // rewrite "protected" access to "public" access in this case, since we
15065 // know by construction that we're calling from a derived class.
15066 if (CopyingBaseSubobject) {
15067 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15068 L != LEnd; ++L) {
15069 if (L.getAccess() == AS_protected)
15070 L.setAccess(AS_public);
15071 }
15072 }
15073
15074 // Create the nested-name-specifier that will be used to qualify the
15075 // reference to operator=; this is required to suppress the virtual
15076 // call mechanism.
15077 CXXScopeSpec SS;
15078 // FIXME: Don't canonicalize this.
15079 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15080 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15081
15082 // Create the reference to operator=.
15083 ExprResult OpEqualRef
15084 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15085 SS, /*TemplateKWLoc=*/SourceLocation(),
15086 /*FirstQualifierInScope=*/nullptr,
15087 R&: OpLookup,
15088 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15089 /*SuppressQualifierCheck=*/true);
15090 if (OpEqualRef.isInvalid())
15091 return StmtError();
15092
15093 // Build the call to the assignment operator.
15094
15095 Expr *FromInst = From.build(S, Loc);
15096 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15097 MemExpr: OpEqualRef.getAs<Expr>(),
15098 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15099 if (Call.isInvalid())
15100 return StmtError();
15101
15102 // If we built a call to a trivial 'operator=' while copying an array,
15103 // bail out. We'll replace the whole shebang with a memcpy.
15104 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15105 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15106 return StmtResult((Stmt*)nullptr);
15107
15108 // Convert to an expression-statement, and clean up any produced
15109 // temporaries.
15110 return S.ActOnExprStmt(Arg: Call);
15111 }
15112
15113 // - if the subobject is of scalar type, the built-in assignment
15114 // operator is used.
15115 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15116 if (!ArrayTy) {
15117 ExprResult Assignment = S.CreateBuiltinBinOp(
15118 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15119 if (Assignment.isInvalid())
15120 return StmtError();
15121 return S.ActOnExprStmt(Arg: Assignment);
15122 }
15123
15124 // - if the subobject is an array, each element is assigned, in the
15125 // manner appropriate to the element type;
15126
15127 // Construct a loop over the array bounds, e.g.,
15128 //
15129 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15130 //
15131 // that will copy each of the array elements.
15132 QualType SizeType = S.Context.getSizeType();
15133
15134 // Create the iteration variable.
15135 IdentifierInfo *IterationVarName = nullptr;
15136 {
15137 SmallString<8> Str;
15138 llvm::raw_svector_ostream OS(Str);
15139 OS << "__i" << Depth;
15140 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15141 }
15142 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15143 Id: IterationVarName, T: SizeType,
15144 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15145 S: SC_None);
15146
15147 // Initialize the iteration variable to zero.
15148 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15149 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15150
15151 // Creates a reference to the iteration variable.
15152 RefBuilder IterationVarRef(IterationVar, SizeType);
15153 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15154
15155 // Create the DeclStmt that holds the iteration variable.
15156 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15157
15158 // Subscript the "from" and "to" expressions with the iteration variable.
15159 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15160 MoveCastBuilder FromIndexMove(FromIndexCopy);
15161 const ExprBuilder *FromIndex;
15162 if (Copying)
15163 FromIndex = &FromIndexCopy;
15164 else
15165 FromIndex = &FromIndexMove;
15166
15167 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15168
15169 // Build the copy/move for an individual element of the array.
15170 StmtResult Copy =
15171 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15172 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15173 Copying, Depth: Depth + 1);
15174 // Bail out if copying fails or if we determined that we should use memcpy.
15175 if (Copy.isInvalid() || !Copy.get())
15176 return Copy;
15177
15178 // Create the comparison against the array bound.
15179 llvm::APInt Upper
15180 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15181 Expr *Comparison = BinaryOperator::Create(
15182 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15183 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15184 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15185 FPFeatures: S.CurFPFeatureOverrides());
15186
15187 // Create the pre-increment of the iteration variable. We can determine
15188 // whether the increment will overflow based on the value of the array
15189 // bound.
15190 Expr *Increment = UnaryOperator::Create(
15191 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15192 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15193
15194 // Construct the loop that copies all elements of this array.
15195 return S.ActOnForStmt(
15196 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15197 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15198 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15199}
15200
15201static StmtResult
15202buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15203 const ExprBuilder &To, const ExprBuilder &From,
15204 bool CopyingBaseSubobject, bool Copying) {
15205 // Maybe we should use a memcpy?
15206 if (T->isArrayType() && !T.hasQualifiers() &&
15207 T.isTriviallyCopyableType(Context: S.Context))
15208 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15209
15210 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15211 CopyingBaseSubobject,
15212 Copying, Depth: 0));
15213
15214 // If we ended up picking a trivial assignment operator for an array of a
15215 // non-trivially-copyable class type, just emit a memcpy.
15216 if (!Result.isInvalid() && !Result.get())
15217 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15218
15219 return Result;
15220}
15221
15222CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15223 // Note: The following rules are largely analoguous to the copy
15224 // constructor rules. Note that virtual bases are not taken into account
15225 // for determining the argument type of the operator. Note also that
15226 // operators taking an object instead of a reference are allowed.
15227 assert(ClassDecl->needsImplicitCopyAssignment());
15228
15229 DeclaringSpecialMember DSM(*this, ClassDecl,
15230 CXXSpecialMemberKind::CopyAssignment);
15231 if (DSM.isAlreadyBeingDeclared())
15232 return nullptr;
15233
15234 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15235 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15236 /*OwnsTag=*/false);
15237 LangAS AS = getDefaultCXXMethodAddrSpace();
15238 if (AS != LangAS::Default)
15239 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15240 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15241 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15242 if (Const)
15243 ArgType = ArgType.withConst();
15244
15245 ArgType = Context.getLValueReferenceType(T: ArgType);
15246
15247 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15248 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15249
15250 // An implicitly-declared copy assignment operator is an inline public
15251 // member of its class.
15252 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15253 SourceLocation ClassLoc = ClassDecl->getLocation();
15254 DeclarationNameInfo NameInfo(Name, ClassLoc);
15255 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15256 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15257 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15258 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15259 /*isInline=*/true,
15260 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15261 EndLocation: SourceLocation());
15262 CopyAssignment->setAccess(AS_public);
15263 CopyAssignment->setDefaulted();
15264 CopyAssignment->setImplicit();
15265
15266 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15267
15268 if (getLangOpts().CUDA)
15269 CUDA().inferTargetForImplicitSpecialMember(
15270 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15271 /* ConstRHS */ Const,
15272 /* Diagnose */ false);
15273
15274 // Add the parameter to the operator.
15275 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15276 StartLoc: ClassLoc, IdLoc: ClassLoc,
15277 /*Id=*/nullptr, T: ArgType,
15278 /*TInfo=*/nullptr, S: SC_None,
15279 DefArg: nullptr);
15280 CopyAssignment->setParams(FromParam);
15281
15282 CopyAssignment->setTrivial(
15283 ClassDecl->needsOverloadResolutionForCopyAssignment()
15284 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15285 CSM: CXXSpecialMemberKind::CopyAssignment)
15286 : ClassDecl->hasTrivialCopyAssignment());
15287
15288 // Note that we have added this copy-assignment operator.
15289 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15290
15291 Scope *S = getScopeForContext(Ctx: ClassDecl);
15292 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15293
15294 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15295 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15296 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15297 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15298 }
15299
15300 if (S)
15301 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15302 ClassDecl->addDecl(D: CopyAssignment);
15303
15304 return CopyAssignment;
15305}
15306
15307/// Diagnose an implicit copy operation for a class which is odr-used, but
15308/// which is deprecated because the class has a user-declared copy constructor,
15309/// copy assignment operator, or destructor.
15310static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15311 assert(CopyOp->isImplicit());
15312
15313 CXXRecordDecl *RD = CopyOp->getParent();
15314 CXXMethodDecl *UserDeclaredOperation = nullptr;
15315
15316 if (RD->hasUserDeclaredDestructor()) {
15317 UserDeclaredOperation = RD->getDestructor();
15318 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15319 RD->hasUserDeclaredCopyConstructor()) {
15320 // Find any user-declared copy constructor.
15321 for (auto *I : RD->ctors()) {
15322 if (I->isCopyConstructor()) {
15323 UserDeclaredOperation = I;
15324 break;
15325 }
15326 }
15327 assert(UserDeclaredOperation);
15328 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15329 RD->hasUserDeclaredCopyAssignment()) {
15330 // Find any user-declared move assignment operator.
15331 for (auto *I : RD->methods()) {
15332 if (I->isCopyAssignmentOperator()) {
15333 UserDeclaredOperation = I;
15334 break;
15335 }
15336 }
15337 assert(UserDeclaredOperation);
15338 }
15339
15340 if (UserDeclaredOperation) {
15341 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15342 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15343 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15344 unsigned DiagID =
15345 (UDOIsUserProvided && UDOIsDestructor)
15346 ? diag::warn_deprecated_copy_with_user_provided_dtor
15347 : (UDOIsUserProvided && !UDOIsDestructor)
15348 ? diag::warn_deprecated_copy_with_user_provided_copy
15349 : (!UDOIsUserProvided && UDOIsDestructor)
15350 ? diag::warn_deprecated_copy_with_dtor
15351 : diag::warn_deprecated_copy;
15352 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15353 << RD << IsCopyAssignment;
15354 }
15355}
15356
15357void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15358 CXXMethodDecl *CopyAssignOperator) {
15359 assert((CopyAssignOperator->isDefaulted() &&
15360 CopyAssignOperator->isOverloadedOperator() &&
15361 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15362 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15363 !CopyAssignOperator->isDeleted()) &&
15364 "DefineImplicitCopyAssignment called for wrong function");
15365 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15366 return;
15367
15368 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15369 if (ClassDecl->isInvalidDecl()) {
15370 CopyAssignOperator->setInvalidDecl();
15371 return;
15372 }
15373
15374 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15375
15376 // The exception specification is needed because we are defining the
15377 // function.
15378 ResolveExceptionSpec(Loc: CurrentLocation,
15379 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15380
15381 // Add a context note for diagnostics produced after this point.
15382 Scope.addContextNote(UseLoc: CurrentLocation);
15383
15384 // C++11 [class.copy]p18:
15385 // The [definition of an implicitly declared copy assignment operator] is
15386 // deprecated if the class has a user-declared copy constructor or a
15387 // user-declared destructor.
15388 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15389 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15390
15391 // C++0x [class.copy]p30:
15392 // The implicitly-defined or explicitly-defaulted copy assignment operator
15393 // for a non-union class X performs memberwise copy assignment of its
15394 // subobjects. The direct base classes of X are assigned first, in the
15395 // order of their declaration in the base-specifier-list, and then the
15396 // immediate non-static data members of X are assigned, in the order in
15397 // which they were declared in the class definition.
15398
15399 // The statements that form the synthesized function body.
15400 SmallVector<Stmt*, 8> Statements;
15401
15402 // The parameter for the "other" object, which we are copying from.
15403 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15404 Qualifiers OtherQuals = Other->getType().getQualifiers();
15405 QualType OtherRefType = Other->getType();
15406 if (OtherRefType->isLValueReferenceType()) {
15407 OtherRefType = OtherRefType->getPointeeType();
15408 OtherQuals = OtherRefType.getQualifiers();
15409 }
15410
15411 // Our location for everything implicitly-generated.
15412 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15413 ? CopyAssignOperator->getEndLoc()
15414 : CopyAssignOperator->getLocation();
15415
15416 // Builds a DeclRefExpr for the "other" object.
15417 RefBuilder OtherRef(Other, OtherRefType);
15418
15419 // Builds the function object parameter.
15420 std::optional<ThisBuilder> This;
15421 std::optional<DerefBuilder> DerefThis;
15422 std::optional<RefBuilder> ExplicitObject;
15423 bool IsArrow = false;
15424 QualType ObjectType;
15425 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15426 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15427 if (ObjectType->isReferenceType())
15428 ObjectType = ObjectType->getPointeeType();
15429 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15430 } else {
15431 ObjectType = getCurrentThisType();
15432 This.emplace();
15433 DerefThis.emplace(args&: *This);
15434 IsArrow = !LangOpts.HLSL;
15435 }
15436 ExprBuilder &ObjectParameter =
15437 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15438 : static_cast<ExprBuilder &>(*This);
15439
15440 // Assign base classes.
15441 bool Invalid = false;
15442 for (auto &Base : ClassDecl->bases()) {
15443 // Form the assignment:
15444 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15445 QualType BaseType = Base.getType().getUnqualifiedType();
15446 if (!BaseType->isRecordType()) {
15447 Invalid = true;
15448 continue;
15449 }
15450
15451 CXXCastPath BasePath;
15452 BasePath.push_back(Elt: &Base);
15453
15454 // Construct the "from" expression, which is an implicit cast to the
15455 // appropriately-qualified base type.
15456 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15457 VK_LValue, BasePath);
15458
15459 // Dereference "this".
15460 CastBuilder To(
15461 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15462 : static_cast<ExprBuilder &>(*DerefThis),
15463 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15464 VK_LValue, BasePath);
15465
15466 // Build the copy.
15467 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15468 To, From,
15469 /*CopyingBaseSubobject=*/true,
15470 /*Copying=*/true);
15471 if (Copy.isInvalid()) {
15472 CopyAssignOperator->setInvalidDecl();
15473 return;
15474 }
15475
15476 // Success! Record the copy.
15477 Statements.push_back(Elt: Copy.getAs<Expr>());
15478 }
15479
15480 // Assign non-static members.
15481 for (auto *Field : ClassDecl->fields()) {
15482 // FIXME: We should form some kind of AST representation for the implied
15483 // memcpy in a union copy operation.
15484 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15485 continue;
15486
15487 if (Field->isInvalidDecl()) {
15488 Invalid = true;
15489 continue;
15490 }
15491
15492 // Check for members of reference type; we can't copy those.
15493 if (Field->getType()->isReferenceType()) {
15494 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15495 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15496 << Field->getDeclName();
15497 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15498 Invalid = true;
15499 continue;
15500 }
15501
15502 // Check for members of const-qualified, non-class type.
15503 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15504 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15505 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15506 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15507 << Field->getDeclName();
15508 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15509 Invalid = true;
15510 continue;
15511 }
15512
15513 // Suppress assigning zero-width bitfields.
15514 if (Field->isZeroLengthBitField())
15515 continue;
15516
15517 QualType FieldType = Field->getType().getNonReferenceType();
15518 if (FieldType->isIncompleteArrayType()) {
15519 assert(ClassDecl->hasFlexibleArrayMember() &&
15520 "Incomplete array type is not valid");
15521 continue;
15522 }
15523
15524 // Build references to the field in the object we're copying from and to.
15525 CXXScopeSpec SS; // Intentionally empty
15526 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15527 LookupMemberName);
15528 MemberLookup.addDecl(D: Field);
15529 MemberLookup.resolveKind();
15530
15531 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15532 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15533 // Build the copy of this field.
15534 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15535 To, From,
15536 /*CopyingBaseSubobject=*/false,
15537 /*Copying=*/true);
15538 if (Copy.isInvalid()) {
15539 CopyAssignOperator->setInvalidDecl();
15540 return;
15541 }
15542
15543 // Success! Record the copy.
15544 Statements.push_back(Elt: Copy.getAs<Stmt>());
15545 }
15546
15547 if (!Invalid) {
15548 // Add a "return *this;"
15549 Expr *ThisExpr =
15550 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15551 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15552 : static_cast<ExprBuilder &>(*DerefThis))
15553 .build(S&: *this, Loc);
15554 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15555 if (Return.isInvalid())
15556 Invalid = true;
15557 else
15558 Statements.push_back(Elt: Return.getAs<Stmt>());
15559 }
15560
15561 if (Invalid) {
15562 CopyAssignOperator->setInvalidDecl();
15563 return;
15564 }
15565
15566 StmtResult Body;
15567 {
15568 CompoundScopeRAII CompoundScope(*this);
15569 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15570 /*isStmtExpr=*/false);
15571 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15572 }
15573 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15574 CopyAssignOperator->markUsed(C&: Context);
15575
15576 if (ASTMutationListener *L = getASTMutationListener()) {
15577 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15578 }
15579}
15580
15581CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15582 assert(ClassDecl->needsImplicitMoveAssignment());
15583
15584 DeclaringSpecialMember DSM(*this, ClassDecl,
15585 CXXSpecialMemberKind::MoveAssignment);
15586 if (DSM.isAlreadyBeingDeclared())
15587 return nullptr;
15588
15589 // Note: The following rules are largely analoguous to the move
15590 // constructor rules.
15591
15592 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15593 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15594 /*OwnsTag=*/false);
15595 LangAS AS = getDefaultCXXMethodAddrSpace();
15596 if (AS != LangAS::Default)
15597 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15598 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15599 ArgType = Context.getRValueReferenceType(T: ArgType);
15600
15601 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15602 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15603
15604 // An implicitly-declared move assignment operator is an inline public
15605 // member of its class.
15606 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15607 SourceLocation ClassLoc = ClassDecl->getLocation();
15608 DeclarationNameInfo NameInfo(Name, ClassLoc);
15609 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15610 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15611 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15612 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15613 /*isInline=*/true,
15614 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15615 EndLocation: SourceLocation());
15616 MoveAssignment->setAccess(AS_public);
15617 MoveAssignment->setDefaulted();
15618 MoveAssignment->setImplicit();
15619
15620 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15621
15622 if (getLangOpts().CUDA)
15623 CUDA().inferTargetForImplicitSpecialMember(
15624 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15625 /* ConstRHS */ false,
15626 /* Diagnose */ false);
15627
15628 // Add the parameter to the operator.
15629 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15630 StartLoc: ClassLoc, IdLoc: ClassLoc,
15631 /*Id=*/nullptr, T: ArgType,
15632 /*TInfo=*/nullptr, S: SC_None,
15633 DefArg: nullptr);
15634 MoveAssignment->setParams(FromParam);
15635
15636 MoveAssignment->setTrivial(
15637 ClassDecl->needsOverloadResolutionForMoveAssignment()
15638 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15639 CSM: CXXSpecialMemberKind::MoveAssignment)
15640 : ClassDecl->hasTrivialMoveAssignment());
15641
15642 // Note that we have added this copy-assignment operator.
15643 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15644
15645 Scope *S = getScopeForContext(Ctx: ClassDecl);
15646 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15647
15648 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15649 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15650 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15651 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15652 }
15653
15654 if (S)
15655 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15656 ClassDecl->addDecl(D: MoveAssignment);
15657
15658 return MoveAssignment;
15659}
15660
15661/// Check if we're implicitly defining a move assignment operator for a class
15662/// with virtual bases. Such a move assignment might move-assign the virtual
15663/// base multiple times.
15664static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15665 SourceLocation CurrentLocation) {
15666 assert(!Class->isDependentContext() && "should not define dependent move");
15667
15668 // Only a virtual base could get implicitly move-assigned multiple times.
15669 // Only a non-trivial move assignment can observe this. We only want to
15670 // diagnose if we implicitly define an assignment operator that assigns
15671 // two base classes, both of which move-assign the same virtual base.
15672 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15673 Class->getNumBases() < 2)
15674 return;
15675
15676 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15677 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15678 VBaseMap VBases;
15679
15680 for (auto &BI : Class->bases()) {
15681 Worklist.push_back(Elt: &BI);
15682 while (!Worklist.empty()) {
15683 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15684 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15685
15686 // If the base has no non-trivial move assignment operators,
15687 // we don't care about moves from it.
15688 if (!Base->hasNonTrivialMoveAssignment())
15689 continue;
15690
15691 // If there's nothing virtual here, skip it.
15692 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15693 continue;
15694
15695 // If we're not actually going to call a move assignment for this base,
15696 // or the selected move assignment is trivial, skip it.
15697 Sema::SpecialMemberOverloadResult SMOR =
15698 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15699 /*ConstArg*/ false, /*VolatileArg*/ false,
15700 /*RValueThis*/ true, /*ConstThis*/ false,
15701 /*VolatileThis*/ false);
15702 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15703 !SMOR.getMethod()->isMoveAssignmentOperator())
15704 continue;
15705
15706 if (BaseSpec->isVirtual()) {
15707 // We're going to move-assign this virtual base, and its move
15708 // assignment operator is not trivial. If this can happen for
15709 // multiple distinct direct bases of Class, diagnose it. (If it
15710 // only happens in one base, we'll diagnose it when synthesizing
15711 // that base class's move assignment operator.)
15712 CXXBaseSpecifier *&Existing =
15713 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15714 .first->second;
15715 if (Existing && Existing != &BI) {
15716 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15717 << Class << Base;
15718 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15719 << (Base->getCanonicalDecl() ==
15720 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15721 << Base << Existing->getType() << Existing->getSourceRange();
15722 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15723 << (Base->getCanonicalDecl() ==
15724 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15725 << Base << BI.getType() << BaseSpec->getSourceRange();
15726
15727 // Only diagnose each vbase once.
15728 Existing = nullptr;
15729 }
15730 } else {
15731 // Only walk over bases that have defaulted move assignment operators.
15732 // We assume that any user-provided move assignment operator handles
15733 // the multiple-moves-of-vbase case itself somehow.
15734 if (!SMOR.getMethod()->isDefaulted())
15735 continue;
15736
15737 // We're going to move the base classes of Base. Add them to the list.
15738 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15739 }
15740 }
15741 }
15742}
15743
15744void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15745 CXXMethodDecl *MoveAssignOperator) {
15746 assert((MoveAssignOperator->isDefaulted() &&
15747 MoveAssignOperator->isOverloadedOperator() &&
15748 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15749 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15750 !MoveAssignOperator->isDeleted()) &&
15751 "DefineImplicitMoveAssignment called for wrong function");
15752 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15753 return;
15754
15755 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15756 if (ClassDecl->isInvalidDecl()) {
15757 MoveAssignOperator->setInvalidDecl();
15758 return;
15759 }
15760
15761 // C++0x [class.copy]p28:
15762 // The implicitly-defined or move assignment operator for a non-union class
15763 // X performs memberwise move assignment of its subobjects. The direct base
15764 // classes of X are assigned first, in the order of their declaration in the
15765 // base-specifier-list, and then the immediate non-static data members of X
15766 // are assigned, in the order in which they were declared in the class
15767 // definition.
15768
15769 // Issue a warning if our implicit move assignment operator will move
15770 // from a virtual base more than once.
15771 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15772
15773 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15774
15775 // The exception specification is needed because we are defining the
15776 // function.
15777 ResolveExceptionSpec(Loc: CurrentLocation,
15778 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15779
15780 // Add a context note for diagnostics produced after this point.
15781 Scope.addContextNote(UseLoc: CurrentLocation);
15782
15783 // The statements that form the synthesized function body.
15784 SmallVector<Stmt*, 8> Statements;
15785
15786 // The parameter for the "other" object, which we are move from.
15787 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15788 QualType OtherRefType =
15789 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15790
15791 // Our location for everything implicitly-generated.
15792 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15793 ? MoveAssignOperator->getEndLoc()
15794 : MoveAssignOperator->getLocation();
15795
15796 // Builds a reference to the "other" object.
15797 RefBuilder OtherRef(Other, OtherRefType);
15798 // Cast to rvalue.
15799 MoveCastBuilder MoveOther(OtherRef);
15800
15801 // Builds the function object parameter.
15802 std::optional<ThisBuilder> This;
15803 std::optional<DerefBuilder> DerefThis;
15804 std::optional<RefBuilder> ExplicitObject;
15805 QualType ObjectType;
15806 bool IsArrow = false;
15807 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15808 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15809 if (ObjectType->isReferenceType())
15810 ObjectType = ObjectType->getPointeeType();
15811 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15812 } else {
15813 ObjectType = getCurrentThisType();
15814 This.emplace();
15815 DerefThis.emplace(args&: *This);
15816 IsArrow = !getLangOpts().HLSL;
15817 }
15818 ExprBuilder &ObjectParameter =
15819 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15820
15821 // Assign base classes.
15822 bool Invalid = false;
15823 for (auto &Base : ClassDecl->bases()) {
15824 // C++11 [class.copy]p28:
15825 // It is unspecified whether subobjects representing virtual base classes
15826 // are assigned more than once by the implicitly-defined copy assignment
15827 // operator.
15828 // FIXME: Do not assign to a vbase that will be assigned by some other base
15829 // class. For a move-assignment, this can result in the vbase being moved
15830 // multiple times.
15831
15832 // Form the assignment:
15833 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15834 QualType BaseType = Base.getType().getUnqualifiedType();
15835 if (!BaseType->isRecordType()) {
15836 Invalid = true;
15837 continue;
15838 }
15839
15840 CXXCastPath BasePath;
15841 BasePath.push_back(Elt: &Base);
15842
15843 // Construct the "from" expression, which is an implicit cast to the
15844 // appropriately-qualified base type.
15845 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15846
15847 // Implicitly cast "this" to the appropriately-qualified base type.
15848 // Dereference "this".
15849 CastBuilder To(
15850 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15851 : static_cast<ExprBuilder &>(*DerefThis),
15852 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15853 VK_LValue, BasePath);
15854
15855 // Build the move.
15856 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15857 To, From,
15858 /*CopyingBaseSubobject=*/true,
15859 /*Copying=*/false);
15860 if (Move.isInvalid()) {
15861 MoveAssignOperator->setInvalidDecl();
15862 return;
15863 }
15864
15865 // Success! Record the move.
15866 Statements.push_back(Elt: Move.getAs<Expr>());
15867 }
15868
15869 // Assign non-static members.
15870 for (auto *Field : ClassDecl->fields()) {
15871 // FIXME: We should form some kind of AST representation for the implied
15872 // memcpy in a union copy operation.
15873 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15874 continue;
15875
15876 if (Field->isInvalidDecl()) {
15877 Invalid = true;
15878 continue;
15879 }
15880
15881 // Check for members of reference type; we can't move those.
15882 if (Field->getType()->isReferenceType()) {
15883 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15884 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15885 << Field->getDeclName();
15886 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15887 Invalid = true;
15888 continue;
15889 }
15890
15891 // Check for members of const-qualified, non-class type.
15892 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15893 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15894 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15895 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15896 << Field->getDeclName();
15897 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15898 Invalid = true;
15899 continue;
15900 }
15901
15902 // Suppress assigning zero-width bitfields.
15903 if (Field->isZeroLengthBitField())
15904 continue;
15905
15906 QualType FieldType = Field->getType().getNonReferenceType();
15907 if (FieldType->isIncompleteArrayType()) {
15908 assert(ClassDecl->hasFlexibleArrayMember() &&
15909 "Incomplete array type is not valid");
15910 continue;
15911 }
15912
15913 // Build references to the field in the object we're copying from and to.
15914 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15915 LookupMemberName);
15916 MemberLookup.addDecl(D: Field);
15917 MemberLookup.resolveKind();
15918 MemberBuilder From(MoveOther, OtherRefType,
15919 /*IsArrow=*/false, MemberLookup);
15920 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15921
15922 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15923 "Member reference with rvalue base must be rvalue except for reference "
15924 "members, which aren't allowed for move assignment.");
15925
15926 // Build the move of this field.
15927 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15928 To, From,
15929 /*CopyingBaseSubobject=*/false,
15930 /*Copying=*/false);
15931 if (Move.isInvalid()) {
15932 MoveAssignOperator->setInvalidDecl();
15933 return;
15934 }
15935
15936 // Success! Record the copy.
15937 Statements.push_back(Elt: Move.getAs<Stmt>());
15938 }
15939
15940 if (!Invalid) {
15941 // Add a "return *this;"
15942 Expr *ThisExpr =
15943 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15944 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15945 : static_cast<ExprBuilder &>(*DerefThis))
15946 .build(S&: *this, Loc);
15947
15948 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15949 if (Return.isInvalid())
15950 Invalid = true;
15951 else
15952 Statements.push_back(Elt: Return.getAs<Stmt>());
15953 }
15954
15955 if (Invalid) {
15956 MoveAssignOperator->setInvalidDecl();
15957 return;
15958 }
15959
15960 StmtResult Body;
15961 {
15962 CompoundScopeRAII CompoundScope(*this);
15963 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15964 /*isStmtExpr=*/false);
15965 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15966 }
15967 MoveAssignOperator->setBody(Body.getAs<Stmt>());
15968 MoveAssignOperator->markUsed(C&: Context);
15969
15970 if (ASTMutationListener *L = getASTMutationListener()) {
15971 L->CompletedImplicitDefinition(D: MoveAssignOperator);
15972 }
15973}
15974
15975CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
15976 CXXRecordDecl *ClassDecl) {
15977 // C++ [class.copy]p4:
15978 // If the class definition does not explicitly declare a copy
15979 // constructor, one is declared implicitly.
15980 assert(ClassDecl->needsImplicitCopyConstructor());
15981
15982 DeclaringSpecialMember DSM(*this, ClassDecl,
15983 CXXSpecialMemberKind::CopyConstructor);
15984 if (DSM.isAlreadyBeingDeclared())
15985 return nullptr;
15986
15987 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15988 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15989 /*OwnsTag=*/false);
15990 QualType ArgType = ClassType;
15991 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
15992 if (Const)
15993 ArgType = ArgType.withConst();
15994
15995 LangAS AS = getDefaultCXXMethodAddrSpace();
15996 if (AS != LangAS::Default)
15997 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15998
15999 ArgType = Context.getLValueReferenceType(T: ArgType);
16000
16001 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16002 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
16003
16004 DeclarationName Name
16005 = Context.DeclarationNames.getCXXConstructorName(
16006 Ty: Context.getCanonicalType(T: ClassType));
16007 SourceLocation ClassLoc = ClassDecl->getLocation();
16008 DeclarationNameInfo NameInfo(Name, ClassLoc);
16009
16010 // An implicitly-declared copy constructor is an inline public
16011 // member of its class.
16012 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
16013 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16014 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16015 /*isInline=*/true,
16016 /*isImplicitlyDeclared=*/true,
16017 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16018 : ConstexprSpecKind::Unspecified);
16019 CopyConstructor->setAccess(AS_public);
16020 CopyConstructor->setDefaulted();
16021
16022 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16023
16024 if (getLangOpts().CUDA)
16025 CUDA().inferTargetForImplicitSpecialMember(
16026 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
16027 /* ConstRHS */ Const,
16028 /* Diagnose */ false);
16029
16030 // During template instantiation of special member functions we need a
16031 // reliable TypeSourceInfo for the parameter types in order to allow functions
16032 // to be substituted.
16033 TypeSourceInfo *TSI = nullptr;
16034 if (inTemplateInstantiation() && ClassDecl->isLambda())
16035 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
16036
16037 // Add the parameter to the constructor.
16038 ParmVarDecl *FromParam =
16039 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
16040 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
16041 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
16042 CopyConstructor->setParams(FromParam);
16043
16044 CopyConstructor->setTrivial(
16045 ClassDecl->needsOverloadResolutionForCopyConstructor()
16046 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16047 CSM: CXXSpecialMemberKind::CopyConstructor)
16048 : ClassDecl->hasTrivialCopyConstructor());
16049
16050 CopyConstructor->setTrivialForCall(
16051 ClassDecl->hasAttr<TrivialABIAttr>() ||
16052 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16053 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16054 CSM: CXXSpecialMemberKind::CopyConstructor,
16055 TAH: TrivialABIHandling::ConsiderTrivialABI)
16056 : ClassDecl->hasTrivialCopyConstructorForCall()));
16057
16058 // Note that we have declared this constructor.
16059 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16060
16061 Scope *S = getScopeForContext(Ctx: ClassDecl);
16062 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16063
16064 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16065 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16066 ClassDecl->setImplicitCopyConstructorIsDeleted();
16067 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16068 }
16069
16070 if (S)
16071 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16072 ClassDecl->addDecl(D: CopyConstructor);
16073
16074 return CopyConstructor;
16075}
16076
16077void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16078 CXXConstructorDecl *CopyConstructor) {
16079 assert((CopyConstructor->isDefaulted() &&
16080 CopyConstructor->isCopyConstructor() &&
16081 !CopyConstructor->doesThisDeclarationHaveABody() &&
16082 !CopyConstructor->isDeleted()) &&
16083 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16084 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16085 return;
16086
16087 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16088 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16089
16090 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16091
16092 // The exception specification is needed because we are defining the
16093 // function.
16094 ResolveExceptionSpec(Loc: CurrentLocation,
16095 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16096 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16097
16098 // Add a context note for diagnostics produced after this point.
16099 Scope.addContextNote(UseLoc: CurrentLocation);
16100
16101 // C++11 [class.copy]p7:
16102 // The [definition of an implicitly declared copy constructor] is
16103 // deprecated if the class has a user-declared copy assignment operator
16104 // or a user-declared destructor.
16105 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16106 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16107
16108 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16109 CopyConstructor->setInvalidDecl();
16110 } else {
16111 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16112 ? CopyConstructor->getEndLoc()
16113 : CopyConstructor->getLocation();
16114 Sema::CompoundScopeRAII CompoundScope(*this);
16115 CopyConstructor->setBody(
16116 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16117 CopyConstructor->markUsed(C&: Context);
16118 }
16119
16120 if (ASTMutationListener *L = getASTMutationListener()) {
16121 L->CompletedImplicitDefinition(D: CopyConstructor);
16122 }
16123}
16124
16125CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16126 CXXRecordDecl *ClassDecl) {
16127 assert(ClassDecl->needsImplicitMoveConstructor());
16128
16129 DeclaringSpecialMember DSM(*this, ClassDecl,
16130 CXXSpecialMemberKind::MoveConstructor);
16131 if (DSM.isAlreadyBeingDeclared())
16132 return nullptr;
16133
16134 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16135 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16136 /*OwnsTag=*/false);
16137
16138 QualType ArgType = ClassType;
16139 LangAS AS = getDefaultCXXMethodAddrSpace();
16140 if (AS != LangAS::Default)
16141 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16142 ArgType = Context.getRValueReferenceType(T: ArgType);
16143
16144 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16145 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16146
16147 DeclarationName Name
16148 = Context.DeclarationNames.getCXXConstructorName(
16149 Ty: Context.getCanonicalType(T: ClassType));
16150 SourceLocation ClassLoc = ClassDecl->getLocation();
16151 DeclarationNameInfo NameInfo(Name, ClassLoc);
16152
16153 // C++11 [class.copy]p11:
16154 // An implicitly-declared copy/move constructor is an inline public
16155 // member of its class.
16156 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16157 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16158 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16159 /*isInline=*/true,
16160 /*isImplicitlyDeclared=*/true,
16161 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16162 : ConstexprSpecKind::Unspecified);
16163 MoveConstructor->setAccess(AS_public);
16164 MoveConstructor->setDefaulted();
16165
16166 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16167
16168 if (getLangOpts().CUDA)
16169 CUDA().inferTargetForImplicitSpecialMember(
16170 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16171 /* ConstRHS */ false,
16172 /* Diagnose */ false);
16173
16174 // Add the parameter to the constructor.
16175 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16176 StartLoc: ClassLoc, IdLoc: ClassLoc,
16177 /*IdentifierInfo=*/Id: nullptr,
16178 T: ArgType, /*TInfo=*/nullptr,
16179 S: SC_None, DefArg: nullptr);
16180 MoveConstructor->setParams(FromParam);
16181
16182 MoveConstructor->setTrivial(
16183 ClassDecl->needsOverloadResolutionForMoveConstructor()
16184 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16185 CSM: CXXSpecialMemberKind::MoveConstructor)
16186 : ClassDecl->hasTrivialMoveConstructor());
16187
16188 MoveConstructor->setTrivialForCall(
16189 ClassDecl->hasAttr<TrivialABIAttr>() ||
16190 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16191 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16192 CSM: CXXSpecialMemberKind::MoveConstructor,
16193 TAH: TrivialABIHandling::ConsiderTrivialABI)
16194 : ClassDecl->hasTrivialMoveConstructorForCall()));
16195
16196 // Note that we have declared this constructor.
16197 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16198
16199 Scope *S = getScopeForContext(Ctx: ClassDecl);
16200 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16201
16202 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16203 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16204 ClassDecl->setImplicitMoveConstructorIsDeleted();
16205 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16206 }
16207
16208 if (S)
16209 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16210 ClassDecl->addDecl(D: MoveConstructor);
16211
16212 return MoveConstructor;
16213}
16214
16215void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16216 CXXConstructorDecl *MoveConstructor) {
16217 assert((MoveConstructor->isDefaulted() &&
16218 MoveConstructor->isMoveConstructor() &&
16219 !MoveConstructor->doesThisDeclarationHaveABody() &&
16220 !MoveConstructor->isDeleted()) &&
16221 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16222 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16223 return;
16224
16225 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16226 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16227
16228 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16229
16230 // The exception specification is needed because we are defining the
16231 // function.
16232 ResolveExceptionSpec(Loc: CurrentLocation,
16233 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16234 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16235
16236 // Add a context note for diagnostics produced after this point.
16237 Scope.addContextNote(UseLoc: CurrentLocation);
16238
16239 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16240 MoveConstructor->setInvalidDecl();
16241 } else {
16242 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16243 ? MoveConstructor->getEndLoc()
16244 : MoveConstructor->getLocation();
16245 Sema::CompoundScopeRAII CompoundScope(*this);
16246 MoveConstructor->setBody(
16247 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16248 MoveConstructor->markUsed(C&: Context);
16249 }
16250
16251 if (ASTMutationListener *L = getASTMutationListener()) {
16252 L->CompletedImplicitDefinition(D: MoveConstructor);
16253 }
16254}
16255
16256bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16257 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16258}
16259
16260void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16261 SourceLocation CurrentLocation,
16262 CXXConversionDecl *Conv) {
16263 SynthesizedFunctionScope Scope(*this, Conv);
16264 assert(!Conv->getReturnType()->isUndeducedType());
16265
16266 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16267 CallingConv CC =
16268 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16269
16270 CXXRecordDecl *Lambda = Conv->getParent();
16271 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16272 FunctionDecl *Invoker =
16273 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16274 ? CallOp
16275 : Lambda->getLambdaStaticInvoker(CC);
16276
16277 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16278 CallOp = InstantiateFunctionDeclaration(
16279 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16280 if (!CallOp)
16281 return;
16282
16283 if (CallOp != Invoker) {
16284 Invoker = InstantiateFunctionDeclaration(
16285 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16286 Loc: CurrentLocation);
16287 if (!Invoker)
16288 return;
16289 }
16290 }
16291
16292 if (CallOp->isInvalidDecl())
16293 return;
16294
16295 // Mark the call operator referenced (and add to pending instantiations
16296 // if necessary).
16297 // For both the conversion and static-invoker template specializations
16298 // we construct their body's in this function, so no need to add them
16299 // to the PendingInstantiations.
16300 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16301
16302 if (Invoker != CallOp) {
16303 // Fill in the __invoke function with a dummy implementation. IR generation
16304 // will fill in the actual details. Update its type in case it contained
16305 // an 'auto'.
16306 Invoker->markUsed(C&: Context);
16307 Invoker->setReferenced();
16308 Invoker->setType(Conv->getReturnType()->getPointeeType());
16309 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16310 }
16311
16312 // Construct the body of the conversion function { return __invoke; }.
16313 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16314 Loc: Conv->getLocation());
16315 assert(FunctionRef && "Can't refer to __invoke function?");
16316 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16317 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16318 LB: Conv->getLocation(), RB: Conv->getLocation()));
16319 Conv->markUsed(C&: Context);
16320 Conv->setReferenced();
16321
16322 if (ASTMutationListener *L = getASTMutationListener()) {
16323 L->CompletedImplicitDefinition(D: Conv);
16324 if (Invoker != CallOp)
16325 L->CompletedImplicitDefinition(D: Invoker);
16326 }
16327}
16328
16329void Sema::DefineImplicitLambdaToBlockPointerConversion(
16330 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16331 assert(!Conv->getParent()->isGenericLambda());
16332
16333 SynthesizedFunctionScope Scope(*this, Conv);
16334
16335 // Copy-initialize the lambda object as needed to capture it.
16336 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16337 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16338
16339 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16340 ConvLocation: Conv->getLocation(),
16341 Conv, Src: DerefThis);
16342
16343 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16344 // behavior. Note that only the general conversion function does this
16345 // (since it's unusable otherwise); in the case where we inline the
16346 // block literal, it has block literal lifetime semantics.
16347 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16348 BuildBlock = ImplicitCastExpr::Create(
16349 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16350 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16351
16352 if (BuildBlock.isInvalid()) {
16353 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16354 Conv->setInvalidDecl();
16355 return;
16356 }
16357
16358 // Create the return statement that returns the block from the conversion
16359 // function.
16360 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16361 if (Return.isInvalid()) {
16362 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16363 Conv->setInvalidDecl();
16364 return;
16365 }
16366
16367 // Set the body of the conversion function.
16368 Stmt *ReturnS = Return.get();
16369 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16370 LB: Conv->getLocation(), RB: Conv->getLocation()));
16371 Conv->markUsed(C&: Context);
16372
16373 // We're done; notify the mutation listener, if any.
16374 if (ASTMutationListener *L = getASTMutationListener()) {
16375 L->CompletedImplicitDefinition(D: Conv);
16376 }
16377}
16378
16379/// Determine whether the given list arguments contains exactly one
16380/// "real" (non-default) argument.
16381static bool hasOneRealArgument(MultiExprArg Args) {
16382 switch (Args.size()) {
16383 case 0:
16384 return false;
16385
16386 default:
16387 if (!Args[1]->isDefaultArgument())
16388 return false;
16389
16390 [[fallthrough]];
16391 case 1:
16392 return !Args[0]->isDefaultArgument();
16393 }
16394
16395 return false;
16396}
16397
16398ExprResult Sema::BuildCXXConstructExpr(
16399 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16400 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16401 bool HadMultipleCandidates, bool IsListInitialization,
16402 bool IsStdInitListInitialization, bool RequiresZeroInit,
16403 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16404 bool Elidable = false;
16405
16406 // C++0x [class.copy]p34:
16407 // When certain criteria are met, an implementation is allowed to
16408 // omit the copy/move construction of a class object, even if the
16409 // copy/move constructor and/or destructor for the object have
16410 // side effects. [...]
16411 // - when a temporary class object that has not been bound to a
16412 // reference (12.2) would be copied/moved to a class object
16413 // with the same cv-unqualified type, the copy/move operation
16414 // can be omitted by constructing the temporary object
16415 // directly into the target of the omitted copy/move
16416 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16417 // FIXME: Converting constructors should also be accepted.
16418 // But to fix this, the logic that digs down into a CXXConstructExpr
16419 // to find the source object needs to handle it.
16420 // Right now it assumes the source object is passed directly as the
16421 // first argument.
16422 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16423 Expr *SubExpr = ExprArgs[0];
16424 // FIXME: Per above, this is also incorrect if we want to accept
16425 // converting constructors, as isTemporaryObject will
16426 // reject temporaries with different type from the
16427 // CXXRecord itself.
16428 Elidable = SubExpr->isTemporaryObject(
16429 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16430 }
16431
16432 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16433 FoundDecl, Constructor,
16434 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16435 IsListInitialization,
16436 IsStdInitListInitialization, RequiresZeroInit,
16437 ConstructKind, ParenRange);
16438}
16439
16440ExprResult Sema::BuildCXXConstructExpr(
16441 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16442 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16443 bool HadMultipleCandidates, bool IsListInitialization,
16444 bool IsStdInitListInitialization, bool RequiresZeroInit,
16445 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16446 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16447 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16448 // The only way to get here is if we did overload resolution to find the
16449 // shadow decl, so we don't need to worry about re-checking the trailing
16450 // requires clause.
16451 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16452 return ExprError();
16453 }
16454
16455 return BuildCXXConstructExpr(
16456 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16457 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16458 RequiresZeroInit, ConstructKind, ParenRange);
16459}
16460
16461/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16462/// including handling of its default argument expressions.
16463ExprResult Sema::BuildCXXConstructExpr(
16464 SourceLocation ConstructLoc, QualType DeclInitType,
16465 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16466 bool HadMultipleCandidates, bool IsListInitialization,
16467 bool IsStdInitListInitialization, bool RequiresZeroInit,
16468 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16469 assert(declaresSameEntity(
16470 Constructor->getParent(),
16471 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16472 "given constructor for wrong type");
16473 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16474 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16475 return ExprError();
16476
16477 return CheckForImmediateInvocation(
16478 E: CXXConstructExpr::Create(
16479 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16480 HadMultipleCandidates, ListInitialization: IsListInitialization,
16481 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16482 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16483 Decl: Constructor);
16484}
16485
16486void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16487 if (VD->isInvalidDecl()) return;
16488 // If initializing the variable failed, don't also diagnose problems with
16489 // the destructor, they're likely related.
16490 if (VD->getInit() && VD->getInit()->containsErrors())
16491 return;
16492
16493 ClassDecl = ClassDecl->getDefinitionOrSelf();
16494 if (ClassDecl->isInvalidDecl()) return;
16495 if (ClassDecl->hasIrrelevantDestructor()) return;
16496 if (ClassDecl->isDependentContext()) return;
16497
16498 if (VD->isNoDestroy(getASTContext()))
16499 return;
16500
16501 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16502 // The result of `LookupDestructor` might be nullptr if the destructor is
16503 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16504 // will not be selected by `CXXRecordDecl::getDestructor()`.
16505 if (!Destructor)
16506 return;
16507 // If this is an array, we'll require the destructor during initialization, so
16508 // we can skip over this. We still want to emit exit-time destructor warnings
16509 // though.
16510 if (!VD->getType()->isArrayType()) {
16511 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16512 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16513 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16514 << VD->getDeclName() << VD->getType());
16515 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16516 }
16517
16518 if (Destructor->isTrivial()) return;
16519
16520 // If the destructor is constexpr, check whether the variable has constant
16521 // destruction now.
16522 if (Destructor->isConstexpr()) {
16523 bool HasConstantInit = false;
16524 if (VD->getInit() && !VD->getInit()->isValueDependent())
16525 HasConstantInit = VD->evaluateValue();
16526 SmallVector<PartialDiagnosticAt, 8> Notes;
16527 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16528 HasConstantInit) {
16529 Diag(Loc: VD->getLocation(),
16530 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16531 for (const PartialDiagnosticAt &Note : Notes)
16532 Diag(Loc: Note.first, PD: Note.second);
16533 }
16534 }
16535
16536 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16537 return;
16538
16539 // Emit warning for non-trivial dtor in global scope (a real global,
16540 // class-static, function-static).
16541 if (!VD->hasAttr<AlwaysDestroyAttr>())
16542 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16543
16544 // TODO: this should be re-enabled for static locals by !CXAAtExit
16545 if (!VD->isStaticLocal())
16546 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16547}
16548
16549bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16550 QualType DeclInitType, MultiExprArg ArgsPtr,
16551 SourceLocation Loc,
16552 SmallVectorImpl<Expr *> &ConvertedArgs,
16553 bool AllowExplicit,
16554 bool IsListInitialization) {
16555 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16556 unsigned NumArgs = ArgsPtr.size();
16557 Expr **Args = ArgsPtr.data();
16558
16559 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16560 unsigned NumParams = Proto->getNumParams();
16561
16562 // If too few arguments are available, we'll fill in the rest with defaults.
16563 if (NumArgs < NumParams)
16564 ConvertedArgs.reserve(N: NumParams);
16565 else
16566 ConvertedArgs.reserve(N: NumArgs);
16567
16568 VariadicCallType CallType = Proto->isVariadic()
16569 ? VariadicCallType::Constructor
16570 : VariadicCallType::DoesNotApply;
16571 SmallVector<Expr *, 8> AllArgs;
16572 bool Invalid = GatherArgumentsForCall(
16573 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16574 CallType, AllowExplicit, IsListInitialization);
16575 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16576
16577 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16578
16579 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16580 Proto, Loc);
16581
16582 return Invalid;
16583}
16584
16585TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16586 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16587 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16588}
16589
16590FunctionDecl *
16591Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16592 QualType DeallocType, SourceLocation Loc) {
16593 if (DeallocType.isNull())
16594 return nullptr;
16595
16596 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16597 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16598 return nullptr;
16599
16600 if (FnDecl->isVariadic())
16601 return nullptr;
16602
16603 unsigned NumParams = FnDecl->getNumParams();
16604 constexpr unsigned RequiredParameterCount =
16605 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16606 // A usual deallocation function has no placement parameters
16607 if (NumParams != RequiredParameterCount)
16608 return nullptr;
16609
16610 // A type aware allocation is only usual if the only dependent parameter is
16611 // the first parameter.
16612 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16613 P: [](const ParmVarDecl *ParamDecl) {
16614 return ParamDecl->getType()->isDependentType();
16615 }))
16616 return nullptr;
16617
16618 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16619 if (SpecializedTypeIdentity.isNull())
16620 return nullptr;
16621
16622 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16623 ArgTypes.reserve(N: NumParams);
16624
16625 // The first parameter to a type aware operator delete is by definition the
16626 // type-identity argument, so we explicitly set this to the target
16627 // type-identity type, the remaining usual parameters should then simply match
16628 // the type declared in the function template.
16629 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16630 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16631 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16632
16633 FunctionProtoType::ExtProtoInfo EPI;
16634 QualType ExpectedFunctionType =
16635 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16636 sema::TemplateDeductionInfo Info(Loc);
16637 FunctionDecl *Result;
16638 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16639 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16640 return nullptr;
16641 return Result;
16642}
16643
16644static inline bool
16645CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16646 const FunctionDecl *FnDecl) {
16647 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16648 if (isa<NamespaceDecl>(Val: DC)) {
16649 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16650 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16651 << FnDecl->getDeclName();
16652 }
16653
16654 if (isa<TranslationUnitDecl>(Val: DC) &&
16655 FnDecl->getStorageClass() == SC_Static) {
16656 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16657 DiagID: diag::err_operator_new_delete_declared_static)
16658 << FnDecl->getDeclName();
16659 }
16660
16661 return false;
16662}
16663
16664static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16665 const PointerType *PtrTy) {
16666 auto &Ctx = SemaRef.Context;
16667 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16668 PtrQuals.removeAddressSpace();
16669 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16670 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16671}
16672
16673enum class AllocationOperatorKind { New, Delete };
16674
16675static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16676 const FunctionDecl *FD,
16677 bool *WasMalformed) {
16678 const Decl *MalformedDecl = nullptr;
16679 if (FD->getNumParams() > 0 &&
16680 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16681 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16682 return true;
16683
16684 if (!MalformedDecl)
16685 return false;
16686
16687 if (WasMalformed)
16688 *WasMalformed = true;
16689
16690 return true;
16691}
16692
16693static bool isDestroyingDeleteT(QualType Type) {
16694 auto *RD = Type->getAsCXXRecordDecl();
16695 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16696 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16697}
16698
16699static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16700 const FunctionDecl *FD) {
16701 // C++ P0722:
16702 // Within a class C, a single object deallocation function with signature
16703 // (T, std::destroying_delete_t, <more params>)
16704 // is a destroying operator delete.
16705 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16706 SemaRef, FD, /*WasMalformed=*/nullptr);
16707 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16708 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16709 FD->getNumParams() > DestroyingDeleteIdx &&
16710 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16711}
16712
16713static inline bool CheckOperatorNewDeleteTypes(
16714 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16715 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16716 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16717 auto NormalizeType = [&SemaRef](QualType T) {
16718 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16719 // The operator is valid on any address space for OpenCL.
16720 // Drop address space from actual and expected result types.
16721 if (const auto PtrTy = T->template getAs<PointerType>())
16722 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16723 }
16724 return SemaRef.Context.getCanonicalType(T);
16725 };
16726
16727 const unsigned NumParams = FnDecl->getNumParams();
16728 unsigned FirstNonTypeParam = 0;
16729 bool MalformedTypeIdentity = false;
16730 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16731 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16732 unsigned MinimumMandatoryArgumentCount = 1;
16733 unsigned SizeParameterIndex = 0;
16734 if (IsPotentiallyTypeAware) {
16735 // We don't emit this diagnosis for template instantiations as we will
16736 // have already emitted it for the original template declaration.
16737 if (!FnDecl->isTemplateInstantiation())
16738 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16739
16740 if (OperatorKind == AllocationOperatorKind::New) {
16741 SizeParameterIndex = 1;
16742 MinimumMandatoryArgumentCount =
16743 FunctionDecl::RequiredTypeAwareNewParameterCount;
16744 } else {
16745 SizeParameterIndex = 2;
16746 MinimumMandatoryArgumentCount =
16747 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16748 }
16749 FirstNonTypeParam = 1;
16750 }
16751
16752 bool IsPotentiallyDestroyingDelete =
16753 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16754
16755 if (IsPotentiallyDestroyingDelete) {
16756 ++MinimumMandatoryArgumentCount;
16757 ++SizeParameterIndex;
16758 }
16759
16760 if (NumParams < MinimumMandatoryArgumentCount)
16761 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16762 DiagID: diag::err_operator_new_delete_too_few_parameters)
16763 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16764 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16765
16766 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16767 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16768 if (ParamDecl->hasDefaultArg())
16769 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16770 DiagID: diag::err_operator_new_default_arg)
16771 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16772 }
16773
16774 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16775 QualType CanResultType = NormalizeType(FnType->getReturnType());
16776 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16777 QualType CanExpectedSizeOrAddressParamType =
16778 NormalizeType(ExpectedSizeOrAddressParamType);
16779
16780 // Check that the result type is what we expect.
16781 if (CanResultType != CanExpectedResultType) {
16782 // Reject even if the type is dependent; an operator delete function is
16783 // required to have a non-dependent result type.
16784 return SemaRef.Diag(
16785 Loc: FnDecl->getLocation(),
16786 DiagID: CanResultType->isDependentType()
16787 ? diag::err_operator_new_delete_dependent_result_type
16788 : diag::err_operator_new_delete_invalid_result_type)
16789 << FnDecl->getDeclName() << ExpectedResultType;
16790 }
16791
16792 // A function template must have at least 2 parameters.
16793 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16794 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16795 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16796 << FnDecl->getDeclName();
16797
16798 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16799 auto FallbackType) -> bool {
16800 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16801 if (ExpectedType.isNull()) {
16802 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16803 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16804 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16805 << ParamDecl->getSourceRange();
16806 }
16807 CanQualType CanExpectedTy =
16808 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16809 auto ActualParamType =
16810 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16811 if (ActualParamType == CanExpectedTy)
16812 return false;
16813 unsigned Diagnostic = ActualParamType->isDependentType()
16814 ? DependentParamTypeDiag
16815 : InvalidParamTypeDiag;
16816 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16817 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16818 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16819 << FallbackType << ParamDecl->getSourceRange();
16820 };
16821
16822 // Check that the first parameter type is what we expect.
16823 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16824 return true;
16825
16826 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16827
16828 // If the first parameter type is not a type-identity we're done, otherwise
16829 // we need to ensure the size and alignment parameters have the correct type
16830 if (!IsPotentiallyTypeAware)
16831 return false;
16832
16833 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16834 return true;
16835 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16836 CanQualType StdAlignValT =
16837 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16838 : CanQualType();
16839 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16840 return true;
16841
16842 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16843 return MalformedTypeIdentity;
16844}
16845
16846static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16847 // C++ [basic.stc.dynamic.allocation]p1:
16848 // A program is ill-formed if an allocation function is declared in a
16849 // namespace scope other than global scope or declared static in global
16850 // scope.
16851 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16852 return true;
16853
16854 CanQualType SizeTy =
16855 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16856
16857 // C++ [basic.stc.dynamic.allocation]p1:
16858 // The return type shall be void*. The first parameter shall have type
16859 // std::size_t.
16860 return CheckOperatorNewDeleteTypes(
16861 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16862 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16863 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16864}
16865
16866static bool
16867CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16868 // C++ [basic.stc.dynamic.deallocation]p1:
16869 // A program is ill-formed if deallocation functions are declared in a
16870 // namespace scope other than global scope or declared static in global
16871 // scope.
16872 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16873 return true;
16874
16875 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16876 auto ConstructDestroyingDeleteAddressType = [&]() {
16877 assert(MD);
16878 return SemaRef.Context.getPointerType(
16879 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16880 };
16881
16882 // C++ P2719: A destroying operator delete cannot be type aware
16883 // so for QoL we actually check for this explicitly by considering
16884 // an destroying-delete appropriate address type and the presence of
16885 // any parameter of type destroying_delete_t as an erroneous attempt
16886 // to declare a type aware destroying delete, rather than emitting a
16887 // pile of incorrect parameter type errors.
16888 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16889 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16890 QualType AddressParamType =
16891 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16892 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16893 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16894 // The address parameter type implies an author trying to construct a
16895 // type aware destroying delete, so we'll see if we can find a parameter
16896 // of type `std::destroying_delete_t`, and if we find it we'll report
16897 // this as being an attempt at a type aware destroying delete just stop
16898 // here. If we don't do this, the resulting incorrect parameter ordering
16899 // results in a pile mismatched argument type errors that don't explain
16900 // the core problem.
16901 for (auto Param : MD->parameters()) {
16902 if (isDestroyingDeleteT(Type: Param->getType())) {
16903 SemaRef.Diag(Loc: MD->getLocation(),
16904 DiagID: diag::err_type_aware_destroying_operator_delete)
16905 << Param->getSourceRange();
16906 return true;
16907 }
16908 }
16909 }
16910 }
16911
16912 // C++ P0722:
16913 // Within a class C, the first parameter of a destroying operator delete
16914 // shall be of type C *. The first parameter of any other deallocation
16915 // function shall be of type void *.
16916 CanQualType ExpectedAddressParamType =
16917 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16918 ? SemaRef.Context.getPointerType(
16919 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16920 : SemaRef.Context.VoidPtrTy;
16921
16922 // C++ [basic.stc.dynamic.deallocation]p2:
16923 // Each deallocation function shall return void
16924 if (CheckOperatorNewDeleteTypes(
16925 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
16926 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
16927 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
16928 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
16929 return true;
16930
16931 // C++ P0722:
16932 // A destroying operator delete shall be a usual deallocation function.
16933 if (MD && !MD->getParent()->isDependentContext() &&
16934 MD->isDestroyingOperatorDelete()) {
16935 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
16936 SemaRef.Diag(Loc: MD->getLocation(),
16937 DiagID: diag::err_destroying_operator_delete_not_usual);
16938 return true;
16939 }
16940 }
16941
16942 return false;
16943}
16944
16945bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
16946 assert(FnDecl && FnDecl->isOverloadedOperator() &&
16947 "Expected an overloaded operator declaration");
16948
16949 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
16950
16951 // C++ [over.oper]p5:
16952 // The allocation and deallocation functions, operator new,
16953 // operator new[], operator delete and operator delete[], are
16954 // described completely in 3.7.3. The attributes and restrictions
16955 // found in the rest of this subclause do not apply to them unless
16956 // explicitly stated in 3.7.3.
16957 if (Op == OO_Delete || Op == OO_Array_Delete)
16958 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
16959
16960 if (Op == OO_New || Op == OO_Array_New)
16961 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
16962
16963 // C++ [over.oper]p7:
16964 // An operator function shall either be a member function or
16965 // be a non-member function and have at least one parameter
16966 // whose type is a class, a reference to a class, an enumeration,
16967 // or a reference to an enumeration.
16968 // Note: Before C++23, a member function could not be static. The only member
16969 // function allowed to be static is the call operator function.
16970 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
16971 if (MethodDecl->isStatic()) {
16972 if (Op == OO_Call || Op == OO_Subscript)
16973 Diag(Loc: FnDecl->getLocation(),
16974 DiagID: (LangOpts.CPlusPlus23
16975 ? diag::warn_cxx20_compat_operator_overload_static
16976 : diag::ext_operator_overload_static))
16977 << FnDecl;
16978 else
16979 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
16980 << FnDecl;
16981 }
16982 } else {
16983 bool ClassOrEnumParam = false;
16984 for (auto *Param : FnDecl->parameters()) {
16985 QualType ParamType = Param->getType().getNonReferenceType();
16986 if (ParamType->isDependentType() || ParamType->isRecordType() ||
16987 ParamType->isEnumeralType()) {
16988 ClassOrEnumParam = true;
16989 break;
16990 }
16991 }
16992
16993 if (!ClassOrEnumParam)
16994 return Diag(Loc: FnDecl->getLocation(),
16995 DiagID: diag::err_operator_overload_needs_class_or_enum)
16996 << FnDecl->getDeclName();
16997 }
16998
16999 // C++ [over.oper]p8:
17000 // An operator function cannot have default arguments (8.3.6),
17001 // except where explicitly stated below.
17002 //
17003 // Only the function-call operator (C++ [over.call]p1) and the subscript
17004 // operator (CWG2507) allow default arguments.
17005 if (Op != OO_Call) {
17006 ParmVarDecl *FirstDefaultedParam = nullptr;
17007 for (auto *Param : FnDecl->parameters()) {
17008 if (Param->hasDefaultArg()) {
17009 FirstDefaultedParam = Param;
17010 break;
17011 }
17012 }
17013 if (FirstDefaultedParam) {
17014 if (Op == OO_Subscript) {
17015 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17016 ? diag::ext_subscript_overload
17017 : diag::error_subscript_overload)
17018 << FnDecl->getDeclName() << 1
17019 << FirstDefaultedParam->getDefaultArgRange();
17020 } else {
17021 return Diag(Loc: FirstDefaultedParam->getLocation(),
17022 DiagID: diag::err_operator_overload_default_arg)
17023 << FnDecl->getDeclName()
17024 << FirstDefaultedParam->getDefaultArgRange();
17025 }
17026 }
17027 }
17028
17029 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17030 { false, false, false }
17031#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17032 , { Unary, Binary, MemberOnly }
17033#include "clang/Basic/OperatorKinds.def"
17034 };
17035
17036 bool CanBeUnaryOperator = OperatorUses[Op][0];
17037 bool CanBeBinaryOperator = OperatorUses[Op][1];
17038 bool MustBeMemberOperator = OperatorUses[Op][2];
17039
17040 // C++ [over.oper]p8:
17041 // [...] Operator functions cannot have more or fewer parameters
17042 // than the number required for the corresponding operator, as
17043 // described in the rest of this subclause.
17044 unsigned NumParams = FnDecl->getNumParams() +
17045 (isa<CXXMethodDecl>(Val: FnDecl) &&
17046 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17047 ? 1
17048 : 0);
17049 if (Op != OO_Call && Op != OO_Subscript &&
17050 ((NumParams == 1 && !CanBeUnaryOperator) ||
17051 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17052 (NumParams > 2))) {
17053 // We have the wrong number of parameters.
17054 unsigned ErrorKind;
17055 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17056 ErrorKind = 2; // 2 -> unary or binary.
17057 } else if (CanBeUnaryOperator) {
17058 ErrorKind = 0; // 0 -> unary
17059 } else {
17060 assert(CanBeBinaryOperator &&
17061 "All non-call overloaded operators are unary or binary!");
17062 ErrorKind = 1; // 1 -> binary
17063 }
17064 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17065 << FnDecl->getDeclName() << NumParams << ErrorKind;
17066 }
17067
17068 if (Op == OO_Subscript && NumParams != 2) {
17069 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17070 ? diag::ext_subscript_overload
17071 : diag::error_subscript_overload)
17072 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17073 }
17074
17075 // Overloaded operators other than operator() and operator[] cannot be
17076 // variadic.
17077 if (Op != OO_Call &&
17078 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17079 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17080 << FnDecl->getDeclName();
17081 }
17082
17083 // Some operators must be member functions.
17084 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17085 return Diag(Loc: FnDecl->getLocation(),
17086 DiagID: diag::err_operator_overload_must_be_member)
17087 << FnDecl->getDeclName();
17088 }
17089
17090 // C++ [over.inc]p1:
17091 // The user-defined function called operator++ implements the
17092 // prefix and postfix ++ operator. If this function is a member
17093 // function with no parameters, or a non-member function with one
17094 // parameter of class or enumeration type, it defines the prefix
17095 // increment operator ++ for objects of that type. If the function
17096 // is a member function with one parameter (which shall be of type
17097 // int) or a non-member function with two parameters (the second
17098 // of which shall be of type int), it defines the postfix
17099 // increment operator ++ for objects of that type.
17100 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17101 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17102 QualType ParamType = LastParam->getType();
17103
17104 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17105 !ParamType->isDependentType())
17106 return Diag(Loc: LastParam->getLocation(),
17107 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17108 << LastParam->getType() << (Op == OO_MinusMinus);
17109 }
17110
17111 return false;
17112}
17113
17114static bool
17115checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17116 FunctionTemplateDecl *TpDecl) {
17117 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17118
17119 // Must have one or two template parameters.
17120 if (TemplateParams->size() == 1) {
17121 NonTypeTemplateParmDecl *PmDecl =
17122 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17123
17124 // The template parameter must be a char parameter pack.
17125 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17126 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17127 return false;
17128
17129 // C++20 [over.literal]p5:
17130 // A string literal operator template is a literal operator template
17131 // whose template-parameter-list comprises a single non-type
17132 // template-parameter of class type.
17133 //
17134 // As a DR resolution, we also allow placeholders for deduced class
17135 // template specializations.
17136 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17137 !PmDecl->isTemplateParameterPack() &&
17138 (PmDecl->getType()->isRecordType() ||
17139 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17140 return false;
17141 } else if (TemplateParams->size() == 2) {
17142 TemplateTypeParmDecl *PmType =
17143 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17144 NonTypeTemplateParmDecl *PmArgs =
17145 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17146
17147 // The second template parameter must be a parameter pack with the
17148 // first template parameter as its type.
17149 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17150 PmArgs->isTemplateParameterPack()) {
17151 if (const auto *TArgs =
17152 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17153 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17154 TArgs->getIndex() == PmType->getIndex()) {
17155 if (!SemaRef.inTemplateInstantiation())
17156 SemaRef.Diag(Loc: TpDecl->getLocation(),
17157 DiagID: diag::ext_string_literal_operator_template);
17158 return false;
17159 }
17160 }
17161 }
17162
17163 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17164 DiagID: diag::err_literal_operator_template)
17165 << TpDecl->getTemplateParameters()->getSourceRange();
17166 return true;
17167}
17168
17169bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17170 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17171 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17172 << FnDecl->getDeclName();
17173 return true;
17174 }
17175
17176 if (FnDecl->isExternC()) {
17177 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17178 if (const LinkageSpecDecl *LSD =
17179 FnDecl->getDeclContext()->getExternCContext())
17180 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17181 return true;
17182 }
17183
17184 // This might be the definition of a literal operator template.
17185 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17186
17187 // This might be a specialization of a literal operator template.
17188 if (!TpDecl)
17189 TpDecl = FnDecl->getPrimaryTemplate();
17190
17191 // template <char...> type operator "" name() and
17192 // template <class T, T...> type operator "" name() are the only valid
17193 // template signatures, and the only valid signatures with no parameters.
17194 //
17195 // C++20 also allows template <SomeClass T> type operator "" name().
17196 if (TpDecl) {
17197 if (FnDecl->param_size() != 0) {
17198 Diag(Loc: FnDecl->getLocation(),
17199 DiagID: diag::err_literal_operator_template_with_params);
17200 return true;
17201 }
17202
17203 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17204 return true;
17205
17206 } else if (FnDecl->param_size() == 1) {
17207 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17208
17209 QualType ParamType = Param->getType().getUnqualifiedType();
17210
17211 // Only unsigned long long int, long double, any character type, and const
17212 // char * are allowed as the only parameters.
17213 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17214 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17215 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17216 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17217 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17218 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17219 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17220 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17221 QualType InnerType = Ptr->getPointeeType();
17222
17223 // Pointer parameter must be a const char *.
17224 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17225 T2: Context.CharTy) &&
17226 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17227 Diag(Loc: Param->getSourceRange().getBegin(),
17228 DiagID: diag::err_literal_operator_param)
17229 << ParamType << "'const char *'" << Param->getSourceRange();
17230 return true;
17231 }
17232
17233 } else if (ParamType->isRealFloatingType()) {
17234 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17235 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17236 return true;
17237
17238 } else if (ParamType->isIntegerType()) {
17239 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17240 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17241 return true;
17242
17243 } else {
17244 Diag(Loc: Param->getSourceRange().getBegin(),
17245 DiagID: diag::err_literal_operator_invalid_param)
17246 << ParamType << Param->getSourceRange();
17247 return true;
17248 }
17249
17250 } else if (FnDecl->param_size() == 2) {
17251 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17252
17253 // First, verify that the first parameter is correct.
17254
17255 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17256
17257 // Two parameter function must have a pointer to const as a
17258 // first parameter; let's strip those qualifiers.
17259 const PointerType *PT = FirstParamType->getAs<PointerType>();
17260
17261 if (!PT) {
17262 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17263 DiagID: diag::err_literal_operator_param)
17264 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17265 return true;
17266 }
17267
17268 QualType PointeeType = PT->getPointeeType();
17269 // First parameter must be const
17270 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17271 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17272 DiagID: diag::err_literal_operator_param)
17273 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17274 return true;
17275 }
17276
17277 QualType InnerType = PointeeType.getUnqualifiedType();
17278 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17279 // const char32_t* are allowed as the first parameter to a two-parameter
17280 // function
17281 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17282 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17283 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17284 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17285 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17286 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17287 DiagID: diag::err_literal_operator_param)
17288 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17289 return true;
17290 }
17291
17292 // Move on to the second and final parameter.
17293 ++Param;
17294
17295 // The second parameter must be a std::size_t.
17296 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17297 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17298 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17299 DiagID: diag::err_literal_operator_param)
17300 << SecondParamType << Context.getSizeType()
17301 << (*Param)->getSourceRange();
17302 return true;
17303 }
17304 } else {
17305 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17306 return true;
17307 }
17308
17309 // Parameters are good.
17310
17311 // A parameter-declaration-clause containing a default argument is not
17312 // equivalent to any of the permitted forms.
17313 for (auto *Param : FnDecl->parameters()) {
17314 if (Param->hasDefaultArg()) {
17315 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17316 DiagID: diag::err_literal_operator_default_argument)
17317 << Param->getDefaultArgRange();
17318 break;
17319 }
17320 }
17321
17322 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17323 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17324 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17325 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17326 // C++23 [usrlit.suffix]p1:
17327 // Literal suffix identifiers that do not start with an underscore are
17328 // reserved for future standardization. Literal suffix identifiers that
17329 // contain a double underscore __ are reserved for use by C++
17330 // implementations.
17331 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17332 << static_cast<int>(Status)
17333 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17334 }
17335
17336 return false;
17337}
17338
17339Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17340 Expr *LangStr,
17341 SourceLocation LBraceLoc) {
17342 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17343 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17344
17345 StringRef Lang = Lit->getString();
17346 LinkageSpecLanguageIDs Language;
17347 if (Lang == "C")
17348 Language = LinkageSpecLanguageIDs::C;
17349 else if (Lang == "C++")
17350 Language = LinkageSpecLanguageIDs::CXX;
17351 else {
17352 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17353 << LangStr->getSourceRange();
17354 return nullptr;
17355 }
17356
17357 // FIXME: Add all the various semantics of linkage specifications
17358
17359 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17360 LangLoc: LangStr->getExprLoc(), Lang: Language,
17361 HasBraces: LBraceLoc.isValid());
17362
17363 /// C++ [module.unit]p7.2.3
17364 /// - Otherwise, if the declaration
17365 /// - ...
17366 /// - ...
17367 /// - appears within a linkage-specification,
17368 /// it is attached to the global module.
17369 ///
17370 /// If the declaration is already in global module fragment, we don't
17371 /// need to attach it again.
17372 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17373 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17374 D->setLocalOwningModule(GlobalModule);
17375 }
17376
17377 CurContext->addDecl(D);
17378 PushDeclContext(S, DC: D);
17379 return D;
17380}
17381
17382Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17383 Decl *LinkageSpec,
17384 SourceLocation RBraceLoc) {
17385 if (RBraceLoc.isValid()) {
17386 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17387 LSDecl->setRBraceLoc(RBraceLoc);
17388 }
17389
17390 // If the current module doesn't has Parent, it implies that the
17391 // LinkageSpec isn't in the module created by itself. So we don't
17392 // need to pop it.
17393 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17394 getCurrentModule()->isImplicitGlobalModule() &&
17395 getCurrentModule()->Parent)
17396 PopImplicitGlobalModuleFragment();
17397
17398 PopDeclContext();
17399 return LinkageSpec;
17400}
17401
17402Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17403 const ParsedAttributesView &AttrList,
17404 SourceLocation SemiLoc) {
17405 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17406 // Attribute declarations appertain to empty declaration so we handle
17407 // them here.
17408 ProcessDeclAttributeList(S, D: ED, AttrList);
17409
17410 CurContext->addDecl(D: ED);
17411 return ED;
17412}
17413
17414VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17415 SourceLocation StartLoc,
17416 SourceLocation Loc,
17417 const IdentifierInfo *Name) {
17418 bool Invalid = false;
17419 QualType ExDeclType = TInfo->getType();
17420
17421 // Arrays and functions decay.
17422 if (ExDeclType->isArrayType())
17423 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17424 else if (ExDeclType->isFunctionType())
17425 ExDeclType = Context.getPointerType(T: ExDeclType);
17426
17427 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17428 // The exception-declaration shall not denote a pointer or reference to an
17429 // incomplete type, other than [cv] void*.
17430 // N2844 forbids rvalue references.
17431 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17432 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17433 Invalid = true;
17434 }
17435
17436 if (ExDeclType->isVariablyModifiedType()) {
17437 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17438 Invalid = true;
17439 }
17440
17441 QualType BaseType = ExDeclType;
17442 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17443 unsigned DK = diag::err_catch_incomplete;
17444 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17445 BaseType = Ptr->getPointeeType();
17446 Mode = 1;
17447 DK = diag::err_catch_incomplete_ptr;
17448 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17449 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17450 BaseType = Ref->getPointeeType();
17451 Mode = 2;
17452 DK = diag::err_catch_incomplete_ref;
17453 }
17454 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17455 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17456 Invalid = true;
17457
17458 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17459 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17460 Invalid = true;
17461 }
17462
17463 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17464 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17465 Invalid = true;
17466 }
17467
17468 if (!Invalid && !ExDeclType->isDependentType() &&
17469 RequireNonAbstractType(Loc, T: ExDeclType,
17470 DiagID: diag::err_abstract_type_in_decl,
17471 Args: AbstractVariableType))
17472 Invalid = true;
17473
17474 // Only the non-fragile NeXT runtime currently supports C++ catches
17475 // of ObjC types, and no runtime supports catching ObjC types by value.
17476 if (!Invalid && getLangOpts().ObjC) {
17477 QualType T = ExDeclType;
17478 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17479 T = RT->getPointeeType();
17480
17481 if (T->isObjCObjectType()) {
17482 Diag(Loc, DiagID: diag::err_objc_object_catch);
17483 Invalid = true;
17484 } else if (T->isObjCObjectPointerType()) {
17485 // FIXME: should this be a test for macosx-fragile specifically?
17486 if (getLangOpts().ObjCRuntime.isFragile())
17487 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17488 }
17489 }
17490
17491 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17492 T: ExDeclType, TInfo, S: SC_None);
17493 ExDecl->setExceptionVariable(true);
17494
17495 // In ARC, infer 'retaining' for variables of retainable type.
17496 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17497 Invalid = true;
17498
17499 if (!Invalid && !ExDeclType->isDependentType()) {
17500 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17501 // Insulate this from anything else we might currently be parsing.
17502 EnterExpressionEvaluationContext scope(
17503 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17504
17505 // C++ [except.handle]p16:
17506 // The object declared in an exception-declaration or, if the
17507 // exception-declaration does not specify a name, a temporary (12.2) is
17508 // copy-initialized (8.5) from the exception object. [...]
17509 // The object is destroyed when the handler exits, after the destruction
17510 // of any automatic objects initialized within the handler.
17511 //
17512 // We just pretend to initialize the object with itself, then make sure
17513 // it can be destroyed later.
17514 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17515
17516 InitializedEntity entity =
17517 InitializedEntity::InitializeVariable(Var: ExDecl);
17518 InitializationKind initKind =
17519 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17520
17521 Expr *opaqueValue =
17522 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17523 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17524 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17525 if (result.isInvalid())
17526 Invalid = true;
17527 else {
17528 // If the constructor used was non-trivial, set this as the
17529 // "initializer".
17530 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17531 if (!construct->getConstructor()->isTrivial()) {
17532 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17533 ExDecl->setInit(init);
17534 }
17535
17536 // And make sure it's destructable.
17537 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17538 }
17539 }
17540 }
17541
17542 if (Invalid)
17543 ExDecl->setInvalidDecl();
17544
17545 return ExDecl;
17546}
17547
17548Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17549 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17550 bool Invalid = D.isInvalidType();
17551
17552 // Check for unexpanded parameter packs.
17553 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17554 UPPC: UPPC_ExceptionType)) {
17555 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17556 Loc: D.getIdentifierLoc());
17557 Invalid = true;
17558 }
17559
17560 const IdentifierInfo *II = D.getIdentifier();
17561 if (NamedDecl *PrevDecl =
17562 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17563 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17564 // The scope should be freshly made just for us. There is just no way
17565 // it contains any previous declaration, except for function parameters in
17566 // a function-try-block's catch statement.
17567 assert(!S->isDeclScope(PrevDecl));
17568 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17569 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17570 << D.getIdentifier();
17571 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17572 Invalid = true;
17573 } else if (PrevDecl->isTemplateParameter())
17574 // Maybe we will complain about the shadowed template parameter.
17575 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17576 }
17577
17578 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17579 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17580 << D.getCXXScopeSpec().getRange();
17581 Invalid = true;
17582 }
17583
17584 VarDecl *ExDecl = BuildExceptionDeclaration(
17585 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17586 if (Invalid)
17587 ExDecl->setInvalidDecl();
17588
17589 // Add the exception declaration into this scope.
17590 if (II)
17591 PushOnScopeChains(D: ExDecl, S);
17592 else
17593 CurContext->addDecl(D: ExDecl);
17594
17595 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17596 return ExDecl;
17597}
17598
17599Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17600 Expr *AssertExpr,
17601 Expr *AssertMessageExpr,
17602 SourceLocation RParenLoc) {
17603 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17604 return nullptr;
17605
17606 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17607 AssertMessageExpr, RParenLoc, Failed: false);
17608}
17609
17610static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17611 switch (BTK) {
17612 case BuiltinType::Char_S:
17613 case BuiltinType::Char_U:
17614 break;
17615 case BuiltinType::Char8:
17616 OS << "u8";
17617 break;
17618 case BuiltinType::Char16:
17619 OS << 'u';
17620 break;
17621 case BuiltinType::Char32:
17622 OS << 'U';
17623 break;
17624 case BuiltinType::WChar_S:
17625 case BuiltinType::WChar_U:
17626 OS << 'L';
17627 break;
17628 default:
17629 llvm_unreachable("Non-character type");
17630 }
17631}
17632
17633/// Convert character's value, interpreted as a code unit, to a string.
17634/// The value needs to be zero-extended to 32-bits.
17635/// FIXME: This assumes Unicode literal encodings
17636static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17637 unsigned TyWidth,
17638 SmallVectorImpl<char> &Str) {
17639 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17640 char *Ptr = Arr;
17641 BuiltinType::Kind K = BTy->getKind();
17642 llvm::raw_svector_ostream OS(Str);
17643
17644 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17645 // other types.
17646 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17647 K == BuiltinType::Char8 || Value <= 0x7F) {
17648 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17649 if (!Escaped.empty())
17650 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17651 else
17652 OS << static_cast<char>(Value);
17653 return;
17654 }
17655
17656 switch (K) {
17657 case BuiltinType::Char16:
17658 case BuiltinType::Char32:
17659 case BuiltinType::WChar_S:
17660 case BuiltinType::WChar_U: {
17661 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17662 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17663 else
17664 OS << "\\x"
17665 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17666 break;
17667 }
17668 default:
17669 llvm_unreachable("Non-character type is passed");
17670 }
17671}
17672
17673/// Convert \V to a string we can present to the user in a diagnostic
17674/// \T is the type of the expression that has been evaluated into \V
17675static bool ConvertAPValueToString(const APValue &V, QualType T,
17676 SmallVectorImpl<char> &Str,
17677 ASTContext &Context) {
17678 if (!V.hasValue())
17679 return false;
17680
17681 switch (V.getKind()) {
17682 case APValue::ValueKind::Int:
17683 if (T->isBooleanType()) {
17684 // Bools are reduced to ints during evaluation, but for
17685 // diagnostic purposes we want to print them as
17686 // true or false.
17687 int64_t BoolValue = V.getInt().getExtValue();
17688 assert((BoolValue == 0 || BoolValue == 1) &&
17689 "Bool type, but value is not 0 or 1");
17690 llvm::raw_svector_ostream OS(Str);
17691 OS << (BoolValue ? "true" : "false");
17692 } else {
17693 llvm::raw_svector_ostream OS(Str);
17694 // Same is true for chars.
17695 // We want to print the character representation for textual types
17696 const auto *BTy = T->getAs<BuiltinType>();
17697 if (BTy) {
17698 switch (BTy->getKind()) {
17699 case BuiltinType::Char_S:
17700 case BuiltinType::Char_U:
17701 case BuiltinType::Char8:
17702 case BuiltinType::Char16:
17703 case BuiltinType::Char32:
17704 case BuiltinType::WChar_S:
17705 case BuiltinType::WChar_U: {
17706 unsigned TyWidth = Context.getIntWidth(T);
17707 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17708 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17709 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17710 OS << '\'';
17711 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17712 OS << "' (0x"
17713 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17714 /*Upper=*/true)
17715 << ", " << V.getInt() << ')';
17716 return true;
17717 }
17718 default:
17719 break;
17720 }
17721 }
17722 V.getInt().toString(Str);
17723 }
17724
17725 break;
17726
17727 case APValue::ValueKind::Float:
17728 V.getFloat().toString(Str);
17729 break;
17730
17731 case APValue::ValueKind::LValue:
17732 if (V.isNullPointer()) {
17733 llvm::raw_svector_ostream OS(Str);
17734 OS << "nullptr";
17735 } else
17736 return false;
17737 break;
17738
17739 case APValue::ValueKind::ComplexFloat: {
17740 llvm::raw_svector_ostream OS(Str);
17741 OS << '(';
17742 V.getComplexFloatReal().toString(Str);
17743 OS << " + ";
17744 V.getComplexFloatImag().toString(Str);
17745 OS << "i)";
17746 } break;
17747
17748 case APValue::ValueKind::ComplexInt: {
17749 llvm::raw_svector_ostream OS(Str);
17750 OS << '(';
17751 V.getComplexIntReal().toString(Str);
17752 OS << " + ";
17753 V.getComplexIntImag().toString(Str);
17754 OS << "i)";
17755 } break;
17756
17757 default:
17758 return false;
17759 }
17760
17761 return true;
17762}
17763
17764/// Some Expression types are not useful to print notes about,
17765/// e.g. literals and values that have already been expanded
17766/// before such as int-valued template parameters.
17767static bool UsefulToPrintExpr(const Expr *E) {
17768 E = E->IgnoreParenImpCasts();
17769 // Literals are pretty easy for humans to understand.
17770 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17771 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17772 return false;
17773
17774 // These have been substituted from template parameters
17775 // and appear as literals in the static assert error.
17776 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17777 return false;
17778
17779 // -5 is also simple to understand.
17780 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17781 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17782
17783 // Only print nested arithmetic operators.
17784 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17785 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17786 BO->isBitwiseOp());
17787
17788 return true;
17789}
17790
17791void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17792 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17793 Op && Op->getOpcode() != BO_LOr) {
17794 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17795 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17796
17797 // Ignore comparisons of boolean expressions with a boolean literal.
17798 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17799 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17800 return;
17801
17802 // Don't print obvious expressions.
17803 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17804 return;
17805
17806 struct {
17807 const clang::Expr *Cond;
17808 Expr::EvalResult Result;
17809 SmallString<12> ValueString;
17810 bool Print;
17811 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17812 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17813 for (auto &DiagSide : DiagSides) {
17814 const Expr *Side = DiagSide.Cond;
17815
17816 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17817
17818 DiagSide.Print = ConvertAPValueToString(
17819 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17820 }
17821 if (DiagSides[0].Print && DiagSides[1].Print) {
17822 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17823 << DiagSides[0].ValueString << Op->getOpcodeStr()
17824 << DiagSides[1].ValueString << Op->getSourceRange();
17825 }
17826 } else {
17827 DiagnoseTypeTraitDetails(E);
17828 }
17829}
17830
17831template <typename ResultType>
17832static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17833 ResultType &Result, ASTContext &Ctx,
17834 Sema::StringEvaluationContext EvalContext,
17835 bool ErrorOnInvalidMessage) {
17836
17837 assert(Message);
17838 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17839 "can't evaluate a dependant static assert message");
17840
17841 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17842 assert(SL->isUnevaluated() && "expected an unevaluated string");
17843 if constexpr (std::is_same_v<APValue, ResultType>) {
17844 Result =
17845 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17846 const ConstantArrayType *CAT =
17847 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17848 assert(CAT && "string literal isn't an array");
17849 QualType CharType = CAT->getElementType();
17850 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17851 CharType->isUnsignedIntegerType());
17852 for (unsigned I = 0; I < SL->getLength(); I++) {
17853 Value = SL->getCodeUnit(i: I);
17854 Result.getArrayInitializedElt(I) = APValue(Value);
17855 }
17856 } else {
17857 Result.assign(SL->getString().begin(), SL->getString().end());
17858 }
17859 return true;
17860 }
17861
17862 SourceLocation Loc = Message->getBeginLoc();
17863 QualType T = Message->getType().getNonReferenceType();
17864 auto *RD = T->getAsCXXRecordDecl();
17865 if (!RD) {
17866 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17867 return false;
17868 }
17869
17870 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17871 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17872 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17873 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17874 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17875 OverloadCandidateSet::CSK_Normal);
17876 if (MemberLookup.empty())
17877 return std::nullopt;
17878 return std::move(MemberLookup);
17879 };
17880
17881 std::optional<LookupResult> SizeMember = FindMember("size");
17882 std::optional<LookupResult> DataMember = FindMember("data");
17883 if (!SizeMember || !DataMember) {
17884 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17885 << EvalContext
17886 << ((!SizeMember && !DataMember) ? 2
17887 : !SizeMember ? 0
17888 : 1);
17889 return false;
17890 }
17891
17892 auto BuildExpr = [&](LookupResult &LR) {
17893 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17894 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17895 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17896 if (Res.isInvalid())
17897 return ExprError();
17898 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17899 IsExecConfig: false, AllowRecovery: true);
17900 if (Res.isInvalid())
17901 return ExprError();
17902 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
17903 return ExprError();
17904 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
17905 };
17906
17907 ExprResult SizeE = BuildExpr(*SizeMember);
17908 ExprResult DataE = BuildExpr(*DataMember);
17909
17910 QualType SizeT = SemaRef.Context.getSizeType();
17911 QualType ConstCharPtr = SemaRef.Context.getPointerType(
17912 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
17913
17914 ExprResult EvaluatedSize =
17915 SizeE.isInvalid()
17916 ? ExprError()
17917 : SemaRef.BuildConvertedConstantExpression(
17918 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
17919 if (EvaluatedSize.isInvalid()) {
17920 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17921 << EvalContext << /*size*/ 0;
17922 return false;
17923 }
17924
17925 ExprResult EvaluatedData =
17926 DataE.isInvalid()
17927 ? ExprError()
17928 : SemaRef.BuildConvertedConstantExpression(
17929 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
17930 if (EvaluatedData.isInvalid()) {
17931 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
17932 << EvalContext << /*data*/ 1;
17933 return false;
17934 }
17935
17936 if (!ErrorOnInvalidMessage &&
17937 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
17938 return true;
17939
17940 Expr::EvalResult Status;
17941 SmallVector<PartialDiagnosticAt, 8> Notes;
17942 Status.Diag = &Notes;
17943 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
17944 EvaluatedData.get(), Ctx, Status) ||
17945 !Notes.empty()) {
17946 SemaRef.Diag(Loc: Message->getBeginLoc(),
17947 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
17948 : diag::warn_user_defined_msg_constexpr)
17949 << EvalContext;
17950 for (const auto &Note : Notes)
17951 SemaRef.Diag(Loc: Note.first, PD: Note.second);
17952 return !ErrorOnInvalidMessage;
17953 }
17954 return true;
17955}
17956
17957bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
17958 StringEvaluationContext EvalContext,
17959 bool ErrorOnInvalidMessage) {
17960 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17961 ErrorOnInvalidMessage);
17962}
17963
17964bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
17965 StringEvaluationContext EvalContext,
17966 bool ErrorOnInvalidMessage) {
17967 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
17968 ErrorOnInvalidMessage);
17969}
17970
17971Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17972 Expr *AssertExpr, Expr *AssertMessage,
17973 SourceLocation RParenLoc,
17974 bool Failed) {
17975 assert(AssertExpr != nullptr && "Expected non-null condition");
17976 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
17977 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
17978 !AssertMessage->isValueDependent())) &&
17979 !Failed) {
17980 // In a static_assert-declaration, the constant-expression shall be a
17981 // constant expression that can be contextually converted to bool.
17982 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
17983 if (Converted.isInvalid())
17984 Failed = true;
17985
17986 ExprResult FullAssertExpr =
17987 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
17988 /*DiscardedValue*/ false,
17989 /*IsConstexpr*/ true);
17990 if (FullAssertExpr.isInvalid())
17991 Failed = true;
17992 else
17993 AssertExpr = FullAssertExpr.get();
17994
17995 llvm::APSInt Cond;
17996 Expr *BaseExpr = AssertExpr;
17997 AllowFoldKind FoldKind = AllowFoldKind::No;
17998
17999 if (!getLangOpts().CPlusPlus) {
18000 // In C mode, allow folding as an extension for better compatibility with
18001 // C++ in terms of expressions like static_assert("test") or
18002 // static_assert(nullptr).
18003 FoldKind = AllowFoldKind::Allow;
18004 }
18005
18006 if (!Failed && VerifyIntegerConstantExpression(
18007 E: BaseExpr, Result: &Cond,
18008 DiagID: diag::err_static_assert_expression_is_not_constant,
18009 CanFold: FoldKind).isInvalid())
18010 Failed = true;
18011
18012 // If the static_assert passes, only verify that
18013 // the message is grammatically valid without evaluating it.
18014 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18015 std::string Str;
18016 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18017 EvalContext: StringEvaluationContext::StaticAssert,
18018 /*ErrorOnInvalidMessage=*/false);
18019 }
18020
18021 // CWG2518
18022 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18023 // template definition, the declaration has no effect.
18024 bool InTemplateDefinition =
18025 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18026
18027 if (!Failed && !Cond && !InTemplateDefinition) {
18028 SmallString<256> MsgBuffer;
18029 llvm::raw_svector_ostream Msg(MsgBuffer);
18030 bool HasMessage = AssertMessage;
18031 if (AssertMessage) {
18032 std::string Str;
18033 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18034 EvalContext: StringEvaluationContext::StaticAssert,
18035 /*ErrorOnInvalidMessage=*/true) ||
18036 !Str.empty();
18037 Msg << Str;
18038 }
18039 Expr *InnerCond = nullptr;
18040 std::string InnerCondDescription;
18041 std::tie(args&: InnerCond, args&: InnerCondDescription) =
18042 findFailedBooleanCondition(Cond: Converted.get());
18043 if (const auto *ConceptIDExpr =
18044 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18045 const ASTConstraintSatisfaction &Satisfaction =
18046 ConceptIDExpr->getSatisfaction();
18047 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18048 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18049 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18050 // Drill down into concept specialization expressions to see why they
18051 // weren't satisfied.
18052 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18053 }
18054 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18055 !isa<IntegerLiteral>(Val: InnerCond)) {
18056 Diag(Loc: InnerCond->getBeginLoc(),
18057 DiagID: diag::err_static_assert_requirement_failed)
18058 << InnerCondDescription << !HasMessage << Msg.str()
18059 << InnerCond->getSourceRange();
18060 DiagnoseStaticAssertDetails(E: InnerCond);
18061 } else {
18062 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18063 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18064 PrintContextStack();
18065 }
18066 Failed = true;
18067 }
18068 } else {
18069 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18070 /*DiscardedValue*/false,
18071 /*IsConstexpr*/true);
18072 if (FullAssertExpr.isInvalid())
18073 Failed = true;
18074 else
18075 AssertExpr = FullAssertExpr.get();
18076 }
18077
18078 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18079 AssertExpr, Message: AssertMessage, RParenLoc,
18080 Failed);
18081
18082 CurContext->addDecl(D: Decl);
18083 return Decl;
18084}
18085
18086DeclResult Sema::ActOnTemplatedFriendTag(
18087 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18088 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18089 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18090 MultiTemplateParamsArg TempParamLists) {
18091 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18092
18093 bool IsMemberSpecialization = false;
18094 bool Invalid = false;
18095
18096 if (TemplateParameterList *TemplateParams =
18097 MatchTemplateParametersToScopeSpecifier(
18098 DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId: nullptr, ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18099 IsMemberSpecialization, Invalid)) {
18100 if (TemplateParams->size() > 0) {
18101 // This is a declaration of a class template.
18102 if (Invalid)
18103 return true;
18104
18105 return CheckClassTemplate(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS,
18106 Name, NameLoc, Attr, TemplateParams, AS: AS_public,
18107 /*ModulePrivateLoc=*/SourceLocation(),
18108 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1,
18109 OuterTemplateParamLists: TempParamLists.data(), IsMemberSpecialization)
18110 .get();
18111 } else {
18112 // The "template<>" header is extraneous.
18113 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18114 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18115 }
18116 }
18117
18118 if (Invalid) return true;
18119
18120 bool isAllExplicitSpecializations =
18121 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18122 return List->size() == 0;
18123 });
18124
18125 // FIXME: don't ignore attributes.
18126
18127 // If it's explicit specializations all the way down, just forget
18128 // about the template header and build an appropriate non-templated
18129 // friend. TODO: for source fidelity, remember the headers.
18130 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18131 if (isAllExplicitSpecializations) {
18132 if (SS.isEmpty()) {
18133 bool Owned = false;
18134 bool IsDependent = false;
18135 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18136 Attr, AS: AS_public,
18137 /*ModulePrivateLoc=*/SourceLocation(),
18138 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18139 /*ScopedEnumKWLoc=*/SourceLocation(),
18140 /*ScopedEnumUsesClassTag=*/false,
18141 /*UnderlyingType=*/TypeResult(),
18142 /*IsTypeSpecifier=*/false,
18143 /*IsTemplateParamOrArg=*/false,
18144 /*OOK=*/OffsetOfKind::Outside);
18145 }
18146
18147 TypeSourceInfo *TSI = nullptr;
18148 ElaboratedTypeKeyword Keyword
18149 = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18150 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18151 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18152 if (T.isNull())
18153 return true;
18154
18155 FriendDecl *Friend =
18156 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18157 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18158 Friend->setAccess(AS_public);
18159 CurContext->addDecl(D: Friend);
18160 return Friend;
18161 }
18162
18163 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18164
18165 // CWG 2917: if it (= the friend-type-specifier) is a pack expansion
18166 // (13.7.4 [temp.variadic]), any packs expanded by that pack expansion
18167 // shall not have been introduced by the template-declaration.
18168 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18169 collectUnexpandedParameterPacks(NNS: QualifierLoc, Unexpanded);
18170 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18171 for (UnexpandedParameterPack &U : Unexpanded) {
18172 if (std::optional<std::pair<unsigned, unsigned>> DI = getDepthAndIndex(UPP: U);
18173 DI && DI->first >= FriendDeclDepth) {
18174 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18175 if (!ND)
18176 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18177 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18178 << ND->getDeclName() << SourceRange(SS.getBeginLoc(), EllipsisLoc);
18179 return true;
18180 }
18181 }
18182
18183 // Handle the case of a templated-scope friend class. e.g.
18184 // template <class T> class A<T>::B;
18185 // FIXME: we don't support these right now.
18186 Diag(Loc: NameLoc, DiagID: diag::warn_template_qualified_friend_unsupported)
18187 << SS.getScopeRep() << SS.getRange() << cast<CXXRecordDecl>(Val: CurContext);
18188 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18189 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18190 TypeSourceInfo *TSI = Context.CreateTypeSourceInfo(T);
18191 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18192 TL.setElaboratedKeywordLoc(TagLoc);
18193 TL.setQualifierLoc(SS.getWithLocInContext(Context));
18194 TL.setNameLoc(NameLoc);
18195
18196 FriendDecl *Friend =
18197 FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend_: TSI, FriendL: FriendLoc,
18198 EllipsisLoc, FriendTypeTPLists: TempParamLists);
18199 Friend->setAccess(AS_public);
18200 Friend->setUnsupportedFriend(true);
18201 CurContext->addDecl(D: Friend);
18202 return Friend;
18203}
18204
18205Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18206 MultiTemplateParamsArg TempParams,
18207 SourceLocation EllipsisLoc) {
18208 SourceLocation Loc = DS.getBeginLoc();
18209 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18210
18211 assert(DS.isFriendSpecified());
18212 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18213
18214 // C++ [class.friend]p3:
18215 // A friend declaration that does not declare a function shall have one of
18216 // the following forms:
18217 // friend elaborated-type-specifier ;
18218 // friend simple-type-specifier ;
18219 // friend typename-specifier ;
18220 //
18221 // If the friend keyword isn't first, or if the declarations has any type
18222 // qualifiers, then the declaration doesn't have that form.
18223 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18224 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18225 if (DS.getTypeQualifiers()) {
18226 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18227 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18228 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18229 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18230 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18231 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18232 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18233 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18234 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18235 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18236 }
18237
18238 // Try to convert the decl specifier to a type. This works for
18239 // friend templates because ActOnTag never produces a ClassTemplateDecl
18240 // for a TagUseKind::Friend.
18241 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18242 DeclaratorContext::Member);
18243 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18244 QualType T = TSI->getType();
18245 if (TheDeclarator.isInvalidType())
18246 return nullptr;
18247
18248 // If '...' is present, the type must contain an unexpanded parameter
18249 // pack, and vice versa.
18250 bool Invalid = false;
18251 if (EllipsisLoc.isInvalid() &&
18252 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18253 return nullptr;
18254 if (EllipsisLoc.isValid() &&
18255 !TSI->getType()->containsUnexpandedParameterPack()) {
18256 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18257 << TSI->getTypeLoc().getSourceRange();
18258 Invalid = true;
18259 }
18260
18261 if (!T->isElaboratedTypeSpecifier()) {
18262 if (TempParams.size()) {
18263 // C++23 [dcl.pre]p5:
18264 // In a simple-declaration, the optional init-declarator-list can be
18265 // omitted only when declaring a class or enumeration, that is, when
18266 // the decl-specifier-seq contains either a class-specifier, an
18267 // elaborated-type-specifier with a class-key, or an enum-specifier.
18268 //
18269 // The declaration of a template-declaration or explicit-specialization
18270 // is never a member-declaration, so this must be a simple-declaration
18271 // with no init-declarator-list. Therefore, this is ill-formed.
18272 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18273 return nullptr;
18274 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18275 SmallString<16> InsertionText(" ");
18276 InsertionText += RD->getKindName();
18277
18278 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18279 ? diag::warn_cxx98_compat_unelaborated_friend_type
18280 : diag::ext_unelaborated_friend_type)
18281 << (unsigned)RD->getTagKind() << T
18282 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18283 Code: InsertionText);
18284 } else {
18285 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18286 << T << DS.getSourceRange();
18287 }
18288 }
18289
18290 // C++98 [class.friend]p1: A friend of a class is a function
18291 // or class that is not a member of the class . . .
18292 // This is fixed in DR77, which just barely didn't make the C++03
18293 // deadline. It's also a very silly restriction that seriously
18294 // affects inner classes and which nobody else seems to implement;
18295 // thus we never diagnose it, not even in -pedantic.
18296 //
18297 // But note that we could warn about it: it's always useless to
18298 // friend one of your own members (it's not, however, worthless to
18299 // friend a member of an arbitrary specialization of your template).
18300
18301 Decl *D;
18302 if (!TempParams.empty())
18303 // TODO: Support variadic friend template decls?
18304 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Params: TempParams, Friend: TSI,
18305 FriendLoc);
18306 else
18307 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18308 Friend_: TSI, FriendL: FriendLoc, EllipsisLoc);
18309
18310 if (!D)
18311 return nullptr;
18312
18313 D->setAccess(AS_public);
18314 CurContext->addDecl(D);
18315
18316 if (Invalid)
18317 D->setInvalidDecl();
18318
18319 return D;
18320}
18321
18322NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18323 MultiTemplateParamsArg TemplateParams) {
18324 const DeclSpec &DS = D.getDeclSpec();
18325
18326 assert(DS.isFriendSpecified());
18327 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18328
18329 SourceLocation Loc = D.getIdentifierLoc();
18330 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18331
18332 // C++ [class.friend]p1
18333 // A friend of a class is a function or class....
18334 // Note that this sees through typedefs, which is intended.
18335 // It *doesn't* see through dependent types, which is correct
18336 // according to [temp.arg.type]p3:
18337 // If a declaration acquires a function type through a
18338 // type dependent on a template-parameter and this causes
18339 // a declaration that does not use the syntactic form of a
18340 // function declarator to have a function type, the program
18341 // is ill-formed.
18342 if (!TInfo->getType()->isFunctionType()) {
18343 Diag(Loc, DiagID: diag::err_unexpected_friend);
18344
18345 // It might be worthwhile to try to recover by creating an
18346 // appropriate declaration.
18347 return nullptr;
18348 }
18349
18350 // C++ [namespace.memdef]p3
18351 // - If a friend declaration in a non-local class first declares a
18352 // class or function, the friend class or function is a member
18353 // of the innermost enclosing namespace.
18354 // - The name of the friend is not found by simple name lookup
18355 // until a matching declaration is provided in that namespace
18356 // scope (either before or after the class declaration granting
18357 // friendship).
18358 // - If a friend function is called, its name may be found by the
18359 // name lookup that considers functions from namespaces and
18360 // classes associated with the types of the function arguments.
18361 // - When looking for a prior declaration of a class or a function
18362 // declared as a friend, scopes outside the innermost enclosing
18363 // namespace scope are not considered.
18364
18365 CXXScopeSpec &SS = D.getCXXScopeSpec();
18366 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18367 assert(NameInfo.getName());
18368
18369 // Check for unexpanded parameter packs.
18370 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18371 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18372 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18373 return nullptr;
18374
18375 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18376
18377 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18378 auto Kind = SS.getScopeRep().getKind();
18379 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18380 Kind == NestedNameSpecifier::Kind::Namespace;
18381 if (IsNamespaceOrGlobal) {
18382 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def)
18383 << SS.getScopeRep() << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18384 SS.clear();
18385 }
18386 }
18387
18388 // The context we found the declaration in, or in which we should
18389 // create the declaration.
18390 DeclContext *DC;
18391 Scope *DCScope = S;
18392 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18393 RedeclarationKind::ForExternalRedeclaration);
18394
18395 // There are five cases here.
18396 // - There's no scope specifier and we're in a local class. Only look
18397 // for functions declared in the immediately-enclosing block scope.
18398 // We recover from invalid scope qualifiers as if they just weren't there.
18399 FunctionDecl *FunctionContainingLocalClass = nullptr;
18400 if ((SS.isInvalid() || !SS.isSet()) &&
18401 (FunctionContainingLocalClass =
18402 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18403 // C++11 [class.friend]p11:
18404 // If a friend declaration appears in a local class and the name
18405 // specified is an unqualified name, a prior declaration is
18406 // looked up without considering scopes that are outside the
18407 // innermost enclosing non-class scope. For a friend function
18408 // declaration, if there is no prior declaration, the program is
18409 // ill-formed.
18410
18411 // Find the innermost enclosing non-class scope. This is the block
18412 // scope containing the local class definition (or for a nested class,
18413 // the outer local class).
18414 DCScope = S->getFnParent();
18415
18416 // Look up the function name in the scope.
18417 Previous.clear(Kind: LookupLocalFriendName);
18418 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18419
18420 if (!Previous.empty()) {
18421 // All possible previous declarations must have the same context:
18422 // either they were declared at block scope or they are members of
18423 // one of the enclosing local classes.
18424 DC = Previous.getRepresentativeDecl()->getDeclContext();
18425 } else {
18426 // This is ill-formed, but provide the context that we would have
18427 // declared the function in, if we were permitted to, for error recovery.
18428 DC = FunctionContainingLocalClass;
18429 }
18430 adjustContextForLocalExternDecl(DC);
18431
18432 // - There's no scope specifier, in which case we just go to the
18433 // appropriate scope and look for a function or function template
18434 // there as appropriate.
18435 } else if (SS.isInvalid() || !SS.isSet()) {
18436 // C++11 [namespace.memdef]p3:
18437 // If the name in a friend declaration is neither qualified nor
18438 // a template-id and the declaration is a function or an
18439 // elaborated-type-specifier, the lookup to determine whether
18440 // the entity has been previously declared shall not consider
18441 // any scopes outside the innermost enclosing namespace.
18442
18443 // Find the appropriate context according to the above.
18444 DC = CurContext;
18445
18446 // Skip class contexts. If someone can cite chapter and verse
18447 // for this behavior, that would be nice --- it's what GCC and
18448 // EDG do, and it seems like a reasonable intent, but the spec
18449 // really only says that checks for unqualified existing
18450 // declarations should stop at the nearest enclosing namespace,
18451 // not that they should only consider the nearest enclosing
18452 // namespace.
18453 while (DC->isRecord())
18454 DC = DC->getParent();
18455
18456 DeclContext *LookupDC = DC->getNonTransparentContext();
18457 while (true) {
18458 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18459
18460 if (!Previous.empty()) {
18461 DC = LookupDC;
18462 break;
18463 }
18464
18465 if (isTemplateId) {
18466 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18467 } else {
18468 if (LookupDC->isFileContext()) break;
18469 }
18470 LookupDC = LookupDC->getParent();
18471 }
18472
18473 DCScope = getScopeForDeclContext(S, DC);
18474
18475 // - There's a non-dependent scope specifier, in which case we
18476 // compute it and do a previous lookup there for a function
18477 // or function template.
18478 } else if (!SS.getScopeRep().isDependent()) {
18479 DC = computeDeclContext(SS);
18480 if (!DC) return nullptr;
18481
18482 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18483
18484 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18485
18486 // C++ [class.friend]p1: A friend of a class is a function or
18487 // class that is not a member of the class . . .
18488 if (DC->Equals(DC: CurContext))
18489 Diag(Loc: DS.getFriendSpecLoc(),
18490 DiagID: getLangOpts().CPlusPlus11 ?
18491 diag::warn_cxx98_compat_friend_is_member :
18492 diag::err_friend_is_member);
18493
18494 // - There's a scope specifier that does not match any template
18495 // parameter lists, in which case we use some arbitrary context,
18496 // create a method or method template, and wait for instantiation.
18497 // - There's a scope specifier that does match some template
18498 // parameter lists, which we don't handle right now.
18499 } else {
18500 DC = CurContext;
18501 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18502 }
18503
18504 if (!DC->isRecord()) {
18505 int DiagArg = -1;
18506 switch (D.getName().getKind()) {
18507 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18508 case UnqualifiedIdKind::IK_ConstructorName:
18509 DiagArg = 0;
18510 break;
18511 case UnqualifiedIdKind::IK_DestructorName:
18512 DiagArg = 1;
18513 break;
18514 case UnqualifiedIdKind::IK_ConversionFunctionId:
18515 DiagArg = 2;
18516 break;
18517 case UnqualifiedIdKind::IK_DeductionGuideName:
18518 DiagArg = 3;
18519 break;
18520 case UnqualifiedIdKind::IK_Identifier:
18521 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18522 case UnqualifiedIdKind::IK_LiteralOperatorId:
18523 case UnqualifiedIdKind::IK_OperatorFunctionId:
18524 case UnqualifiedIdKind::IK_TemplateId:
18525 break;
18526 }
18527 // This implies that it has to be an operator or function.
18528 if (DiagArg >= 0) {
18529 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18530 return nullptr;
18531 }
18532 } else {
18533 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(Val: DC);
18534 if (RC->isLambda()) {
18535 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_lambda_decl);
18536 }
18537 }
18538
18539 // FIXME: This is an egregious hack to cope with cases where the scope stack
18540 // does not contain the declaration context, i.e., in an out-of-line
18541 // definition of a class.
18542 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18543 if (!DCScope) {
18544 FakeDCScope.setEntity(DC);
18545 DCScope = &FakeDCScope;
18546 }
18547
18548 bool AddToScope = true;
18549 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18550 TemplateParamLists: TemplateParams, AddToScope);
18551 if (!ND) return nullptr;
18552
18553 assert(ND->getLexicalDeclContext() == CurContext);
18554
18555 // If we performed typo correction, we might have added a scope specifier
18556 // and changed the decl context.
18557 DC = ND->getDeclContext();
18558
18559 // Add the function declaration to the appropriate lookup tables,
18560 // adjusting the redeclarations list as necessary. We don't
18561 // want to do this yet if the friending class is dependent.
18562 //
18563 // Also update the scope-based lookup if the target context's
18564 // lookup context is in lexical scope.
18565 if (!CurContext->isDependentContext()) {
18566 DC = DC->getRedeclContext();
18567 DC->makeDeclVisibleInContext(D: ND);
18568 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18569 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18570 }
18571
18572 FriendDecl *FrD = FriendDecl::Create(C&: Context, DC: CurContext,
18573 L: D.getIdentifierLoc(), Friend_: ND,
18574 FriendL: DS.getFriendSpecLoc());
18575 FrD->setAccess(AS_public);
18576 CurContext->addDecl(D: FrD);
18577
18578 if (ND->isInvalidDecl()) {
18579 FrD->setInvalidDecl();
18580 } else {
18581 if (DC->isRecord()) CheckFriendAccess(D: ND);
18582
18583 FunctionDecl *FD;
18584 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: ND))
18585 FD = FTD->getTemplatedDecl();
18586 else
18587 FD = cast<FunctionDecl>(Val: ND);
18588
18589 // C++ [class.friend]p6:
18590 // A function may be defined in a friend declaration of a class if and
18591 // only if the class is a non-local class, and the function name is
18592 // unqualified.
18593 if (D.isFunctionDefinition()) {
18594 // Qualified friend function definition.
18595 if (SS.isNotEmpty()) {
18596 // FIXME: We should only do this if the scope specifier names the
18597 // innermost enclosing namespace; otherwise the fixit changes the
18598 // meaning of the code.
18599 SemaDiagnosticBuilder DB =
18600 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18601
18602 DB << SS.getScopeRep();
18603 if (DC->isFileContext())
18604 DB << FixItHint::CreateRemoval(RemoveRange: SS.getRange());
18605
18606 // Friend function defined in a local class.
18607 } else if (FunctionContainingLocalClass) {
18608 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18609
18610 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18611 // a template-id, the function name is not unqualified because these is
18612 // no name. While the wording requires some reading in-between the
18613 // lines, GCC, MSVC, and EDG all consider a friend function
18614 // specialization definitions to be de facto explicit specialization
18615 // and diagnose them as such.
18616 } else if (isTemplateId) {
18617 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18618 }
18619 }
18620
18621 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18622 // default argument expression, that declaration shall be a definition
18623 // and shall be the only declaration of the function or function
18624 // template in the translation unit.
18625 if (functionDeclHasDefaultArgument(FD)) {
18626 // We can't look at FD->getPreviousDecl() because it may not have been set
18627 // if we're in a dependent context. If the function is known to be a
18628 // redeclaration, we will have narrowed Previous down to the right decl.
18629 if (D.isRedeclaration()) {
18630 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18631 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18632 DiagID: diag::note_previous_declaration);
18633 } else if (!D.isFunctionDefinition())
18634 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18635 }
18636
18637 // Mark templated-scope function declarations as unsupported.
18638 if (!FD->getTemplateParameterLists().empty() && SS.isValid()) {
18639 Diag(Loc: FD->getLocation(), DiagID: diag::warn_template_qualified_friend_unsupported)
18640 << SS.getScopeRep() << SS.getRange()
18641 << cast<CXXRecordDecl>(Val: CurContext);
18642 FrD->setUnsupportedFriend(true);
18643 }
18644 }
18645
18646 warnOnReservedIdentifier(D: ND);
18647
18648 return ND;
18649}
18650
18651void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18652 StringLiteral *Message) {
18653 AdjustDeclIfTemplate(Decl&: Dcl);
18654
18655 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18656 if (!Fn) {
18657 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18658 return;
18659 }
18660
18661 // Deleted function does not have a body.
18662 Fn->setWillHaveBody(false);
18663
18664 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18665 // Don't consider the implicit declaration we generate for explicit
18666 // specializations. FIXME: Do not generate these implicit declarations.
18667 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18668 Prev->getPreviousDecl()) &&
18669 !Prev->isDefined()) {
18670 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18671 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18672 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18673 : diag::note_previous_declaration);
18674 // We can't recover from this; the declaration might have already
18675 // been used.
18676 Fn->setInvalidDecl();
18677 return;
18678 }
18679
18680 // To maintain the invariant that functions are only deleted on their first
18681 // declaration, mark the implicitly-instantiated declaration of the
18682 // explicitly-specialized function as deleted instead of marking the
18683 // instantiated redeclaration.
18684 Fn = Fn->getCanonicalDecl();
18685 }
18686
18687 // dllimport/dllexport cannot be deleted.
18688 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18689 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18690 Fn->setInvalidDecl();
18691 }
18692
18693 // C++11 [basic.start.main]p3:
18694 // A program that defines main as deleted [...] is ill-formed.
18695 if (Fn->isMain())
18696 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18697
18698 // C++11 [dcl.fct.def.delete]p4:
18699 // A deleted function is implicitly inline.
18700 Fn->setImplicitlyInline();
18701 Fn->setDeletedAsWritten(D: true, Message);
18702}
18703
18704void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18705 if (!Dcl || Dcl->isInvalidDecl())
18706 return;
18707
18708 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18709 if (!FD) {
18710 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18711 if (getDefaultedFunctionKind(FD: FTD->getTemplatedDecl()).isComparison()) {
18712 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18713 return;
18714 }
18715 }
18716
18717 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18718 << getLangOpts().CPlusPlus20;
18719 return;
18720 }
18721
18722 // Reject if this can't possibly be a defaultable function.
18723 DefaultedFunctionKind DefKind = getDefaultedFunctionKind(FD);
18724 if (!DefKind &&
18725 // A dependent function that doesn't locally look defaultable can
18726 // still instantiate to a defaultable function if it's a constructor
18727 // or assignment operator.
18728 (!FD->isDependentContext() ||
18729 (!isa<CXXConstructorDecl>(Val: FD) &&
18730 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
18731 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18732 << getLangOpts().CPlusPlus20;
18733 return;
18734 }
18735
18736 // Issue compatibility warning. We already warned if the operator is
18737 // 'operator<=>' when parsing the '<=>' token.
18738 if (DefKind.isComparison() &&
18739 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
18740 Diag(Loc: DefaultLoc, DiagID: getLangOpts().CPlusPlus20
18741 ? diag::warn_cxx17_compat_defaulted_comparison
18742 : diag::ext_defaulted_comparison);
18743 }
18744
18745 FD->setDefaulted();
18746 FD->setExplicitlyDefaulted();
18747 FD->setDefaultLoc(DefaultLoc);
18748
18749 // Defer checking functions that are defaulted in a dependent context.
18750 if (FD->isDependentContext())
18751 return;
18752
18753 // Unset that we will have a body for this function. We might not,
18754 // if it turns out to be trivial, and we don't need this marking now
18755 // that we've marked it as defaulted.
18756 FD->setWillHaveBody(false);
18757
18758 if (DefKind.isComparison()) {
18759 // If this comparison's defaulting occurs within the definition of its
18760 // lexical class context, we have to do the checking when complete.
18761 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
18762 if (!RD->isCompleteDefinition())
18763 return;
18764 }
18765
18766 // If this member fn was defaulted on its first declaration, we will have
18767 // already performed the checking in CheckCompletedCXXClass. Such a
18768 // declaration doesn't trigger an implicit definition.
18769 if (isa<CXXMethodDecl>(Val: FD)) {
18770 const FunctionDecl *Primary = FD;
18771 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
18772 // Ask the template instantiation pattern that actually had the
18773 // '= default' on it.
18774 Primary = Pattern;
18775 if (Primary->getCanonicalDecl()->isDefaulted())
18776 return;
18777 }
18778
18779 if (DefKind.isComparison()) {
18780 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
18781 FD->setInvalidDecl();
18782 else
18783 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
18784 } else {
18785 auto *MD = cast<CXXMethodDecl>(Val: FD);
18786
18787 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
18788 DefaultLoc))
18789 MD->setInvalidDecl();
18790 else
18791 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
18792 }
18793}
18794
18795static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
18796 for (Stmt *SubStmt : S->children()) {
18797 if (!SubStmt)
18798 continue;
18799 if (isa<ReturnStmt>(Val: SubStmt))
18800 Self.Diag(Loc: SubStmt->getBeginLoc(),
18801 DiagID: diag::err_return_in_constructor_handler);
18802 if (!isa<Expr>(Val: SubStmt))
18803 SearchForReturnInStmt(Self, S: SubStmt);
18804 }
18805}
18806
18807void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
18808 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
18809 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
18810 SearchForReturnInStmt(Self&: *this, S: Handler);
18811 }
18812}
18813
18814void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
18815 StringLiteral *DeletedMessage) {
18816 switch (BodyKind) {
18817 case FnBodyKind::Delete:
18818 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
18819 break;
18820 case FnBodyKind::Default:
18821 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
18822 break;
18823 case FnBodyKind::Other:
18824 llvm_unreachable(
18825 "Parsed function body should be '= delete;' or '= default;'");
18826 }
18827}
18828
18829bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
18830 const CXXMethodDecl *Old) {
18831 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18832 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
18833
18834 if (OldFT->hasExtParameterInfos()) {
18835 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
18836 // A parameter of the overriding method should be annotated with noescape
18837 // if the corresponding parameter of the overridden method is annotated.
18838 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
18839 !NewFT->getExtParameterInfo(I).isNoEscape()) {
18840 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
18841 DiagID: diag::warn_overriding_method_missing_noescape);
18842 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
18843 DiagID: diag::note_overridden_marked_noescape);
18844 }
18845 }
18846
18847 // SME attributes must match when overriding a function declaration.
18848 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
18849 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
18850 << New << New->getType() << Old->getType();
18851 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18852 return true;
18853 }
18854
18855 // Virtual overrides must have the same code_seg.
18856 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
18857 const auto *NewCSA = New->getAttr<CodeSegAttr>();
18858 if ((NewCSA || OldCSA) &&
18859 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
18860 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
18861 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
18862 return true;
18863 }
18864
18865 // Virtual overrides: check for matching effects.
18866 if (Context.hasAnyFunctionEffects()) {
18867 const auto OldFX = Old->getFunctionEffects();
18868 const auto NewFXOrig = New->getFunctionEffects();
18869
18870 if (OldFX != NewFXOrig) {
18871 FunctionEffectSet NewFX(NewFXOrig);
18872 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
18873 FunctionEffectSet::Conflicts Errs;
18874 for (const auto &Diff : Diffs) {
18875 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
18876 case FunctionEffectDiff::OverrideResult::NoAction:
18877 break;
18878 case FunctionEffectDiff::OverrideResult::Warn:
18879 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
18880 << Diff.effectName();
18881 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18882 << Old->getReturnTypeSourceRange();
18883 break;
18884 case FunctionEffectDiff::OverrideResult::Merge: {
18885 NewFX.insert(NewEC: Diff.Old.value(), Errs);
18886 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
18887 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
18888 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
18889 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
18890 Args: NewFT->getParamTypes(), EPI);
18891 New->setType(ModQT);
18892 if (Errs.empty()) {
18893 // A warning here is somewhat pedantic. Skip this if there was
18894 // already a merge conflict, which is more serious.
18895 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
18896 << Diff.effectName();
18897 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18898 << Old->getReturnTypeSourceRange();
18899 }
18900 break;
18901 }
18902 }
18903 }
18904 if (!Errs.empty())
18905 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
18906 OldLoc: Old->getLocation());
18907 }
18908 }
18909
18910 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
18911
18912 // If the calling conventions match, everything is fine
18913 if (NewCC == OldCC)
18914 return false;
18915
18916 // If the calling conventions mismatch because the new function is static,
18917 // suppress the calling convention mismatch error; the error about static
18918 // function override (err_static_overrides_virtual from
18919 // Sema::CheckFunctionDeclaration) is more clear.
18920 if (New->getStorageClass() == SC_Static)
18921 return false;
18922
18923 Diag(Loc: New->getLocation(),
18924 DiagID: diag::err_conflicting_overriding_cc_attributes)
18925 << New->getDeclName() << New->getType() << Old->getType();
18926 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18927 return true;
18928}
18929
18930bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
18931 const CXXMethodDecl *Old) {
18932 // CWG2553
18933 // A virtual function shall not be an explicit object member function.
18934 if (!New->isExplicitObjectMemberFunction())
18935 return true;
18936 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
18937 DiagID: diag::err_explicit_object_parameter_nonmember)
18938 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
18939 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
18940 New->setInvalidDecl();
18941 return false;
18942}
18943
18944bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
18945 const CXXMethodDecl *Old) {
18946 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
18947 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
18948
18949 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
18950 NewTy->isDependentType() || OldTy->isDependentType())
18951 return false;
18952
18953 // Check if the return types are covariant
18954 QualType NewClassTy, OldClassTy;
18955
18956 /// Both types must be pointers or references to classes.
18957 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
18958 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
18959 NewClassTy = NewPT->getPointeeType();
18960 OldClassTy = OldPT->getPointeeType();
18961 }
18962 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
18963 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
18964 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
18965 NewClassTy = NewRT->getPointeeType();
18966 OldClassTy = OldRT->getPointeeType();
18967 }
18968 }
18969 }
18970
18971 // The return types aren't either both pointers or references to a class type.
18972 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
18973 Diag(Loc: New->getLocation(),
18974 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
18975 << New->getDeclName() << NewTy << OldTy
18976 << New->getReturnTypeSourceRange();
18977 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
18978 << Old->getReturnTypeSourceRange();
18979
18980 return true;
18981 }
18982
18983 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
18984 // C++14 [class.virtual]p8:
18985 // If the class type in the covariant return type of D::f differs from
18986 // that of B::f, the class type in the return type of D::f shall be
18987 // complete at the point of declaration of D::f or shall be the class
18988 // type D.
18989 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
18990 if (!RD->isBeingDefined() &&
18991 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
18992 DiagID: diag::err_covariant_return_incomplete,
18993 Args: New->getDeclName()))
18994 return true;
18995 }
18996
18997 // Check if the new class derives from the old class.
18998 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
18999 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
19000 << New->getDeclName() << NewTy << OldTy
19001 << New->getReturnTypeSourceRange();
19002 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19003 << Old->getReturnTypeSourceRange();
19004 return true;
19005 }
19006
19007 // Check if we the conversion from derived to base is valid.
19008 if (CheckDerivedToBaseConversion(
19009 Derived: NewClassTy, Base: OldClassTy,
19010 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
19011 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
19012 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
19013 Name: New->getDeclName(), BasePath: nullptr)) {
19014 // FIXME: this note won't trigger for delayed access control
19015 // diagnostics, and it's impossible to get an undelayed error
19016 // here from access control during the original parse because
19017 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19018 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19019 << Old->getReturnTypeSourceRange();
19020 return true;
19021 }
19022 }
19023
19024 // The qualifiers of the return types must be the same.
19025 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19026 Diag(Loc: New->getLocation(),
19027 DiagID: diag::err_covariant_return_type_different_qualifications)
19028 << New->getDeclName() << NewTy << OldTy
19029 << New->getReturnTypeSourceRange();
19030 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19031 << Old->getReturnTypeSourceRange();
19032 return true;
19033 }
19034
19035
19036 // The new class type must have the same or less qualifiers as the old type.
19037 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
19038 Diag(Loc: New->getLocation(),
19039 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19040 << New->getDeclName() << NewTy << OldTy
19041 << New->getReturnTypeSourceRange();
19042 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19043 << Old->getReturnTypeSourceRange();
19044 return true;
19045 }
19046
19047 return false;
19048}
19049
19050bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
19051 SourceLocation EndLoc = InitRange.getEnd();
19052 if (EndLoc.isValid())
19053 Method->setRangeEnd(EndLoc);
19054
19055 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19056 Method->setIsPureVirtual();
19057 return false;
19058 }
19059
19060 if (!Method->isInvalidDecl())
19061 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19062 << Method->getDeclName() << InitRange;
19063 return true;
19064}
19065
19066void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19067 if (D->getFriendObjectKind())
19068 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19069 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19070 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19071 else
19072 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19073}
19074
19075/// Invoked when we are about to parse an initializer for the declaration
19076/// 'Dcl'.
19077///
19078/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19079/// static data member of class X, names should be looked up in the scope of
19080/// class X. If the declaration had a scope specifier, a scope will have
19081/// been created and passed in for this purpose. Otherwise, S will be null.
19082void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19083 assert(D && !D->isInvalidDecl());
19084
19085 // We will always have a nested name specifier here, but this declaration
19086 // might not be out of line if the specifier names the current namespace:
19087 // extern int n;
19088 // int ::n = 0;
19089 if (S && D->isOutOfLine())
19090 EnterDeclaratorContext(S, DC: D->getDeclContext());
19091
19092 PushExpressionEvaluationContext(
19093 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19094 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19095}
19096
19097void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19098 assert(D);
19099
19100 if (S && D->isOutOfLine())
19101 ExitDeclaratorContext(S);
19102
19103 PopExpressionEvaluationContext();
19104}
19105
19106DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19107 // C++ 6.4p2:
19108 // The declarator shall not specify a function or an array.
19109 // The type-specifier-seq shall not contain typedef and shall not declare a
19110 // new class or enumeration.
19111 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19112 "Parser allowed 'typedef' as storage class of condition decl.");
19113
19114 Decl *Dcl = ActOnDeclarator(S, D);
19115 if (!Dcl)
19116 return true;
19117
19118 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19119 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19120 << D.getSourceRange();
19121 return true;
19122 }
19123
19124 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19125 VD->setCXXCondDecl();
19126
19127 return Dcl;
19128}
19129
19130void Sema::LoadExternalVTableUses() {
19131 if (!ExternalSource)
19132 return;
19133
19134 SmallVector<ExternalVTableUse, 4> VTables;
19135 ExternalSource->ReadUsedVTables(VTables);
19136 SmallVector<VTableUse, 4> NewUses;
19137 for (const ExternalVTableUse &VTable : VTables) {
19138 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19139 VTablesUsed.find(Val: VTable.Record);
19140 // Even if a definition wasn't required before, it may be required now.
19141 if (Pos != VTablesUsed.end()) {
19142 if (!Pos->second && VTable.DefinitionRequired)
19143 Pos->second = true;
19144 continue;
19145 }
19146
19147 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19148 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19149 }
19150
19151 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19152}
19153
19154void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19155 bool DefinitionRequired) {
19156 // Ignore any vtable uses in unevaluated operands or for classes that do
19157 // not have a vtable.
19158 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19159 CurContext->isDependentContext() || isUnevaluatedContext())
19160 return;
19161 // Do not mark as used if compiling for the device outside of the target
19162 // region.
19163 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19164 !OpenMP().isInOpenMPDeclareTargetContext() &&
19165 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19166 if (!DefinitionRequired)
19167 MarkVirtualMembersReferenced(Loc, RD: Class);
19168 return;
19169 }
19170
19171 // Try to insert this class into the map.
19172 LoadExternalVTableUses();
19173 Class = Class->getCanonicalDecl();
19174 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19175 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19176 if (!Pos.second) {
19177 // If we already had an entry, check to see if we are promoting this vtable
19178 // to require a definition. If so, we need to reappend to the VTableUses
19179 // list, since we may have already processed the first entry.
19180 if (DefinitionRequired && !Pos.first->second) {
19181 Pos.first->second = true;
19182 } else {
19183 // Otherwise, we can early exit.
19184 return;
19185 }
19186 } else {
19187 // The Microsoft ABI requires that we perform the destructor body
19188 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19189 // the deleting destructor is emitted with the vtable, not with the
19190 // destructor definition as in the Itanium ABI.
19191 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19192 CXXDestructorDecl *DD = Class->getDestructor();
19193 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19194 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19195 // If this is an out-of-line declaration, marking it referenced will
19196 // not do anything. Manually call CheckDestructor to look up operator
19197 // delete().
19198 ContextRAII SavedContext(*this, DD);
19199 CheckDestructor(Destructor: DD);
19200 if (!DD->getOperatorDelete())
19201 DD->setInvalidDecl();
19202 } else {
19203 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19204 }
19205 }
19206 }
19207 }
19208
19209 // Local classes need to have their virtual members marked
19210 // immediately. For all other classes, we mark their virtual members
19211 // at the end of the translation unit.
19212 if (Class->isLocalClass())
19213 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19214 else
19215 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19216}
19217
19218bool Sema::DefineUsedVTables() {
19219 LoadExternalVTableUses();
19220 if (VTableUses.empty())
19221 return false;
19222
19223 // Note: The VTableUses vector could grow as a result of marking
19224 // the members of a class as "used", so we check the size each
19225 // time through the loop and prefer indices (which are stable) to
19226 // iterators (which are not).
19227 bool DefinedAnything = false;
19228 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19229 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19230 if (!Class)
19231 continue;
19232 TemplateSpecializationKind ClassTSK =
19233 Class->getTemplateSpecializationKind();
19234
19235 SourceLocation Loc = VTableUses[I].second;
19236
19237 bool DefineVTable = true;
19238
19239 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19240 // V-tables for non-template classes with an owning module are always
19241 // uniquely emitted in that module.
19242 if (Class->isInCurrentModuleUnit()) {
19243 DefineVTable = true;
19244 } else if (KeyFunction && !KeyFunction->hasBody()) {
19245 // If this class has a key function, but that key function is
19246 // defined in another translation unit, we don't need to emit the
19247 // vtable even though we're using it.
19248 // The key function is in another translation unit.
19249 DefineVTable = false;
19250 TemplateSpecializationKind TSK =
19251 KeyFunction->getTemplateSpecializationKind();
19252 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19253 TSK != TSK_ImplicitInstantiation &&
19254 "Instantiations don't have key functions");
19255 (void)TSK;
19256 } else if (!KeyFunction) {
19257 // If we have a class with no key function that is the subject
19258 // of an explicit instantiation declaration, suppress the
19259 // vtable; it will live with the explicit instantiation
19260 // definition.
19261 bool IsExplicitInstantiationDeclaration =
19262 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19263 for (auto *R : Class->redecls()) {
19264 TemplateSpecializationKind TSK
19265 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19266 if (TSK == TSK_ExplicitInstantiationDeclaration)
19267 IsExplicitInstantiationDeclaration = true;
19268 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19269 IsExplicitInstantiationDeclaration = false;
19270 break;
19271 }
19272 }
19273
19274 if (IsExplicitInstantiationDeclaration) {
19275 const bool HasExcludeFromExplicitInstantiation =
19276 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19277 // If the class has a member function declared with
19278 // `__attribute__((exclude_from_explicit_instantiation))`, the
19279 // explicit instantiation declaration should not suppress emitting
19280 // the vtable, since the corresponding explicit instantiation
19281 // definition might not emit the vtable if a triggering method is
19282 // excluded.
19283 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19284 });
19285 if (!HasExcludeFromExplicitInstantiation)
19286 DefineVTable = false;
19287 }
19288 }
19289
19290 // The exception specifications for all virtual members may be needed even
19291 // if we are not providing an authoritative form of the vtable in this TU.
19292 // We may choose to emit it available_externally anyway.
19293 if (!DefineVTable) {
19294 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19295 continue;
19296 }
19297
19298 // Mark all of the virtual members of this class as referenced, so
19299 // that we can build a vtable. Then, tell the AST consumer that a
19300 // vtable for this class is required.
19301 DefinedAnything = true;
19302 MarkVirtualMembersReferenced(Loc, RD: Class);
19303 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19304 // The vtable is assumed to be emitted in an external source only for
19305 // classes attached to a named module, which is guaranteed to have an object
19306 // file. This isn't true for -fmodules-debuginfo, which still has
19307 // shouldEmitInExternalSource as true so that debug info gets supressed.
19308 if (VTablesUsed[Canonical] &&
19309 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19310 Consumer.HandleVTable(RD: Class);
19311
19312 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19313 // no key function or the key function is inlined. Don't warn in C++ ABIs
19314 // that lack key functions, since the user won't be able to make one.
19315 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19316 Class->isExternallyVisible() &&
19317 !(Class->getOwningModule() &&
19318 Class->getOwningModule()->isInterfaceOrPartition()) &&
19319 ClassTSK != TSK_ImplicitInstantiation &&
19320 ClassTSK != TSK_ExplicitInstantiationDeclaration &&
19321 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19322 const FunctionDecl *KeyFunctionDef = nullptr;
19323 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19324 KeyFunctionDef->isInlined()))
19325 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19326 }
19327 }
19328 VTableUses.clear();
19329
19330 return DefinedAnything;
19331}
19332
19333void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19334 const CXXRecordDecl *RD) {
19335 for (const auto *I : RD->methods())
19336 if (I->isVirtual() && !I->isPureVirtual())
19337 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19338}
19339
19340void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19341 const CXXRecordDecl *RD,
19342 bool ConstexprOnly) {
19343 // Mark all functions which will appear in RD's vtable as used.
19344 CXXFinalOverriderMap FinalOverriders;
19345 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19346 for (const auto &FinalOverrider : FinalOverriders) {
19347 for (const auto &OverridingMethod : FinalOverrider.second) {
19348 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19349 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19350
19351 // C++ [basic.def.odr]p2:
19352 // [...] A virtual member function is used if it is not pure. [...]
19353 if (!Overrider->isPureVirtual() &&
19354 (!ConstexprOnly || Overrider->isConstexpr()))
19355 MarkFunctionReferenced(Loc, Func: Overrider);
19356 }
19357 }
19358
19359 // Only classes that have virtual bases need a VTT.
19360 if (RD->getNumVBases() == 0)
19361 return;
19362
19363 for (const auto &I : RD->bases()) {
19364 const auto *Base = I.getType()->castAsCXXRecordDecl();
19365 if (Base->getNumVBases() == 0)
19366 continue;
19367 MarkVirtualMembersReferenced(Loc, RD: Base);
19368 }
19369}
19370
19371static
19372void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19373 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19374 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19375 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19376 Sema &S) {
19377 if (Ctor->isInvalidDecl())
19378 return;
19379
19380 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19381
19382 // Target may not be determinable yet, for instance if this is a dependent
19383 // call in an uninstantiated template.
19384 if (Target) {
19385 const FunctionDecl *FNTarget = nullptr;
19386 (void)Target->hasBody(Definition&: FNTarget);
19387 Target = const_cast<CXXConstructorDecl*>(
19388 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19389 }
19390
19391 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19392 // Avoid dereferencing a null pointer here.
19393 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19394
19395 if (!Current.insert(Ptr: Canonical).second)
19396 return;
19397
19398 // We know that beyond here, we aren't chaining into a cycle.
19399 if (!Target || !Target->isDelegatingConstructor() ||
19400 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19401 Valid.insert_range(R&: Current);
19402 Current.clear();
19403 // We've hit a cycle.
19404 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19405 Current.count(Ptr: TCanonical)) {
19406 // If we haven't diagnosed this cycle yet, do so now.
19407 if (!Invalid.count(Ptr: TCanonical)) {
19408 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19409 DiagID: diag::warn_delegating_ctor_cycle)
19410 << Ctor;
19411
19412 // Don't add a note for a function delegating directly to itself.
19413 if (TCanonical != Canonical)
19414 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19415
19416 CXXConstructorDecl *C = Target;
19417 while (C->getCanonicalDecl() != Canonical) {
19418 const FunctionDecl *FNTarget = nullptr;
19419 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19420 assert(FNTarget && "Ctor cycle through bodiless function");
19421
19422 C = const_cast<CXXConstructorDecl*>(
19423 cast<CXXConstructorDecl>(Val: FNTarget));
19424 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19425 }
19426 }
19427
19428 Invalid.insert_range(R&: Current);
19429 Current.clear();
19430 } else {
19431 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19432 }
19433}
19434
19435
19436void Sema::CheckDelegatingCtorCycles() {
19437 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19438
19439 for (DelegatingCtorDeclsType::iterator
19440 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19441 E = DelegatingCtorDecls.end();
19442 I != E; ++I)
19443 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19444
19445 for (CXXConstructorDecl *CI : Invalid)
19446 CI->setInvalidDecl();
19447}
19448
19449namespace {
19450 /// AST visitor that finds references to the 'this' expression.
19451class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19452 Sema &S;
19453
19454public:
19455 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19456
19457 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19458 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19459 << E->isImplicit();
19460 return false;
19461 }
19462};
19463}
19464
19465bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19466 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19467 if (!TSInfo)
19468 return false;
19469
19470 TypeLoc TL = TSInfo->getTypeLoc();
19471 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19472 if (!ProtoTL)
19473 return false;
19474
19475 // C++11 [expr.prim.general]p3:
19476 // [The expression this] shall not appear before the optional
19477 // cv-qualifier-seq and it shall not appear within the declaration of a
19478 // static member function (although its type and value category are defined
19479 // within a static member function as they are within a non-static member
19480 // function). [ Note: this is because declaration matching does not occur
19481 // until the complete declarator is known. - end note ]
19482 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19483 FindCXXThisExpr Finder(*this);
19484
19485 // If the return type came after the cv-qualifier-seq, check it now.
19486 if (Proto->hasTrailingReturn() &&
19487 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19488 return true;
19489
19490 // Check the exception specification.
19491 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19492 return true;
19493
19494 // Check the trailing requires clause
19495 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19496 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19497 return true;
19498
19499 return checkThisInStaticMemberFunctionAttributes(Method);
19500}
19501
19502bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19503 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19504 if (!TSInfo)
19505 return false;
19506
19507 TypeLoc TL = TSInfo->getTypeLoc();
19508 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19509 if (!ProtoTL)
19510 return false;
19511
19512 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19513 FindCXXThisExpr Finder(*this);
19514
19515 switch (Proto->getExceptionSpecType()) {
19516 case EST_Unparsed:
19517 case EST_Uninstantiated:
19518 case EST_Unevaluated:
19519 case EST_BasicNoexcept:
19520 case EST_NoThrow:
19521 case EST_DynamicNone:
19522 case EST_MSAny:
19523 case EST_None:
19524 break;
19525
19526 case EST_DependentNoexcept:
19527 case EST_NoexceptFalse:
19528 case EST_NoexceptTrue:
19529 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19530 return true;
19531 [[fallthrough]];
19532
19533 case EST_Dynamic:
19534 for (const auto &E : Proto->exceptions()) {
19535 if (!Finder.TraverseType(T: E))
19536 return true;
19537 }
19538 break;
19539 }
19540
19541 return false;
19542}
19543
19544bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19545 FindCXXThisExpr Finder(*this);
19546
19547 // Check attributes.
19548 for (const auto *A : Method->attrs()) {
19549 // FIXME: This should be emitted by tblgen.
19550 Expr *Arg = nullptr;
19551 ArrayRef<Expr *> Args;
19552 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19553 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19554 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19555 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19556 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19557 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19558 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19559 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19560 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19561 Arg = LR->getArg();
19562 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19563 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19564 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19565 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19566 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19567 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19568 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19569 Arg = AC->getSuccessValue();
19570 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19571 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19572 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19573
19574 if (Arg && !Finder.TraverseStmt(S: Arg))
19575 return true;
19576
19577 for (Expr *A : Args) {
19578 if (!Finder.TraverseStmt(S: A))
19579 return true;
19580 }
19581 }
19582
19583 return false;
19584}
19585
19586void Sema::checkExceptionSpecification(
19587 bool IsTopLevel, ExceptionSpecificationType EST,
19588 ArrayRef<ParsedType> DynamicExceptions,
19589 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19590 SmallVectorImpl<QualType> &Exceptions,
19591 FunctionProtoType::ExceptionSpecInfo &ESI) {
19592 Exceptions.clear();
19593 ESI.Type = EST;
19594 if (EST == EST_Dynamic) {
19595 Exceptions.reserve(N: DynamicExceptions.size());
19596 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19597 // FIXME: Preserve type source info.
19598 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19599
19600 if (IsTopLevel) {
19601 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19602 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19603 if (!Unexpanded.empty()) {
19604 DiagnoseUnexpandedParameterPacks(
19605 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19606 Unexpanded);
19607 continue;
19608 }
19609 }
19610
19611 // Check that the type is valid for an exception spec, and
19612 // drop it if not.
19613 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19614 Exceptions.push_back(Elt: ET);
19615 }
19616 ESI.Exceptions = Exceptions;
19617 return;
19618 }
19619
19620 if (isComputedNoexcept(ESpecType: EST)) {
19621 assert((NoexceptExpr->isTypeDependent() ||
19622 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19623 Context.BoolTy) &&
19624 "Parser should have made sure that the expression is boolean");
19625 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19626 ESI.Type = EST_BasicNoexcept;
19627 return;
19628 }
19629
19630 ESI.NoexceptExpr = NoexceptExpr;
19631 return;
19632 }
19633}
19634
19635void Sema::actOnDelayedExceptionSpecification(
19636 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19637 ArrayRef<ParsedType> DynamicExceptions,
19638 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19639 if (!D)
19640 return;
19641
19642 // Dig out the function we're referring to.
19643 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19644 D = FTD->getTemplatedDecl();
19645
19646 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19647 if (!FD)
19648 return;
19649
19650 // Check the exception specification.
19651 llvm::SmallVector<QualType, 4> Exceptions;
19652 FunctionProtoType::ExceptionSpecInfo ESI;
19653 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19654 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19655 ESI);
19656
19657 // Update the exception specification on the function type.
19658 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19659
19660 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19661 if (MD->isStatic())
19662 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19663
19664 if (MD->isVirtual()) {
19665 // Check overrides, which we previously had to delay.
19666 for (const CXXMethodDecl *O : MD->overridden_methods())
19667 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19668 }
19669 }
19670}
19671
19672/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19673///
19674MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19675 SourceLocation DeclStart, Declarator &D,
19676 Expr *BitWidth,
19677 InClassInitStyle InitStyle,
19678 AccessSpecifier AS,
19679 const ParsedAttr &MSPropertyAttr) {
19680 const IdentifierInfo *II = D.getIdentifier();
19681 if (!II) {
19682 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19683 return nullptr;
19684 }
19685 SourceLocation Loc = D.getIdentifierLoc();
19686
19687 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19688 QualType T = TInfo->getType();
19689 if (getLangOpts().CPlusPlus) {
19690 CheckExtraCXXDefaultArguments(D);
19691
19692 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19693 UPPC: UPPC_DataMemberType)) {
19694 D.setInvalidType();
19695 T = Context.IntTy;
19696 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19697 }
19698 }
19699
19700 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19701
19702 if (D.getDeclSpec().isInlineSpecified())
19703 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19704 << getLangOpts().CPlusPlus17;
19705 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19706 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19707 DiagID: diag::err_invalid_thread)
19708 << DeclSpec::getSpecifierName(S: TSCS);
19709
19710 // Check to see if this name was declared as a member previously
19711 NamedDecl *PrevDecl = nullptr;
19712 LookupResult Previous(*this, II, Loc, LookupMemberName,
19713 RedeclarationKind::ForVisibleRedeclaration);
19714 LookupName(R&: Previous, S);
19715 switch (Previous.getResultKind()) {
19716 case LookupResultKind::Found:
19717 case LookupResultKind::FoundUnresolvedValue:
19718 PrevDecl = Previous.getAsSingle<NamedDecl>();
19719 break;
19720
19721 case LookupResultKind::FoundOverloaded:
19722 PrevDecl = Previous.getRepresentativeDecl();
19723 break;
19724
19725 case LookupResultKind::NotFound:
19726 case LookupResultKind::NotFoundInCurrentInstantiation:
19727 case LookupResultKind::Ambiguous:
19728 break;
19729 }
19730
19731 if (PrevDecl && PrevDecl->isTemplateParameter()) {
19732 // Maybe we will complain about the shadowed template parameter.
19733 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
19734 // Just pretend that we didn't see the previous declaration.
19735 PrevDecl = nullptr;
19736 }
19737
19738 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
19739 PrevDecl = nullptr;
19740
19741 SourceLocation TSSL = D.getBeginLoc();
19742 MSPropertyDecl *NewPD =
19743 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
19744 Getter: MSPropertyAttr.getPropertyDataGetter(),
19745 Setter: MSPropertyAttr.getPropertyDataSetter());
19746 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
19747 NewPD->setAccess(AS);
19748
19749 if (NewPD->isInvalidDecl())
19750 Record->setInvalidDecl();
19751
19752 if (D.getDeclSpec().isModulePrivateSpecified())
19753 NewPD->setModulePrivate();
19754
19755 if (NewPD->isInvalidDecl() && PrevDecl) {
19756 // Don't introduce NewFD into scope; there's already something
19757 // with the same name in the same scope.
19758 } else if (II) {
19759 PushOnScopeChains(D: NewPD, S);
19760 } else
19761 Record->addDecl(D: NewPD);
19762
19763 return NewPD;
19764}
19765
19766void Sema::ActOnStartFunctionDeclarationDeclarator(
19767 Declarator &Declarator, unsigned TemplateParameterDepth) {
19768 auto &Info = InventedParameterInfos.emplace_back();
19769 TemplateParameterList *ExplicitParams = nullptr;
19770 ArrayRef<TemplateParameterList *> ExplicitLists =
19771 Declarator.getTemplateParameterLists();
19772 if (!ExplicitLists.empty()) {
19773 bool IsMemberSpecialization, IsInvalid;
19774 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
19775 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
19776 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
19777 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
19778 /*SuppressDiagnostic=*/true);
19779 }
19780 // C++23 [dcl.fct]p23:
19781 // An abbreviated function template can have a template-head. The invented
19782 // template-parameters are appended to the template-parameter-list after
19783 // the explicitly declared template-parameters.
19784 //
19785 // A template-head must have one or more template-parameters (read:
19786 // 'template<>' is *not* a template-head). Only append the invented
19787 // template parameters if we matched the nested-name-specifier to a non-empty
19788 // TemplateParameterList.
19789 if (ExplicitParams && !ExplicitParams->empty()) {
19790 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
19791 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
19792 Info.NumExplicitTemplateParams = ExplicitParams->size();
19793 } else {
19794 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
19795 Info.NumExplicitTemplateParams = 0;
19796 }
19797}
19798
19799void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
19800 auto &FSI = InventedParameterInfos.back();
19801 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
19802 if (FSI.NumExplicitTemplateParams != 0) {
19803 TemplateParameterList *ExplicitParams =
19804 Declarator.getTemplateParameterLists().back();
19805 Declarator.setInventedTemplateParameterList(
19806 TemplateParameterList::Create(
19807 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
19808 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
19809 RAngleLoc: ExplicitParams->getRAngleLoc(),
19810 RequiresClause: ExplicitParams->getRequiresClause()));
19811 } else {
19812 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
19813 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
19814 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
19815 /*RequiresClause=*/nullptr));
19816 }
19817 }
19818 InventedParameterInfos.pop_back();
19819}
19820