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 // C++11 [dcl.fct.default]p3
363 // A default argument expression [...] shall not be specified for a
364 // parameter pack.
365 //
366 // Check this before looking for unexpanded parameter packs in DefaultArg:
367 // if DefaultArg references a pack from an enclosing lambda/block, that
368 // check would (incorrectly) mark the lambda as containing an unexpanded
369 // pack that never actually appears in the final AST once we discard
370 // DefaultArg below.
371 if (Param->isParameterPack()) {
372 Diag(Loc: EqualLoc, DiagID: diag::err_param_default_argument_on_parameter_pack)
373 << DefaultArg->getSourceRange();
374 // Recover by discarding the default argument.
375 Param->setDefaultArg(nullptr);
376 return;
377 }
378
379 // Check for unexpanded parameter packs.
380 if (DiagnoseUnexpandedParameterPack(E: DefaultArg, UPPC: UPPC_DefaultArgument))
381 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
382
383 ExprResult Result = ConvertParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
384 if (Result.isInvalid())
385 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
386
387 DefaultArg = Result.getAs<Expr>();
388
389 // Check that the default argument is well-formed
390 CheckDefaultArgumentVisitor DefaultArgChecker(*this, DefaultArg);
391 if (DefaultArgChecker.Visit(S: DefaultArg))
392 return ActOnParamDefaultArgumentError(param, EqualLoc, DefaultArg);
393
394 SetParamDefaultArgument(Param, Arg: DefaultArg, EqualLoc);
395}
396
397void Sema::ActOnParamUnparsedDefaultArgument(Decl *param,
398 SourceLocation EqualLoc,
399 SourceLocation ArgLoc) {
400 if (!param)
401 return;
402
403 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
404 Param->setUnparsedDefaultArg();
405 UnparsedDefaultArgLocs[Param] = ArgLoc;
406}
407
408void Sema::ActOnParamDefaultArgumentError(Decl *param, SourceLocation EqualLoc,
409 Expr *DefaultArg) {
410 if (!param)
411 return;
412
413 ParmVarDecl *Param = cast<ParmVarDecl>(Val: param);
414 Param->setInvalidDecl();
415 UnparsedDefaultArgLocs.erase(Val: Param);
416 ExprResult RE;
417 if (DefaultArg) {
418 RE = CreateRecoveryExpr(Begin: EqualLoc, End: DefaultArg->getEndLoc(), SubExprs: {DefaultArg},
419 T: Param->getType().getNonReferenceType());
420 } else {
421 RE = CreateRecoveryExpr(Begin: EqualLoc, End: EqualLoc, SubExprs: {},
422 T: Param->getType().getNonReferenceType());
423 }
424 Param->setDefaultArg(RE.get());
425}
426
427void Sema::CheckExtraCXXDefaultArguments(Declarator &D) {
428 // C++ [dcl.fct.default]p3
429 // A default argument expression shall be specified only in the
430 // parameter-declaration-clause of a function declaration or in a
431 // template-parameter (14.1). It shall not be specified for a
432 // parameter pack. If it is specified in a
433 // parameter-declaration-clause, it shall not occur within a
434 // declarator or abstract-declarator of a parameter-declaration.
435 bool MightBeFunction = D.isFunctionDeclarationContext();
436 for (unsigned i = 0, e = D.getNumTypeObjects(); i != e; ++i) {
437 DeclaratorChunk &chunk = D.getTypeObject(i);
438 if (chunk.Kind == DeclaratorChunk::Function) {
439 if (MightBeFunction) {
440 // This is a function declaration. It can have default arguments, but
441 // keep looking in case its return type is a function type with default
442 // arguments.
443 MightBeFunction = false;
444 continue;
445 }
446 for (unsigned argIdx = 0, e = chunk.Fun.NumParams; argIdx != e;
447 ++argIdx) {
448 ParmVarDecl *Param = cast<ParmVarDecl>(Val: chunk.Fun.Params[argIdx].Param);
449 if (Param->hasUnparsedDefaultArg()) {
450 std::unique_ptr<CachedTokens> Toks =
451 std::move(chunk.Fun.Params[argIdx].DefaultArgTokens);
452 SourceRange SR;
453 if (Toks->size() > 1)
454 SR = SourceRange((*Toks)[1].getLocation(),
455 Toks->back().getLocation());
456 else
457 SR = UnparsedDefaultArgLocs[Param];
458 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
459 << SR;
460 } else if (Param->getDefaultArg()) {
461 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_nonfunc)
462 << Param->getDefaultArg()->getSourceRange();
463 Param->setDefaultArg(nullptr);
464 }
465 }
466 } else if (chunk.Kind != DeclaratorChunk::Paren) {
467 MightBeFunction = false;
468 }
469 }
470}
471
472static bool functionDeclHasDefaultArgument(const FunctionDecl *FD) {
473 return llvm::any_of(Range: FD->parameters(), P: [](ParmVarDecl *P) {
474 return P->hasDefaultArg() && !P->hasInheritedDefaultArg();
475 });
476}
477
478bool Sema::MergeCXXFunctionDecl(FunctionDecl *New, FunctionDecl *Old,
479 Scope *S) {
480 bool Invalid = false;
481
482 // The declaration context corresponding to the scope is the semantic
483 // parent, unless this is a local function declaration, in which case
484 // it is that surrounding function.
485 DeclContext *ScopeDC = New->isLocalExternDecl()
486 ? New->getLexicalDeclContext()
487 : New->getDeclContext();
488
489 // Find the previous declaration for the purpose of default arguments.
490 FunctionDecl *PrevForDefaultArgs = Old;
491 for (/**/; PrevForDefaultArgs;
492 // Don't bother looking back past the latest decl if this is a local
493 // extern declaration; nothing else could work.
494 PrevForDefaultArgs = New->isLocalExternDecl()
495 ? nullptr
496 : PrevForDefaultArgs->getPreviousDecl()) {
497 // Ignore hidden declarations.
498 if (!LookupResult::isVisible(SemaRef&: *this, D: PrevForDefaultArgs))
499 continue;
500
501 if (S && !isDeclInScope(D: PrevForDefaultArgs, Ctx: ScopeDC, S) &&
502 !New->isCXXClassMember()) {
503 // Ignore default arguments of old decl if they are not in
504 // the same scope and this is not an out-of-line definition of
505 // a member function.
506 continue;
507 }
508
509 if (PrevForDefaultArgs->isLocalExternDecl() != New->isLocalExternDecl()) {
510 // If only one of these is a local function declaration, then they are
511 // declared in different scopes, even though isDeclInScope may think
512 // they're in the same scope. (If both are local, the scope check is
513 // sufficient, and if neither is local, then they are in the same scope.)
514 continue;
515 }
516
517 if (PrevForDefaultArgs->getFriendObjectKind()) {
518 // Don't inherit default arguments from a friend declaration. It's invalid
519 // to redeclare such a function at all if it owns the default arguments;
520 // we check for that later. Otherwise, it's not the declaration that we're
521 // inheriting them from.
522 continue;
523 }
524
525 // We found the right previous declaration.
526 break;
527 }
528
529 // C++ [dcl.fct.default]p4:
530 // For non-template functions, default arguments can be added in
531 // later declarations of a function in the same
532 // scope. Declarations in different scopes have completely
533 // distinct sets of default arguments. That is, declarations in
534 // inner scopes do not acquire default arguments from
535 // declarations in outer scopes, and vice versa. In a given
536 // function declaration, all parameters subsequent to a
537 // parameter with a default argument shall have default
538 // arguments supplied in this or previous declarations. A
539 // default argument shall not be redefined by a later
540 // declaration (not even to the same value).
541 //
542 // C++ [dcl.fct.default]p6:
543 // Except for member functions of class templates, the default arguments
544 // in a member function definition that appears outside of the class
545 // definition are added to the set of default arguments provided by the
546 // member function declaration in the class definition.
547 for (unsigned p = 0, NumParams = PrevForDefaultArgs
548 ? PrevForDefaultArgs->getNumParams()
549 : 0;
550 p < NumParams; ++p) {
551 ParmVarDecl *OldParam = PrevForDefaultArgs->getParamDecl(i: p);
552 ParmVarDecl *NewParam = New->getParamDecl(i: p);
553
554 bool OldParamHasDfl = OldParam ? OldParam->hasDefaultArg() : false;
555 bool NewParamHasDfl = NewParam->hasDefaultArg();
556
557 if (OldParamHasDfl && NewParamHasDfl) {
558 unsigned DiagDefaultParamID =
559 diag::err_param_default_argument_redefinition;
560
561 // MSVC accepts that default parameters be redefined for member functions
562 // of template class. The new default parameter's value is ignored.
563 Invalid = true;
564 if (getLangOpts().MicrosoftExt) {
565 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: New);
566 if (MD && MD->getParent()->getDescribedClassTemplate()) {
567 // Merge the old default argument into the new parameter.
568 NewParam->setHasInheritedDefaultArg();
569 if (OldParam->hasUninstantiatedDefaultArg())
570 NewParam->setUninstantiatedDefaultArg(
571 OldParam->getUninstantiatedDefaultArg());
572 else
573 NewParam->setDefaultArg(OldParam->getInit());
574 DiagDefaultParamID = diag::ext_param_default_argument_redefinition;
575 Invalid = false;
576 }
577 }
578
579 // FIXME: If we knew where the '=' was, we could easily provide a fix-it
580 // hint here. Alternatively, we could walk the type-source information
581 // for NewParam to find the last source location in the type... but it
582 // isn't worth the effort right now. This is the kind of test case that
583 // is hard to get right:
584 // int f(int);
585 // void g(int (*fp)(int) = f);
586 // void g(int (*fp)(int) = &f);
587 Diag(Loc: NewParam->getLocation(), DiagID: DiagDefaultParamID)
588 << NewParam->getDefaultArgRange();
589
590 // Look for the function declaration where the default argument was
591 // actually written, which may be a declaration prior to Old.
592 for (auto Older = PrevForDefaultArgs;
593 OldParam->hasInheritedDefaultArg(); /**/) {
594 Older = Older->getPreviousDecl();
595 OldParam = Older->getParamDecl(i: p);
596 }
597
598 Diag(Loc: OldParam->getLocation(), DiagID: diag::note_previous_definition)
599 << OldParam->getDefaultArgRange();
600 } else if (OldParamHasDfl) {
601 // Merge the old default argument into the new parameter unless the new
602 // function is a friend declaration in a template class. In the latter
603 // case the default arguments will be inherited when the friend
604 // declaration will be instantiated.
605 if (New->getFriendObjectKind() == Decl::FOK_None ||
606 !New->getLexicalDeclContext()->isDependentContext()) {
607 // It's important to use getInit() here; getDefaultArg()
608 // strips off any top-level ExprWithCleanups.
609 NewParam->setHasInheritedDefaultArg();
610 if (OldParam->hasUnparsedDefaultArg())
611 NewParam->setUnparsedDefaultArg();
612 else if (OldParam->hasUninstantiatedDefaultArg())
613 NewParam->setUninstantiatedDefaultArg(
614 OldParam->getUninstantiatedDefaultArg());
615 else
616 NewParam->setDefaultArg(OldParam->getInit());
617 }
618 } else if (NewParamHasDfl) {
619 if (New->getDescribedFunctionTemplate()) {
620 // Paragraph 4, quoted above, only applies to non-template functions.
621 Diag(Loc: NewParam->getLocation(),
622 DiagID: diag::err_param_default_argument_template_redecl)
623 << NewParam->getDefaultArgRange();
624 Diag(Loc: PrevForDefaultArgs->getLocation(),
625 DiagID: diag::note_template_prev_declaration)
626 << false;
627 } else if (New->getTemplateSpecializationKind()
628 != TSK_ImplicitInstantiation &&
629 New->getTemplateSpecializationKind() != TSK_Undeclared) {
630 // C++ [temp.expr.spec]p21:
631 // Default function arguments shall not be specified in a declaration
632 // or a definition for one of the following explicit specializations:
633 // - the explicit specialization of a function template;
634 // - the explicit specialization of a member function template;
635 // - the explicit specialization of a member function of a class
636 // template where the class template specialization to which the
637 // member function specialization belongs is implicitly
638 // instantiated.
639 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_template_spec_default_arg)
640 << (New->getTemplateSpecializationKind() ==TSK_ExplicitSpecialization)
641 << New->getDeclName()
642 << NewParam->getDefaultArgRange();
643 } else if (New->getDeclContext()
644 ->getEnclosingNonExpansionStatementContext()
645 ->isDependentContext()) {
646 // C++ [dcl.fct.default]p6 (DR217):
647 // Default arguments for a member function of a class template shall
648 // be specified on the initial declaration of the member function
649 // within the class template.
650 //
651 // Reading the tea leaves a bit in DR217 and its reference to DR205
652 // leads me to the conclusion that one cannot add default function
653 // arguments for an out-of-line definition of a member function of a
654 // dependent type.
655 int WhichKind = 2;
656 if (CXXRecordDecl *Record
657 = dyn_cast<CXXRecordDecl>(Val: New->getDeclContext())) {
658 if (Record->getDescribedClassTemplate())
659 WhichKind = 0;
660 else if (isa<ClassTemplatePartialSpecializationDecl>(Val: Record))
661 WhichKind = 1;
662 else
663 WhichKind = 2;
664 }
665
666 Diag(Loc: NewParam->getLocation(),
667 DiagID: diag::err_param_default_argument_member_template_redecl)
668 << WhichKind
669 << NewParam->getDefaultArgRange();
670 }
671 }
672 }
673
674 // DR1344: If a default argument is added outside a class definition and that
675 // default argument makes the function a special member function, the program
676 // is ill-formed. This can only happen for constructors.
677 if (isa<CXXConstructorDecl>(Val: New) &&
678 New->getMinRequiredArguments() < Old->getMinRequiredArguments()) {
679 CXXSpecialMemberKind NewSM =
680 cast<CXXMethodDecl>(Val: New)->getSpecialMemberKind(),
681 OldSM =
682 cast<CXXMethodDecl>(Val: Old)->getSpecialMemberKind();
683 if (NewSM != OldSM) {
684 auto It = llvm::find_if(Range: New->parameters(), P: [](const ParmVarDecl *P) {
685 return P->hasDefaultArg();
686 });
687 assert(It != New->param_end());
688 ParmVarDecl *NewParam = *It;
689 Diag(Loc: NewParam->getLocation(), DiagID: diag::err_default_arg_makes_ctor_special)
690 << NewParam->getDefaultArgRange() << NewSM;
691 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
692 }
693 }
694
695 const FunctionDecl *Def;
696 // C++11 [dcl.constexpr]p1: If any declaration of a function or function
697 // template has a constexpr specifier then all its declarations shall
698 // contain the constexpr specifier.
699 if (New->getConstexprKind() != Old->getConstexprKind()) {
700 Diag(Loc: New->getLocation(), DiagID: diag::err_constexpr_redecl_mismatch)
701 << New << static_cast<int>(New->getConstexprKind())
702 << static_cast<int>(Old->getConstexprKind());
703 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
704 Invalid = true;
705 } else if (!Old->getMostRecentDecl()->isInlined() && New->isInlined() &&
706 Old->isDefined(Definition&: Def) &&
707 // If a friend function is inlined but does not have 'inline'
708 // specifier, it is a definition. Do not report attribute conflict
709 // in this case, redefinition will be diagnosed later.
710 (New->isInlineSpecified() ||
711 New->getFriendObjectKind() == Decl::FOK_None)) {
712 // C++11 [dcl.fcn.spec]p4:
713 // If the definition of a function appears in a translation unit before its
714 // first declaration as inline, the program is ill-formed.
715 Diag(Loc: New->getLocation(), DiagID: diag::err_inline_decl_follows_def) << New;
716 Diag(Loc: Def->getLocation(), DiagID: diag::note_previous_definition);
717 Invalid = true;
718 }
719
720 // C++17 [temp.deduct.guide]p3:
721 // Two deduction guide declarations in the same translation unit
722 // for the same class template shall not have equivalent
723 // parameter-declaration-clauses.
724 if (isa<CXXDeductionGuideDecl>(Val: New) &&
725 !New->isFunctionTemplateSpecialization() && isVisible(D: Old)) {
726 Diag(Loc: New->getLocation(), DiagID: diag::err_deduction_guide_redeclared);
727 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
728 }
729
730 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a default
731 // argument expression, that declaration shall be a definition and shall be
732 // the only declaration of the function or function template in the
733 // translation unit.
734 if (Old->getFriendObjectKind() == Decl::FOK_Undeclared &&
735 functionDeclHasDefaultArgument(FD: Old)) {
736 Diag(Loc: New->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
737 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
738 Invalid = true;
739 }
740
741 // C++11 [temp.friend]p4 (DR329):
742 // When a function is defined in a friend function declaration in a class
743 // template, the function is instantiated when the function is odr-used.
744 // The same restrictions on multiple declarations and definitions that
745 // apply to non-template function declarations and definitions also apply
746 // to these implicit definitions.
747 const FunctionDecl *OldDefinition = nullptr;
748 if (New->isThisDeclarationInstantiatedFromAFriendDefinition() &&
749 Old->isDefined(Definition&: OldDefinition, CheckForPendingFriendDefinition: true))
750 CheckForFunctionRedefinition(FD: New, EffectiveDefinition: OldDefinition);
751
752 return Invalid;
753}
754
755void Sema::DiagPlaceholderVariableDefinition(SourceLocation Loc) {
756 DiagCompat(Loc, CompatDiagId: diag_compat::placeholder_var_definition);
757}
758
759NamedDecl *
760Sema::ActOnDecompositionDeclarator(Scope *S, Declarator &D,
761 MultiTemplateParamsArg TemplateParamLists) {
762 assert(D.isDecompositionDeclarator());
763 const DecompositionDeclarator &Decomp = D.getDecompositionDeclarator();
764
765 // The syntax only allows a decomposition declarator as a simple-declaration,
766 // a for-range-declaration, or a condition in Clang, but we parse it in more
767 // cases than that.
768 if (!D.mayHaveDecompositionDeclarator()) {
769 Diag(Loc: Decomp.getLSquareLoc(), DiagID: diag::err_decomp_decl_context)
770 << Decomp.getSourceRange();
771 return nullptr;
772 }
773
774 if (!TemplateParamLists.empty()) {
775 // C++17 [temp]/1:
776 // A template defines a family of class, functions, or variables, or an
777 // alias for a family of types.
778 //
779 // Structured bindings are not included.
780 Diag(Loc: TemplateParamLists.front()->getTemplateLoc(),
781 DiagID: diag::err_decomp_decl_template);
782 return nullptr;
783 }
784
785 unsigned DiagID;
786 if (!getLangOpts().CPlusPlus17)
787 DiagID = diag::compat_pre_cxx17_decomp_decl;
788 else if (D.getContext() == DeclaratorContext::Condition)
789 DiagID = getLangOpts().CPlusPlus26
790 ? diag::compat_cxx26_decomp_decl_cond
791 : diag::compat_pre_cxx26_decomp_decl_cond;
792 else
793 DiagID = diag::compat_cxx17_decomp_decl;
794
795 Diag(Loc: Decomp.getLSquareLoc(), DiagID) << Decomp.getSourceRange();
796
797 // The semantic context is always just the current context.
798 DeclContext *const DC = CurContext;
799
800 // C++17 [dcl.dcl]/8:
801 // The decl-specifier-seq shall contain only the type-specifier auto
802 // and cv-qualifiers.
803 // C++20 [dcl.dcl]/8:
804 // If decl-specifier-seq contains any decl-specifier other than static,
805 // thread_local, auto, or cv-qualifiers, the program is ill-formed.
806 // C++23 [dcl.pre]/6:
807 // Each decl-specifier in the decl-specifier-seq shall be static,
808 // thread_local, auto (9.2.9.6 [dcl.spec.auto]), or a cv-qualifier.
809 // C++23 [dcl.pre]/7:
810 // Each decl-specifier in the decl-specifier-seq shall be constexpr,
811 // constinit, static, thread_local, auto, or a cv-qualifier
812 auto &DS = D.getDeclSpec();
813 auto DiagBadSpecifier = [&](StringRef Name, SourceLocation Loc) {
814 Diag(Loc, DiagID: diag::err_decomp_decl_spec) << Name;
815 };
816
817 auto DiagCpp20Specifier = [&](StringRef Name, SourceLocation Loc) {
818 DiagCompat(Loc, CompatDiagId: diag_compat::decomp_decl_spec) << Name;
819 };
820
821 if (auto SCS = DS.getStorageClassSpec()) {
822 if (SCS == DeclSpec::SCS_static)
823 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: SCS),
824 DS.getStorageClassSpecLoc());
825 else
826 DiagBadSpecifier(DeclSpec::getSpecifierName(S: SCS),
827 DS.getStorageClassSpecLoc());
828 }
829 if (auto TSCS = DS.getThreadStorageClassSpec())
830 DiagCpp20Specifier(DeclSpec::getSpecifierName(S: TSCS),
831 DS.getThreadStorageClassSpecLoc());
832
833 if (DS.isInlineSpecified())
834 DiagBadSpecifier("inline", DS.getInlineSpecLoc());
835
836 if (ConstexprSpecKind ConstexprSpec = DS.getConstexprSpecifier();
837 ConstexprSpec != ConstexprSpecKind::Unspecified) {
838 if (ConstexprSpec == ConstexprSpecKind::Consteval ||
839 !getLangOpts().CPlusPlus26)
840 DiagBadSpecifier(DeclSpec::getSpecifierName(C: ConstexprSpec),
841 DS.getConstexprSpecLoc());
842 }
843
844 // We can't recover from it being declared as a typedef.
845 if (DS.getStorageClassSpec() == DeclSpec::SCS_typedef)
846 return nullptr;
847
848 // C++2a [dcl.struct.bind]p1:
849 // A cv that includes volatile is deprecated
850 if ((DS.getTypeQualifiers() & DeclSpec::TQ_volatile) &&
851 getLangOpts().CPlusPlus20)
852 Diag(Loc: DS.getVolatileSpecLoc(),
853 DiagID: diag::warn_deprecated_volatile_structured_binding);
854
855 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
856 QualType R = TInfo->getType();
857
858 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
859 UPPC: UPPC_DeclarationType))
860 D.setInvalidType();
861
862 // The syntax only allows a single ref-qualifier prior to the decomposition
863 // declarator. No other declarator chunks are permitted. Also check the type
864 // specifier here.
865 if (DS.getTypeSpecType() != DeclSpec::TST_auto ||
866 D.hasGroupingParens() || D.getNumTypeObjects() > 1 ||
867 (D.getNumTypeObjects() == 1 &&
868 D.getTypeObject(i: 0).Kind != DeclaratorChunk::Reference)) {
869 Diag(Loc: Decomp.getLSquareLoc(),
870 DiagID: (D.hasGroupingParens() ||
871 (D.getNumTypeObjects() &&
872 D.getTypeObject(i: 0).Kind == DeclaratorChunk::Paren))
873 ? diag::err_decomp_decl_parens
874 : diag::err_decomp_decl_type)
875 << R;
876
877 // In most cases, there's no actual problem with an explicitly-specified
878 // type, but a function type won't work here, and ActOnVariableDeclarator
879 // shouldn't be called for such a type.
880 if (R->isFunctionType())
881 D.setInvalidType();
882 }
883
884 // Constrained auto is prohibited by [decl.pre]p6, so check that here.
885 if (DS.isConstrainedAuto()) {
886 TemplateIdAnnotation *TemplRep = DS.getRepAsTemplateId();
887 assert(TemplRep->Kind == TNK_Concept_template &&
888 "No other template kind should be possible for a constrained auto");
889
890 SourceRange TemplRange{TemplRep->TemplateNameLoc,
891 TemplRep->RAngleLoc.isValid()
892 ? TemplRep->RAngleLoc
893 : TemplRep->TemplateNameLoc};
894 Diag(Loc: TemplRep->TemplateNameLoc, DiagID: diag::err_decomp_decl_constraint)
895 << TemplRange << FixItHint::CreateRemoval(RemoveRange: TemplRange);
896 }
897
898 // Build the BindingDecls.
899 SmallVector<BindingDecl*, 8> Bindings;
900
901 // Build the BindingDecls.
902 for (auto &B : D.getDecompositionDeclarator().bindings()) {
903 // Check for name conflicts.
904 DeclarationNameInfo NameInfo(B.Name, B.NameLoc);
905 IdentifierInfo *VarName = B.Name;
906 assert(VarName && "Cannot have an unnamed binding declaration");
907
908 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
909 RedeclarationKind::ForVisibleRedeclaration);
910 LookupName(R&: Previous, S,
911 /*CreateBuiltins*/AllowBuiltinCreation: DC->getRedeclContext()->isTranslationUnit());
912
913 // It's not permitted to shadow a template parameter name.
914 if (Previous.isSingleResult() &&
915 Previous.getFoundDecl()->isTemplateParameter()) {
916 DiagnoseTemplateParameterShadow(Loc: B.NameLoc, PrevDecl: Previous.getFoundDecl());
917 Previous.clear();
918 }
919
920 QualType QT;
921 if (B.EllipsisLoc.isValid()) {
922 if (!cast<Decl>(Val: DC)->isTemplated())
923 Diag(Loc: B.EllipsisLoc, DiagID: diag::err_pack_outside_template);
924 QT = Context.getPackExpansionType(Pattern: Context.DependentTy, NumExpansions: std::nullopt,
925 /*ExpectsPackInType=*/ExpectPackInType: false);
926 }
927
928 auto *BD = BindingDecl::Create(C&: Context, DC, IdLoc: B.NameLoc, Id: B.Name, T: QT);
929
930 if (BD->isParameterPack()) {
931 if (sema::CapturingScopeInfo *CSI = getEnclosingLambdaOrBlock())
932 CSI->LocalPacks.push_back(Elt: BD);
933 }
934
935 ProcessDeclAttributeList(S, D: BD, AttrList: *B.Attrs);
936
937 // Find the shadowed declaration before filtering for scope.
938 NamedDecl *ShadowedDecl = D.getCXXScopeSpec().isEmpty()
939 ? getShadowedDeclaration(D: BD, R: Previous)
940 : nullptr;
941
942 bool ConsiderLinkage = DC->isFunctionOrMethod() &&
943 DS.getStorageClassSpec() == DeclSpec::SCS_extern;
944 FilterLookupForScope(R&: Previous, Ctx: DC, S, ConsiderLinkage,
945 /*AllowInlineNamespace*/false);
946
947 bool IsPlaceholder = DS.getStorageClassSpec() != DeclSpec::SCS_static &&
948 DC->isFunctionOrMethod() && VarName->isPlaceholder();
949 if (!Previous.empty()) {
950 if (IsPlaceholder) {
951 bool sameDC = (Previous.end() - 1)
952 ->getDeclContext()
953 ->getRedeclContext()
954 ->Equals(DC: DC->getRedeclContext());
955 if (sameDC &&
956 isDeclInScope(D: *(Previous.end() - 1), Ctx: CurContext, S, AllowInlineNamespace: false)) {
957 Previous.clear();
958 DiagPlaceholderVariableDefinition(Loc: B.NameLoc);
959 }
960 } else {
961 auto *Old = Previous.getRepresentativeDecl();
962 Diag(Loc: B.NameLoc, DiagID: diag::err_redefinition) << B.Name;
963 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_definition);
964 }
965 } else if (ShadowedDecl && !D.isRedeclaration()) {
966 CheckShadow(D: BD, ShadowedDecl, R: Previous);
967 }
968 PushOnScopeChains(D: BD, S, AddToContext: true);
969 Bindings.push_back(Elt: BD);
970 ParsingInitForAutoVars.insert(Ptr: BD);
971 }
972
973 // There are no prior lookup results for the variable itself, because it
974 // is unnamed.
975 DeclarationNameInfo NameInfo((IdentifierInfo *)nullptr,
976 Decomp.getLSquareLoc());
977 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
978 RedeclarationKind::ForVisibleRedeclaration);
979
980 // Build the variable that holds the non-decomposed object.
981 bool AddToScope = true;
982 NamedDecl *New =
983 ActOnVariableDeclarator(S, D, DC, TInfo, Previous,
984 TemplateParamLists: MultiTemplateParamsArg(), AddToScope, Bindings);
985 if (AddToScope) {
986 S->AddDecl(D: New);
987 CurContext->addHiddenDecl(D: New);
988 }
989
990 if (OpenMP().isInOpenMPDeclareTargetContext())
991 OpenMP().checkDeclIsAllowedInOpenMPTarget(E: nullptr, D: New);
992
993 return New;
994}
995
996// Check the arity of the structured bindings.
997// Create the resolved pack expr if needed.
998static bool CheckBindingsCount(Sema &S, DecompositionDecl *DD,
999 QualType DecompType,
1000 ArrayRef<BindingDecl *> Bindings,
1001 unsigned MemberCount) {
1002 auto BindingWithPackItr = llvm::find_if(
1003 Range&: Bindings, P: [](BindingDecl *D) -> bool { return D->isParameterPack(); });
1004 bool HasPack = BindingWithPackItr != Bindings.end();
1005 bool IsValid;
1006 if (!HasPack) {
1007 IsValid = Bindings.size() == MemberCount;
1008 } else {
1009 // There may not be more members than non-pack bindings.
1010 IsValid = MemberCount >= Bindings.size() - 1;
1011 }
1012
1013 if (IsValid && HasPack) {
1014 // Create the pack expr and assign it to the binding.
1015 unsigned PackSize = MemberCount - Bindings.size() + 1;
1016
1017 BindingDecl *BPack = *BindingWithPackItr;
1018 BPack->setDecomposedDecl(DD);
1019 SmallVector<ValueDecl *, 8> NestedBDs(PackSize);
1020 // Create the nested BindingDecls.
1021 for (unsigned I = 0; I < PackSize; ++I) {
1022 BindingDecl *NestedBD = BindingDecl::Create(
1023 C&: S.Context, DC: BPack->getDeclContext(), IdLoc: BPack->getLocation(),
1024 Id: BPack->getIdentifier(), T: QualType());
1025 NestedBD->setDecomposedDecl(DD);
1026 NestedBDs[I] = NestedBD;
1027 }
1028
1029 QualType PackType = S.Context.getPackExpansionType(
1030 Pattern: S.Context.DependentTy, NumExpansions: PackSize, /*ExpectsPackInType=*/ExpectPackInType: false);
1031 auto *PackExpr = FunctionParmPackExpr::Create(
1032 Context: S.Context, T: PackType, ParamPack: BPack, NameLoc: BPack->getBeginLoc(), Params: NestedBDs);
1033 BPack->setBinding(DeclaredType: PackType, Binding: PackExpr);
1034 }
1035
1036 if (IsValid)
1037 return false;
1038
1039 S.Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_wrong_number_bindings)
1040 << DecompType << (unsigned)Bindings.size() << MemberCount << MemberCount
1041 << (MemberCount < Bindings.size());
1042 return true;
1043}
1044
1045static bool checkSimpleDecomposition(
1046 Sema &S, ArrayRef<BindingDecl *> Bindings, ValueDecl *Src,
1047 QualType DecompType, const llvm::APSInt &NumElemsAPS, QualType ElemType,
1048 llvm::function_ref<ExprResult(SourceLocation, Expr *, unsigned)> GetInit) {
1049 unsigned NumElems = (unsigned)NumElemsAPS.getLimitedValue(UINT_MAX);
1050 auto *DD = cast<DecompositionDecl>(Val: Src);
1051
1052 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1053 return true;
1054
1055 unsigned I = 0;
1056 for (auto *B : DD->flat_bindings()) {
1057 SourceLocation Loc = B->getLocation();
1058 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1059 if (E.isInvalid())
1060 return true;
1061 E = GetInit(Loc, E.get(), I++);
1062 if (E.isInvalid())
1063 return true;
1064 B->setBinding(DeclaredType: ElemType, Binding: E.get());
1065 }
1066
1067 return false;
1068}
1069
1070static bool checkArrayLikeDecomposition(Sema &S,
1071 ArrayRef<BindingDecl *> Bindings,
1072 ValueDecl *Src, QualType DecompType,
1073 const llvm::APSInt &NumElems,
1074 QualType ElemType) {
1075 return checkSimpleDecomposition(
1076 S, Bindings, Src, DecompType, NumElemsAPS: NumElems, ElemType,
1077 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1078 ExprResult E = S.ActOnIntegerConstant(Loc, Val: I);
1079 if (E.isInvalid())
1080 return ExprError();
1081 return S.CreateBuiltinArraySubscriptExpr(Base, LLoc: Loc, Idx: E.get(), RLoc: Loc);
1082 });
1083}
1084
1085static bool checkArrayDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1086 ValueDecl *Src, QualType DecompType,
1087 const ConstantArrayType *CAT) {
1088 return checkArrayLikeDecomposition(S, Bindings, Src, DecompType,
1089 NumElems: llvm::APSInt(CAT->getSize()),
1090 ElemType: CAT->getElementType());
1091}
1092
1093static bool checkVectorDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1094 ValueDecl *Src, QualType DecompType,
1095 const VectorType *VT) {
1096 return checkArrayLikeDecomposition(
1097 S, Bindings, Src, DecompType, NumElems: llvm::APSInt::get(X: VT->getNumElements()),
1098 ElemType: S.Context.getQualifiedType(T: VT->getElementType(),
1099 Qs: DecompType.getQualifiers()));
1100}
1101
1102static bool checkComplexDecomposition(Sema &S,
1103 ArrayRef<BindingDecl *> Bindings,
1104 ValueDecl *Src, QualType DecompType,
1105 const ComplexType *CT) {
1106 return checkSimpleDecomposition(
1107 S, Bindings, Src, DecompType, NumElemsAPS: llvm::APSInt::get(X: 2),
1108 ElemType: S.Context.getQualifiedType(T: CT->getElementType(),
1109 Qs: DecompType.getQualifiers()),
1110 GetInit: [&](SourceLocation Loc, Expr *Base, unsigned I) -> ExprResult {
1111 return S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: I ? UO_Imag : UO_Real, InputExpr: Base);
1112 });
1113}
1114
1115static std::string printTemplateArgs(const PrintingPolicy &PrintingPolicy,
1116 TemplateArgumentListInfo &Args,
1117 const TemplateParameterList *Params) {
1118 SmallString<128> SS;
1119 llvm::raw_svector_ostream OS(SS);
1120 bool First = true;
1121 unsigned I = 0;
1122 for (auto &Arg : Args.arguments()) {
1123 if (!First)
1124 OS << ", ";
1125 Arg.getArgument().print(Policy: PrintingPolicy, Out&: OS,
1126 IncludeType: TemplateParameterList::shouldIncludeTypeForArgument(
1127 Policy: PrintingPolicy, TPL: Params, Idx: I));
1128 First = false;
1129 I++;
1130 }
1131 return std::string(OS.str());
1132}
1133
1134static QualType getStdTrait(Sema &S, SourceLocation Loc, StringRef Trait,
1135 TemplateArgumentListInfo &Args, unsigned DiagID) {
1136 auto DiagnoseMissing = [&] {
1137 if (DiagID)
1138 S.Diag(Loc, DiagID) << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(),
1139 Args, /*Params*/ nullptr);
1140 return QualType();
1141 };
1142
1143 // FIXME: Factor out duplication with lookupPromiseType in SemaCoroutine.
1144 NamespaceDecl *Std = S.getStdNamespace();
1145 if (!Std)
1146 return DiagnoseMissing();
1147
1148 // Look up the trait itself, within namespace std. We can diagnose various
1149 // problems with this lookup even if we've been asked to not diagnose a
1150 // missing specialization, because this can only fail if the user has been
1151 // declaring their own names in namespace std or we don't support the
1152 // standard library implementation in use.
1153 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: Trait), Loc,
1154 Sema::LookupOrdinaryName);
1155 if (!S.LookupQualifiedName(R&: Result, LookupCtx: Std))
1156 return DiagnoseMissing();
1157 if (Result.isAmbiguous())
1158 return QualType();
1159
1160 ClassTemplateDecl *TraitTD = Result.getAsSingle<ClassTemplateDecl>();
1161 if (!TraitTD) {
1162 Result.suppressDiagnostics();
1163 NamedDecl *Found = *Result.begin();
1164 S.Diag(Loc, DiagID: diag::err_std_type_trait_not_class_template) << Trait;
1165 S.Diag(Loc: Found->getLocation(), DiagID: diag::note_declared_at);
1166 return QualType();
1167 }
1168
1169 // Build the template-id.
1170 QualType TraitTy = S.CheckTemplateIdType(
1171 Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(TraitTD), TemplateLoc: Loc, TemplateArgs&: Args,
1172 /*Scope=*/nullptr, /*ForNestedNameSpecifier=*/false);
1173 if (TraitTy.isNull())
1174 return QualType();
1175
1176 if (!S.isCompleteType(Loc, T: TraitTy)) {
1177 if (DiagID)
1178 S.RequireCompleteType(
1179 Loc, T: TraitTy, DiagID,
1180 Args: printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1181 Params: TraitTD->getTemplateParameters()));
1182 return QualType();
1183 }
1184 return TraitTy;
1185}
1186
1187static bool lookupMember(Sema &S, CXXRecordDecl *RD,
1188 LookupResult &MemberLookup) {
1189 assert(RD && "specialization of class template is not a class?");
1190 S.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
1191 return MemberLookup.isAmbiguous();
1192}
1193
1194static TemplateArgumentLoc
1195getTrivialIntegralTemplateArgument(Sema &S, SourceLocation Loc, QualType T,
1196 uint64_t I) {
1197 TemplateArgument Arg(S.Context, S.Context.MakeIntValue(Value: I, Type: T), T);
1198 return S.getTrivialTemplateArgumentLoc(Arg, NTTPType: T, Loc);
1199}
1200
1201static TemplateArgumentLoc
1202getTrivialTypeTemplateArgument(Sema &S, SourceLocation Loc, QualType T) {
1203 return S.getTrivialTemplateArgumentLoc(Arg: TemplateArgument(T), NTTPType: QualType(), Loc);
1204}
1205
1206namespace { enum class IsTupleLike { TupleLike, NotTupleLike, Error }; }
1207
1208static IsTupleLike isTupleLike(Sema &S, SourceLocation Loc, QualType T,
1209 unsigned &OutSize) {
1210 EnterExpressionEvaluationContext ContextRAII(
1211 S, Sema::ExpressionEvaluationContext::ConstantEvaluated);
1212
1213 // Form template argument list for tuple_size<T>.
1214 TemplateArgumentListInfo Args(Loc, Loc);
1215 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1216
1217 QualType TraitTy = getStdTrait(S, Loc, Trait: "tuple_size", Args, /*DiagID=*/0);
1218 if (TraitTy.isNull())
1219 return IsTupleLike::NotTupleLike;
1220
1221 DeclarationName Value = S.PP.getIdentifierInfo(Name: "value");
1222 LookupResult R(S, Value, Loc, Sema::LookupOrdinaryName);
1223
1224 // If there's no tuple_size specialization or the lookup of 'value' is empty,
1225 // it's not tuple-like.
1226 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R) || R.empty())
1227 return IsTupleLike::NotTupleLike;
1228
1229 // If we get this far, we've committed to the tuple interpretation, but
1230 // we can still fail if there actually isn't a usable ::value.
1231
1232 struct ICEDiagnoser : Sema::VerifyICEDiagnoser {
1233 LookupResult &R;
1234 TemplateArgumentListInfo &Args;
1235 ICEDiagnoser(LookupResult &R, TemplateArgumentListInfo &Args)
1236 : R(R), Args(Args) {}
1237 Sema::SemaDiagnosticBuilder diagnoseNotICE(Sema &S,
1238 SourceLocation Loc) override {
1239 return S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_not_constant)
1240 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1241 /*Params*/ nullptr);
1242 }
1243 } Diagnoser(R, Args);
1244
1245 ExprResult E =
1246 S.BuildDeclarationNameExpr(SS: CXXScopeSpec(), R, /*NeedsADL*/false);
1247 if (E.isInvalid())
1248 return IsTupleLike::Error;
1249
1250 llvm::APSInt Size;
1251 E = S.VerifyIntegerConstantExpression(E: E.get(), Result: &Size, Diagnoser);
1252 if (E.isInvalid())
1253 return IsTupleLike::Error;
1254
1255 // The implementation limit is UINT_MAX-1, to allow this to be passed down on
1256 // an UnsignedOrNone.
1257 if (Size < 0 || Size >= UINT_MAX) {
1258 llvm::SmallVector<char, 16> Str;
1259 Size.toString(Str);
1260 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_size_invalid)
1261 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1262 /*Params=*/nullptr)
1263 << StringRef(Str.data(), Str.size());
1264 return IsTupleLike::Error;
1265 }
1266
1267 OutSize = Size.getExtValue();
1268 return IsTupleLike::TupleLike;
1269}
1270
1271/// \return std::tuple_element<I, T>::type.
1272static QualType getTupleLikeElementType(Sema &S, SourceLocation Loc,
1273 unsigned I, QualType T) {
1274 // Form template argument list for tuple_element<I, T>.
1275 TemplateArgumentListInfo Args(Loc, Loc);
1276 Args.addArgument(
1277 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1278 Args.addArgument(Loc: getTrivialTypeTemplateArgument(S, Loc, T));
1279
1280 QualType TraitTy =
1281 getStdTrait(S, Loc, Trait: "tuple_element", Args,
1282 DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized);
1283 if (TraitTy.isNull())
1284 return QualType();
1285
1286 DeclarationName TypeDN = S.PP.getIdentifierInfo(Name: "type");
1287 LookupResult R(S, TypeDN, Loc, Sema::LookupOrdinaryName);
1288 if (lookupMember(S, RD: TraitTy->getAsCXXRecordDecl(), MemberLookup&: R))
1289 return QualType();
1290
1291 auto *TD = R.getAsSingle<TypeDecl>();
1292 if (!TD) {
1293 R.suppressDiagnostics();
1294 S.Diag(Loc, DiagID: diag::err_decomp_decl_std_tuple_element_not_specialized)
1295 << printTemplateArgs(PrintingPolicy: S.Context.getPrintingPolicy(), Args,
1296 /*Params*/ nullptr);
1297 if (!R.empty())
1298 S.Diag(Loc: R.getRepresentativeDecl()->getLocation(), DiagID: diag::note_declared_at);
1299 return QualType();
1300 }
1301
1302 NestedNameSpecifier Qualifier(TraitTy.getTypePtr());
1303 return S.Context.getTypeDeclType(Keyword: ElaboratedTypeKeyword::None, Qualifier, Decl: TD);
1304}
1305
1306namespace {
1307struct InitializingBinding {
1308 Sema &S;
1309 InitializingBinding(Sema &S, BindingDecl *BD) : S(S) {
1310 Sema::CodeSynthesisContext Ctx;
1311 Ctx.Kind = Sema::CodeSynthesisContext::InitializingStructuredBinding;
1312 Ctx.PointOfInstantiation = BD->getLocation();
1313 Ctx.Entity = BD;
1314 S.pushCodeSynthesisContext(Ctx);
1315 }
1316 ~InitializingBinding() {
1317 S.popCodeSynthesisContext();
1318 }
1319};
1320}
1321
1322static bool checkTupleLikeDecomposition(Sema &S,
1323 ArrayRef<BindingDecl *> Bindings,
1324 VarDecl *Src, QualType DecompType,
1325 unsigned NumElems) {
1326 auto *DD = cast<DecompositionDecl>(Val: Src);
1327 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumElems))
1328 return true;
1329
1330 if (Bindings.empty())
1331 return false;
1332
1333 DeclarationName GetDN = S.PP.getIdentifierInfo(Name: "get");
1334
1335 // [dcl.decomp]p3:
1336 // The unqualified-id get is looked up in the scope of E by class member
1337 // access lookup ...
1338 LookupResult MemberGet(S, GetDN, Src->getLocation(), Sema::LookupMemberName);
1339 bool UseMemberGet = false;
1340 if (S.isCompleteType(Loc: Src->getLocation(), T: DecompType)) {
1341 if (auto *RD = DecompType->getAsCXXRecordDecl())
1342 S.LookupQualifiedName(R&: MemberGet, LookupCtx: RD);
1343 if (MemberGet.isAmbiguous())
1344 return true;
1345 // ... and if that finds at least one declaration that is a function
1346 // template whose first template parameter is a non-type parameter ...
1347 for (NamedDecl *D : MemberGet) {
1348 if (FunctionTemplateDecl *FTD =
1349 dyn_cast<FunctionTemplateDecl>(Val: D->getUnderlyingDecl())) {
1350 TemplateParameterList *TPL = FTD->getTemplateParameters();
1351 if (TPL->size() != 0 &&
1352 isa<NonTypeTemplateParmDecl>(Val: TPL->getParam(Idx: 0))) {
1353 // ... the initializer is e.get<i>().
1354 UseMemberGet = true;
1355 break;
1356 }
1357 }
1358 }
1359 }
1360
1361 unsigned I = 0;
1362 for (auto *B : DD->flat_bindings()) {
1363 InitializingBinding InitContext(S, B);
1364 SourceLocation Loc = B->getLocation();
1365
1366 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1367 if (E.isInvalid())
1368 return true;
1369
1370 // e is an lvalue if the type of the entity is an lvalue reference and
1371 // an xvalue otherwise
1372 if (!Src->getType()->isLValueReferenceType())
1373 E = ImplicitCastExpr::Create(Context: S.Context, T: E.get()->getType(), Kind: CK_NoOp,
1374 Operand: E.get(), BasePath: nullptr, Cat: VK_XValue,
1375 FPO: FPOptionsOverride());
1376
1377 TemplateArgumentListInfo Args(Loc, Loc);
1378 Args.addArgument(
1379 Loc: getTrivialIntegralTemplateArgument(S, Loc, T: S.Context.getSizeType(), I));
1380
1381 if (UseMemberGet) {
1382 // if [lookup of member get] finds at least one declaration, the
1383 // initializer is e.get<i-1>().
1384 E = S.BuildMemberReferenceExpr(Base: E.get(), BaseType: DecompType, OpLoc: Loc, IsArrow: false,
1385 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr,
1386 R&: MemberGet, TemplateArgs: &Args, S: nullptr);
1387 if (E.isInvalid())
1388 return true;
1389
1390 E = S.BuildCallExpr(S: nullptr, Fn: E.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc);
1391 } else {
1392 // Otherwise, the initializer is get<i-1>(e), where get is looked up
1393 // in the associated namespaces.
1394 Expr *Get = UnresolvedLookupExpr::Create(
1395 Context: S.Context, NamingClass: nullptr, QualifierLoc: NestedNameSpecifierLoc(), TemplateKWLoc: SourceLocation(),
1396 NameInfo: DeclarationNameInfo(GetDN, Loc), /*RequiresADL=*/true, Args: &Args,
1397 Begin: UnresolvedSetIterator(), End: UnresolvedSetIterator(),
1398 /*KnownDependent=*/false, /*KnownInstantiationDependent=*/false);
1399
1400 Expr *Arg = E.get();
1401 E = S.BuildCallExpr(S: nullptr, Fn: Get, LParenLoc: Loc, ArgExprs: Arg, RParenLoc: Loc);
1402 }
1403 if (E.isInvalid())
1404 return true;
1405 Expr *Init = E.get();
1406
1407 // Given the type T designated by std::tuple_element<i - 1, E>::type
1408 QualType T = getTupleLikeElementType(S, Loc, I, T: DecompType);
1409 if (T.isNull())
1410 return true;
1411
1412 // C++26 [dcl.struct.bind]p7:
1413 // and the type Ui, defined as Ti if the initializer is a prvalue,
1414 // as "lvalue reference to Ti" if the initializer is an lvalue,
1415 // or as "rvalue reference to Ti" otherwise
1416 // "defined as Ti if the initializer is a prvalue" was introduced by CWG3135
1417 QualType U = E.get()->isPRValue()
1418 ? T
1419 : S.BuildReferenceType(T, LValueRef: E.get()->isLValue(), Loc,
1420 Entity: B->getDeclName());
1421 if (U.isNull())
1422 return true;
1423
1424 // Don't give this VarDecl a TypeSourceInfo, since this is a synthesized
1425 // entity and this type was never written in source code.
1426 auto *BindingVD =
1427 VarDecl::Create(C&: S.Context, DC: Src->getDeclContext(), StartLoc: Loc, IdLoc: Loc,
1428 Id: B->getDeclName().getAsIdentifierInfo(), T: U,
1429 /*TInfo=*/nullptr, S: Src->getStorageClass());
1430 BindingVD->setLexicalDeclContext(Src->getLexicalDeclContext());
1431 BindingVD->setTSCSpec(Src->getTSCSpec());
1432 BindingVD->setConstexpr(Src->isConstexpr());
1433 if (const auto *CIAttr = Src->getAttr<ConstInitAttr>())
1434 BindingVD->addAttr(A: CIAttr->clone(C&: S.Context));
1435 BindingVD->setImplicit();
1436 if (Src->isInlineSpecified())
1437 BindingVD->setInlineSpecified();
1438 BindingVD->getLexicalDeclContext()->addHiddenDecl(D: BindingVD);
1439
1440 InitializedEntity Entity = InitializedEntity::InitializeBinding(Binding: BindingVD);
1441 InitializationKind Kind = InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: Loc);
1442 InitializationSequence Seq(S, Entity, Kind, Init);
1443 E = Seq.Perform(S, Entity, Kind, Args: Init);
1444 if (E.isInvalid())
1445 return true;
1446 E = S.ActOnFinishFullExpr(Expr: E.get(), CC: Loc, /*DiscardedValue*/ false);
1447 if (E.isInvalid())
1448 return true;
1449 BindingVD->setInit(E.get());
1450 S.CheckCompleteVariableDeclaration(VD: BindingVD);
1451
1452 E = S.BuildDeclarationNameExpr(
1453 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(B->getDeclName(), Loc), D: BindingVD);
1454 if (E.isInvalid())
1455 return true;
1456
1457 B->setBinding(DeclaredType: T, Binding: E.get());
1458 I++;
1459 }
1460
1461 return false;
1462}
1463
1464/// Find the base class to decompose in a built-in decomposition of a class type.
1465/// This base class search is, unfortunately, not quite like any other that we
1466/// perform anywhere else in C++.
1467static DeclAccessPair findDecomposableBaseClass(Sema &S, SourceLocation Loc,
1468 const CXXRecordDecl *RD,
1469 CXXCastPath &BasePath) {
1470 auto BaseHasFields = [](const CXXBaseSpecifier *Specifier,
1471 CXXBasePath &Path) {
1472 return Specifier->getType()->getAsCXXRecordDecl()->hasDirectFields();
1473 };
1474
1475 const CXXRecordDecl *ClassWithFields = nullptr;
1476 AccessSpecifier AS = AS_public;
1477 if (RD->hasDirectFields())
1478 // [dcl.decomp]p4:
1479 // Otherwise, all of E's non-static data members shall be public direct
1480 // members of E ...
1481 ClassWithFields = RD;
1482 else {
1483 // ... or of ...
1484 CXXBasePaths Paths;
1485 Paths.setOrigin(const_cast<CXXRecordDecl*>(RD));
1486 if (!RD->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1487 // If no classes have fields, just decompose RD itself. (This will work
1488 // if and only if zero bindings were provided.)
1489 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(RD), AS: AS_public);
1490 }
1491
1492 CXXBasePath *BestPath = nullptr;
1493 for (auto &P : Paths) {
1494 if (!BestPath)
1495 BestPath = &P;
1496 else if (!S.Context.hasSameType(T1: P.back().Base->getType(),
1497 T2: BestPath->back().Base->getType())) {
1498 // ... the same ...
1499 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1500 << false << RD << BestPath->back().Base->getType()
1501 << P.back().Base->getType();
1502 return DeclAccessPair();
1503 } else if (P.Access < BestPath->Access) {
1504 BestPath = &P;
1505 }
1506 }
1507
1508 // ... unambiguous ...
1509 QualType BaseType = BestPath->back().Base->getType();
1510 if (Paths.isAmbiguous(BaseType: S.Context.getCanonicalType(T: BaseType))) {
1511 S.Diag(Loc, DiagID: diag::err_decomp_decl_ambiguous_base)
1512 << RD << BaseType << S.getAmbiguousPathsDisplayString(Paths);
1513 return DeclAccessPair();
1514 }
1515
1516 // ... [accessible, implied by other rules] base class of E.
1517 S.CheckBaseClassAccess(AccessLoc: Loc, Base: BaseType, Derived: S.Context.getCanonicalTagType(TD: RD),
1518 Path: *BestPath, DiagID: diag::err_decomp_decl_inaccessible_base);
1519 AS = BestPath->Access;
1520
1521 ClassWithFields = BaseType->getAsCXXRecordDecl();
1522 S.BuildBasePathArray(Paths, BasePath);
1523 }
1524
1525 // The above search did not check whether the selected class itself has base
1526 // classes with fields, so check that now.
1527 CXXBasePaths Paths;
1528 if (ClassWithFields->lookupInBases(BaseMatches: BaseHasFields, Paths)) {
1529 S.Diag(Loc, DiagID: diag::err_decomp_decl_multiple_bases_with_members)
1530 << (ClassWithFields == RD) << RD << ClassWithFields
1531 << Paths.front().back().Base->getType();
1532 return DeclAccessPair();
1533 }
1534
1535 return DeclAccessPair::make(D: const_cast<CXXRecordDecl*>(ClassWithFields), AS);
1536}
1537
1538static bool CheckMemberDecompositionFields(Sema &S, SourceLocation Loc,
1539 const CXXRecordDecl *OrigRD,
1540 QualType DecompType,
1541 DeclAccessPair BasePair) {
1542 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1543 if (!RD)
1544 return true;
1545
1546 for (auto *FD : RD->fields()) {
1547 if (FD->isUnnamedBitField())
1548 continue;
1549
1550 // All the non-static data members are required to be nameable, so they
1551 // must all have names.
1552 if (!FD->getDeclName()) {
1553 if (RD->isLambda()) {
1554 S.Diag(Loc, DiagID: diag::err_decomp_decl_lambda);
1555 S.Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
1556 return true;
1557 }
1558
1559 if (FD->isAnonymousStructOrUnion()) {
1560 S.Diag(Loc, DiagID: diag::err_decomp_decl_anon_union_member)
1561 << DecompType << FD->getType()->isUnionType();
1562 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_declared_at);
1563 return true;
1564 }
1565
1566 // FIXME: Are there any other ways we could have an anonymous member?
1567 }
1568 // The field must be accessible in the context of the structured binding.
1569 // We already checked that the base class is accessible.
1570 // FIXME: Add 'const' to AccessedEntity's classes so we can remove the
1571 // const_cast here.
1572 S.CheckStructuredBindingMemberAccess(
1573 UseLoc: Loc, DecomposedClass: const_cast<CXXRecordDecl *>(OrigRD),
1574 Field: DeclAccessPair::make(D: FD, AS: CXXRecordDecl::MergeAccess(
1575 PathAccess: BasePair.getAccess(), DeclAccess: FD->getAccess())));
1576 }
1577 return false;
1578}
1579
1580static bool checkMemberDecomposition(Sema &S, ArrayRef<BindingDecl*> Bindings,
1581 ValueDecl *Src, QualType DecompType,
1582 const CXXRecordDecl *OrigRD) {
1583 if (S.RequireCompleteType(Loc: Src->getLocation(), T: DecompType,
1584 DiagID: diag::err_incomplete_type))
1585 return true;
1586
1587 CXXCastPath BasePath;
1588 DeclAccessPair BasePair =
1589 findDecomposableBaseClass(S, Loc: Src->getLocation(), RD: OrigRD, BasePath);
1590 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1591 if (!RD)
1592 return true;
1593 QualType BaseType = S.Context.getQualifiedType(
1594 T: S.Context.getCanonicalTagType(TD: RD), Qs: DecompType.getQualifiers());
1595
1596 auto *DD = cast<DecompositionDecl>(Val: Src);
1597 unsigned NumFields = llvm::count_if(
1598 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1599 if (CheckBindingsCount(S, DD, DecompType, Bindings, MemberCount: NumFields))
1600 return true;
1601
1602 // all of E's non-static data members shall be [...] well-formed
1603 // when named as e.name in the context of the structured binding,
1604 // E shall not have an anonymous union member, ...
1605 auto FlatBindings = DD->flat_bindings();
1606 assert(llvm::range_size(FlatBindings) == NumFields);
1607 auto FlatBindingsItr = FlatBindings.begin();
1608
1609 if (CheckMemberDecompositionFields(S, Loc: Src->getLocation(), OrigRD, DecompType,
1610 BasePair))
1611 return true;
1612
1613 for (auto *FD : RD->fields()) {
1614 if (FD->isUnnamedBitField())
1615 continue;
1616
1617 // We have a real field to bind.
1618 assert(FlatBindingsItr != FlatBindings.end());
1619 BindingDecl *B = *(FlatBindingsItr++);
1620 SourceLocation Loc = B->getLocation();
1621
1622 // Initialize the binding to Src.FD.
1623 ExprResult E = S.BuildDeclRefExpr(D: Src, Ty: DecompType, VK: VK_LValue, Loc);
1624 if (E.isInvalid())
1625 return true;
1626 E = S.ImpCastExprToType(E: E.get(), Type: BaseType, CK: CK_UncheckedDerivedToBase,
1627 VK: VK_LValue, BasePath: &BasePath);
1628 if (E.isInvalid())
1629 return true;
1630 E = S.BuildFieldReferenceExpr(BaseExpr: E.get(), /*IsArrow*/ false, OpLoc: Loc,
1631 SS: CXXScopeSpec(), Field: FD,
1632 FoundDecl: DeclAccessPair::make(D: FD, AS: FD->getAccess()),
1633 MemberNameInfo: DeclarationNameInfo(FD->getDeclName(), Loc));
1634 if (E.isInvalid())
1635 return true;
1636
1637 // If the type of the member is T, the referenced type is cv T, where cv is
1638 // the cv-qualification of the decomposition expression.
1639 //
1640 // FIXME: We resolve a defect here: if the field is mutable, we do not add
1641 // 'const' to the type of the field.
1642 Qualifiers Q = DecompType.getQualifiers();
1643 if (FD->isMutable())
1644 Q.removeConst();
1645 B->setBinding(DeclaredType: S.BuildQualifiedType(T: FD->getType(), Loc, Qs: Q), Binding: E.get());
1646 }
1647
1648 return false;
1649}
1650
1651void Sema::CheckCompleteDecompositionDeclaration(DecompositionDecl *DD) {
1652 QualType DecompType = DD->getType();
1653
1654 // If the type of the decomposition is dependent, then so is the type of
1655 // each binding.
1656 if (DecompType->isDependentType()) {
1657 // Note that all of the types are still Null or PackExpansionType.
1658 for (auto *B : DD->bindings()) {
1659 // Do not overwrite any pack type.
1660 if (B->getType().isNull())
1661 B->setType(Context.DependentTy);
1662 }
1663 return;
1664 }
1665
1666 DecompType = DecompType.getNonReferenceType();
1667 ArrayRef<BindingDecl*> Bindings = DD->bindings();
1668
1669 // C++1z [dcl.decomp]/2:
1670 // If E is an array type [...]
1671 // As an extension, we also support decomposition of built-in complex and
1672 // vector types.
1673 if (auto *CAT = Context.getAsConstantArrayType(T: DecompType)) {
1674 if (checkArrayDecomposition(S&: *this, Bindings, Src: DD, DecompType, CAT))
1675 DD->setInvalidDecl();
1676 return;
1677 }
1678 if (auto *VT = DecompType->getAs<VectorType>()) {
1679 if (checkVectorDecomposition(S&: *this, Bindings, Src: DD, DecompType, VT))
1680 DD->setInvalidDecl();
1681 return;
1682 }
1683 if (auto *CT = DecompType->getAs<ComplexType>()) {
1684 if (checkComplexDecomposition(S&: *this, Bindings, Src: DD, DecompType, CT))
1685 DD->setInvalidDecl();
1686 return;
1687 }
1688
1689 // C++1z [dcl.decomp]/3:
1690 // if the expression std::tuple_size<E>::value is a well-formed integral
1691 // constant expression, [...]
1692 unsigned TupleSize;
1693 switch (isTupleLike(S&: *this, Loc: DD->getLocation(), T: DecompType, OutSize&: TupleSize)) {
1694 case IsTupleLike::Error:
1695 DD->setInvalidDecl();
1696 return;
1697
1698 case IsTupleLike::TupleLike:
1699 if (checkTupleLikeDecomposition(S&: *this, Bindings, Src: DD, DecompType, NumElems: TupleSize))
1700 DD->setInvalidDecl();
1701 return;
1702
1703 case IsTupleLike::NotTupleLike:
1704 break;
1705 }
1706
1707 // C++1z [dcl.dcl]/8:
1708 // [E shall be of array or non-union class type]
1709 CXXRecordDecl *RD = DecompType->getAsCXXRecordDecl();
1710 if (!RD || RD->isUnion()) {
1711 Diag(Loc: DD->getLocation(), DiagID: diag::err_decomp_decl_unbindable_type)
1712 << DD << !RD << DecompType;
1713 DD->setInvalidDecl();
1714 return;
1715 }
1716
1717 // C++1z [dcl.decomp]/4:
1718 // all of E's non-static data members shall be [...] direct members of
1719 // E or of the same unambiguous public base class of E, ...
1720 if (checkMemberDecomposition(S&: *this, Bindings, Src: DD, DecompType, OrigRD: RD))
1721 DD->setInvalidDecl();
1722}
1723
1724UnsignedOrNone Sema::GetDecompositionElementCount(QualType T,
1725 SourceLocation Loc) {
1726 const ASTContext &Ctx = getASTContext();
1727 assert(!T->isDependentType());
1728
1729 Qualifiers Quals;
1730 QualType Unqual = Context.getUnqualifiedArrayType(T, Quals);
1731 Quals.removeCVRQualifiers();
1732 T = Context.getQualifiedType(T: Unqual, Qs: Quals);
1733
1734 if (auto *CAT = Ctx.getAsConstantArrayType(T))
1735 return static_cast<unsigned>(CAT->getSize().getZExtValue());
1736 if (auto *VT = T->getAs<VectorType>())
1737 return VT->getNumElements();
1738 if (T->getAs<ComplexType>())
1739 return 2u;
1740
1741 unsigned TupleSize;
1742 switch (isTupleLike(S&: *this, Loc, T, OutSize&: TupleSize)) {
1743 case IsTupleLike::Error:
1744 return std::nullopt;
1745 case IsTupleLike::TupleLike:
1746 return TupleSize;
1747 case IsTupleLike::NotTupleLike:
1748 break;
1749 }
1750
1751 const CXXRecordDecl *OrigRD = T->getAsCXXRecordDecl();
1752 if (!OrigRD || OrigRD->isUnion())
1753 return std::nullopt;
1754
1755 if (RequireCompleteType(Loc, T, DiagID: diag::err_incomplete_type))
1756 return std::nullopt;
1757
1758 CXXCastPath BasePath;
1759 DeclAccessPair BasePair =
1760 findDecomposableBaseClass(S&: *this, Loc, RD: OrigRD, BasePath);
1761 const auto *RD = cast_or_null<CXXRecordDecl>(Val: BasePair.getDecl());
1762 if (!RD)
1763 return std::nullopt;
1764
1765 unsigned NumFields = llvm::count_if(
1766 Range: RD->fields(), P: [](FieldDecl *FD) { return !FD->isUnnamedBitField(); });
1767
1768 if (CheckMemberDecompositionFields(S&: *this, Loc, OrigRD, DecompType: T, BasePair))
1769 return std::nullopt;
1770
1771 return NumFields;
1772}
1773
1774void Sema::MergeVarDeclExceptionSpecs(VarDecl *New, VarDecl *Old) {
1775 // Shortcut if exceptions are disabled.
1776 if (!getLangOpts().CXXExceptions)
1777 return;
1778
1779 assert(Context.hasSameType(New->getType(), Old->getType()) &&
1780 "Should only be called if types are otherwise the same.");
1781
1782 QualType NewType = New->getType();
1783 QualType OldType = Old->getType();
1784
1785 // We're only interested in pointers and references to functions, as well
1786 // as pointers to member functions.
1787 if (const ReferenceType *R = NewType->getAs<ReferenceType>()) {
1788 NewType = R->getPointeeType();
1789 OldType = OldType->castAs<ReferenceType>()->getPointeeType();
1790 } else if (const PointerType *P = NewType->getAs<PointerType>()) {
1791 NewType = P->getPointeeType();
1792 OldType = OldType->castAs<PointerType>()->getPointeeType();
1793 } else if (const MemberPointerType *M = NewType->getAs<MemberPointerType>()) {
1794 NewType = M->getPointeeType();
1795 OldType = OldType->castAs<MemberPointerType>()->getPointeeType();
1796 }
1797
1798 if (!NewType->isFunctionProtoType())
1799 return;
1800
1801 // There's lots of special cases for functions. For function pointers, system
1802 // libraries are hopefully not as broken so that we don't need these
1803 // workarounds.
1804 if (CheckEquivalentExceptionSpec(
1805 Old: OldType->getAs<FunctionProtoType>(), OldLoc: Old->getLocation(),
1806 New: NewType->getAs<FunctionProtoType>(), NewLoc: New->getLocation())) {
1807 New->setInvalidDecl();
1808 }
1809}
1810
1811/// CheckCXXDefaultArguments - Verify that the default arguments for a
1812/// function declaration are well-formed according to C++
1813/// [dcl.fct.default].
1814void Sema::CheckCXXDefaultArguments(FunctionDecl *FD) {
1815 // This checking doesn't make sense for explicit specializations; their
1816 // default arguments are determined by the declaration we're specializing,
1817 // not by FD.
1818 if (FD->getTemplateSpecializationKind() == TSK_ExplicitSpecialization)
1819 return;
1820 if (auto *FTD = FD->getDescribedFunctionTemplate())
1821 if (FTD->isMemberSpecialization())
1822 return;
1823
1824 unsigned NumParams = FD->getNumParams();
1825 unsigned ParamIdx = 0;
1826
1827 // Find first parameter with a default argument
1828 for (; ParamIdx < NumParams; ++ParamIdx) {
1829 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1830 if (Param->hasDefaultArg())
1831 break;
1832 }
1833
1834 // C++20 [dcl.fct.default]p4:
1835 // In a given function declaration, each parameter subsequent to a parameter
1836 // with a default argument shall have a default argument supplied in this or
1837 // a previous declaration, unless the parameter was expanded from a
1838 // parameter pack, or shall be a function parameter pack.
1839 for (++ParamIdx; ParamIdx < NumParams; ++ParamIdx) {
1840 ParmVarDecl *Param = FD->getParamDecl(i: ParamIdx);
1841 if (Param->hasDefaultArg() || Param->isParameterPack() ||
1842 (CurrentInstantiationScope &&
1843 CurrentInstantiationScope->isLocalPackExpansion(D: Param)))
1844 continue;
1845 if (Param->isInvalidDecl())
1846 /* We already complained about this parameter. */;
1847 else if (Param->getIdentifier())
1848 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing_name)
1849 << Param->getIdentifier();
1850 else
1851 Diag(Loc: Param->getLocation(), DiagID: diag::err_param_default_argument_missing);
1852 }
1853}
1854
1855/// Check that the given type is a literal type. Issue a diagnostic if not,
1856/// if Kind is Diagnose.
1857/// \return \c true if a problem has been found (and optionally diagnosed).
1858template <typename... Ts>
1859static bool CheckLiteralType(Sema &SemaRef, Sema::CheckConstexprKind Kind,
1860 SourceLocation Loc, QualType T, unsigned DiagID,
1861 Ts &&...DiagArgs) {
1862 if (T->isDependentType())
1863 return false;
1864
1865 switch (Kind) {
1866 case Sema::CheckConstexprKind::Diagnose:
1867 return SemaRef.RequireLiteralType(Loc, T, DiagID,
1868 std::forward<Ts>(DiagArgs)...);
1869
1870 case Sema::CheckConstexprKind::CheckValid:
1871 return !T->isLiteralType(Ctx: SemaRef.Context);
1872 }
1873
1874 llvm_unreachable("unknown CheckConstexprKind");
1875}
1876
1877/// Determine whether a destructor cannot be constexpr due to
1878static bool CheckConstexprDestructorSubobjects(Sema &SemaRef,
1879 const CXXDestructorDecl *DD,
1880 Sema::CheckConstexprKind Kind) {
1881 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1882 "this check is obsolete for C++23");
1883 auto Check = [&](SourceLocation Loc, QualType T, const FieldDecl *FD) {
1884 const CXXRecordDecl *RD =
1885 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1886 if (!RD || RD->hasConstexprDestructor())
1887 return true;
1888
1889 if (Kind == Sema::CheckConstexprKind::Diagnose) {
1890 SemaRef.Diag(Loc: DD->getLocation(), DiagID: diag::err_constexpr_dtor_subobject)
1891 << static_cast<int>(DD->getConstexprKind()) << !FD
1892 << (FD ? FD->getDeclName() : DeclarationName()) << T;
1893 SemaRef.Diag(Loc, DiagID: diag::note_constexpr_dtor_subobject)
1894 << !FD << (FD ? FD->getDeclName() : DeclarationName()) << T;
1895 }
1896 return false;
1897 };
1898
1899 const CXXRecordDecl *RD = DD->getParent();
1900 for (const CXXBaseSpecifier &B : RD->bases())
1901 if (!Check(B.getBaseTypeLoc(), B.getType(), nullptr))
1902 return false;
1903 for (const FieldDecl *FD : RD->fields())
1904 if (!Check(FD->getLocation(), FD->getType(), FD))
1905 return false;
1906 return true;
1907}
1908
1909/// Check whether a function's parameter types are all literal types. If so,
1910/// return true. If not, produce a suitable diagnostic and return false.
1911static bool CheckConstexprParameterTypes(Sema &SemaRef,
1912 const FunctionDecl *FD,
1913 Sema::CheckConstexprKind Kind) {
1914 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1915 "this check is obsolete for C++23");
1916 unsigned ArgIndex = 0;
1917 const auto *FT = FD->getType()->castAs<FunctionProtoType>();
1918 for (FunctionProtoType::param_type_iterator i = FT->param_type_begin(),
1919 e = FT->param_type_end();
1920 i != e; ++i, ++ArgIndex) {
1921 const ParmVarDecl *PD = FD->getParamDecl(i: ArgIndex);
1922 assert(PD && "null in a parameter list");
1923 SourceLocation ParamLoc = PD->getLocation();
1924 if (CheckLiteralType(SemaRef, Kind, Loc: ParamLoc, T: *i,
1925 DiagID: diag::err_constexpr_non_literal_param, DiagArgs: ArgIndex + 1,
1926 DiagArgs: PD->getSourceRange(), DiagArgs: isa<CXXConstructorDecl>(Val: FD),
1927 DiagArgs: FD->isConsteval()))
1928 return false;
1929 }
1930 return true;
1931}
1932
1933/// Check whether a function's return type is a literal type. If so, return
1934/// true. If not, produce a suitable diagnostic and return false.
1935static bool CheckConstexprReturnType(Sema &SemaRef, const FunctionDecl *FD,
1936 Sema::CheckConstexprKind Kind) {
1937 assert(!SemaRef.getLangOpts().CPlusPlus23 &&
1938 "this check is obsolete for C++23");
1939 if (CheckLiteralType(SemaRef, Kind, Loc: FD->getLocation(), T: FD->getReturnType(),
1940 DiagID: diag::err_constexpr_non_literal_return,
1941 DiagArgs: FD->isConsteval()))
1942 return false;
1943 return true;
1944}
1945
1946/// Get diagnostic %select index for tag kind for
1947/// record diagnostic message.
1948/// WARNING: Indexes apply to particular diagnostics only!
1949///
1950/// \returns diagnostic %select index.
1951static unsigned getRecordDiagFromTagKind(TagTypeKind Tag) {
1952 switch (Tag) {
1953 case TagTypeKind::Struct:
1954 return 0;
1955 case TagTypeKind::Interface:
1956 return 1;
1957 case TagTypeKind::Class:
1958 return 2;
1959 default: llvm_unreachable("Invalid tag kind for record diagnostic!");
1960 }
1961}
1962
1963static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
1964 Stmt *Body,
1965 Sema::CheckConstexprKind Kind);
1966static bool CheckConstexprMissingReturn(Sema &SemaRef, const FunctionDecl *Dcl);
1967
1968bool Sema::CheckConstexprFunctionDefinition(const FunctionDecl *NewFD,
1969 CheckConstexprKind Kind) {
1970 const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: NewFD);
1971 if (!getLangOpts().CPlusPlus26 && MD && MD->isInstance()) {
1972 // C++11 [dcl.constexpr]p4:
1973 // The definition of a constexpr constructor shall satisfy the following
1974 // constraints:
1975 // - the class shall not have any virtual base classes;
1976 //
1977 // FIXME: This only applies to constructors and destructors, not arbitrary
1978 // member functions.
1979 const CXXRecordDecl *RD = MD->getParent();
1980 if (RD->getNumVBases()) {
1981 if (Kind == CheckConstexprKind::CheckValid)
1982 return false;
1983
1984 Diag(Loc: NewFD->getLocation(), DiagID: diag::err_constexpr_virtual_base)
1985 << isa<CXXConstructorDecl>(Val: NewFD)
1986 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD->getNumVBases();
1987 for (const auto &I : RD->vbases())
1988 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here)
1989 << I.getSourceRange();
1990 return false;
1991 }
1992 }
1993
1994 if (!isa<CXXConstructorDecl>(Val: NewFD)) {
1995 // C++11 [dcl.constexpr]p3:
1996 // The definition of a constexpr function shall satisfy the following
1997 // constraints:
1998 // - it shall not be virtual; (removed in C++20)
1999 const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: NewFD);
2000 if (Method && Method->isVirtual()) {
2001 if (getLangOpts().CPlusPlus20) {
2002 if (Kind == CheckConstexprKind::Diagnose)
2003 Diag(Loc: Method->getLocation(), DiagID: diag::warn_cxx17_compat_constexpr_virtual);
2004 } else {
2005 if (Kind == CheckConstexprKind::CheckValid)
2006 return false;
2007
2008 Method = Method->getCanonicalDecl();
2009 Diag(Loc: Method->getLocation(), DiagID: diag::err_constexpr_virtual);
2010
2011 // If it's not obvious why this function is virtual, find an overridden
2012 // function which uses the 'virtual' keyword.
2013 const CXXMethodDecl *WrittenVirtual = Method;
2014 while (!WrittenVirtual->isVirtualAsWritten())
2015 WrittenVirtual = *WrittenVirtual->begin_overridden_methods();
2016 if (WrittenVirtual != Method)
2017 Diag(Loc: WrittenVirtual->getLocation(),
2018 DiagID: diag::note_overridden_virtual_function);
2019 return false;
2020 }
2021 }
2022
2023 // - its return type shall be a literal type; (removed in C++23)
2024 if (!getLangOpts().CPlusPlus23 &&
2025 !CheckConstexprReturnType(SemaRef&: *this, FD: NewFD, Kind))
2026 return false;
2027 }
2028
2029 if (auto *Dtor = dyn_cast<CXXDestructorDecl>(Val: NewFD)) {
2030 // A destructor can be constexpr only if the defaulted destructor could be;
2031 // we don't need to check the members and bases if we already know they all
2032 // have constexpr destructors. (removed in C++23)
2033 if (!getLangOpts().CPlusPlus23 &&
2034 !Dtor->getParent()->defaultedDestructorIsConstexpr()) {
2035 if (Kind == CheckConstexprKind::CheckValid)
2036 return false;
2037 if (!CheckConstexprDestructorSubobjects(SemaRef&: *this, DD: Dtor, Kind))
2038 return false;
2039 }
2040 }
2041
2042 // - each of its parameter types shall be a literal type; (removed in C++23)
2043 if (!getLangOpts().CPlusPlus23 &&
2044 !CheckConstexprParameterTypes(SemaRef&: *this, FD: NewFD, Kind))
2045 return false;
2046
2047 Stmt *Body = NewFD->getBody();
2048 assert(Body &&
2049 "CheckConstexprFunctionDefinition called on function with no body");
2050 return CheckConstexprFunctionBody(SemaRef&: *this, Dcl: NewFD, Body, Kind);
2051}
2052
2053/// Check the given declaration statement is legal within a constexpr function
2054/// body. C++11 [dcl.constexpr]p3,p4, and C++1y [dcl.constexpr]p3.
2055///
2056/// \return true if the body is OK (maybe only as an extension), false if we
2057/// have diagnosed a problem.
2058static bool CheckConstexprDeclStmt(Sema &SemaRef, const FunctionDecl *Dcl,
2059 DeclStmt *DS, SourceLocation &Cxx1yLoc,
2060 Sema::CheckConstexprKind Kind) {
2061 // C++11 [dcl.constexpr]p3 and p4:
2062 // The definition of a constexpr function(p3) or constructor(p4) [...] shall
2063 // contain only
2064 for (const auto *DclIt : DS->decls()) {
2065 switch (DclIt->getKind()) {
2066 case Decl::StaticAssert:
2067 case Decl::Using:
2068 case Decl::UsingShadow:
2069 case Decl::UsingDirective:
2070 case Decl::UnresolvedUsingTypename:
2071 case Decl::UnresolvedUsingValue:
2072 case Decl::UsingEnum:
2073 // - static_assert-declarations
2074 // - using-declarations,
2075 // - using-directives,
2076 // - using-enum-declaration
2077 continue;
2078
2079 case Decl::Typedef:
2080 case Decl::TypeAlias: {
2081 // - typedef declarations and alias-declarations that do not define
2082 // classes or enumerations,
2083 const auto *TN = cast<TypedefNameDecl>(Val: DclIt);
2084 if (TN->getUnderlyingType()->isVariablyModifiedType()) {
2085 // Don't allow variably-modified types in constexpr functions.
2086 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2087 TypeLoc TL = TN->getTypeSourceInfo()->getTypeLoc();
2088 SemaRef.Diag(Loc: TL.getBeginLoc(), DiagID: diag::err_constexpr_vla)
2089 << TL.getSourceRange() << TL.getType()
2090 << isa<CXXConstructorDecl>(Val: Dcl);
2091 }
2092 return false;
2093 }
2094 continue;
2095 }
2096
2097 case Decl::Enum:
2098 case Decl::CXXRecord:
2099 // C++1y allows types to be defined, not just declared.
2100 if (cast<TagDecl>(Val: DclIt)->isThisDeclarationADefinition()) {
2101 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2102 SemaRef.DiagCompat(Loc: DS->getBeginLoc(),
2103 CompatDiagId: diag_compat::constexpr_type_definition)
2104 << isa<CXXConstructorDecl>(Val: Dcl);
2105 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2106 return false;
2107 }
2108 }
2109 continue;
2110
2111 case Decl::EnumConstant:
2112 case Decl::IndirectField:
2113 case Decl::ParmVar:
2114 // These can only appear with other declarations which are banned in
2115 // C++11 and permitted in C++1y, so ignore them.
2116 continue;
2117
2118 case Decl::Var:
2119 case Decl::Decomposition: {
2120 // C++1y [dcl.constexpr]p3 allows anything except:
2121 // a definition of a variable of non-literal type or of static or
2122 // thread storage duration or [before C++2a] for which no
2123 // initialization is performed.
2124 const auto *VD = cast<VarDecl>(Val: DclIt);
2125 if (VD->isThisDeclarationADefinition()) {
2126 if (VD->isStaticLocal()) {
2127 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2128 SemaRef.DiagCompat(Loc: VD->getLocation(),
2129 CompatDiagId: diag_compat::constexpr_static_var)
2130 << isa<CXXConstructorDecl>(Val: Dcl)
2131 << (VD->getTLSKind() == VarDecl::TLS_Dynamic);
2132 } else if (!SemaRef.getLangOpts().CPlusPlus23) {
2133 return false;
2134 }
2135 }
2136 if (SemaRef.LangOpts.CPlusPlus23) {
2137 CheckLiteralType(SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2138 DiagID: diag::warn_cxx20_compat_constexpr_var,
2139 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl));
2140 } else if (CheckLiteralType(
2141 SemaRef, Kind, Loc: VD->getLocation(), T: VD->getType(),
2142 DiagID: diag::err_constexpr_local_var_non_literal_type,
2143 DiagArgs: isa<CXXConstructorDecl>(Val: Dcl))) {
2144 return false;
2145 }
2146 if (!VD->getType()->isDependentType() &&
2147 !VD->hasInit() && !VD->isCXXForRangeDecl()) {
2148 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2149 SemaRef.DiagCompat(Loc: VD->getLocation(),
2150 CompatDiagId: diag_compat::constexpr_local_var_no_init)
2151 << isa<CXXConstructorDecl>(Val: Dcl);
2152 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2153 return false;
2154 }
2155 continue;
2156 }
2157 }
2158 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2159 SemaRef.DiagCompat(Loc: VD->getLocation(), CompatDiagId: diag_compat::constexpr_local_var)
2160 << isa<CXXConstructorDecl>(Val: Dcl);
2161 } else if (!SemaRef.getLangOpts().CPlusPlus14) {
2162 return false;
2163 }
2164 continue;
2165 }
2166
2167 case Decl::NamespaceAlias:
2168 case Decl::Function:
2169 // These are disallowed in C++11 and permitted in C++1y. Allow them
2170 // everywhere as an extension.
2171 if (!Cxx1yLoc.isValid())
2172 Cxx1yLoc = DS->getBeginLoc();
2173 continue;
2174
2175 default:
2176 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2177 SemaRef.Diag(Loc: DS->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2178 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2179 }
2180 return false;
2181 }
2182 }
2183
2184 return true;
2185}
2186
2187/// Check that the given field is initialized within a constexpr constructor.
2188///
2189/// \param Dcl The constexpr constructor being checked.
2190/// \param Field The field being checked. This may be a member of an anonymous
2191/// struct or union nested within the class being checked.
2192/// \param Inits All declarations, including anonymous struct/union members and
2193/// indirect members, for which any initialization was provided.
2194/// \param Diagnosed Whether we've emitted the error message yet. Used to attach
2195/// multiple notes for different members to the same error.
2196/// \param Kind Whether we're diagnosing a constructor as written or determining
2197/// whether the formal requirements are satisfied.
2198/// \return \c false if we're checking for validity and the constructor does
2199/// not satisfy the requirements on a constexpr constructor.
2200static bool CheckConstexprCtorInitializer(Sema &SemaRef,
2201 const FunctionDecl *Dcl,
2202 FieldDecl *Field,
2203 llvm::SmallPtrSet<Decl *, 16> &Inits,
2204 bool &Diagnosed,
2205 Sema::CheckConstexprKind Kind) {
2206 // In C++20 onwards, there's nothing to check for validity.
2207 if (Kind == Sema::CheckConstexprKind::CheckValid &&
2208 SemaRef.getLangOpts().CPlusPlus20)
2209 return true;
2210
2211 if (Field->isInvalidDecl())
2212 return true;
2213
2214 if (Field->isUnnamedBitField())
2215 return true;
2216
2217 // Anonymous unions with no variant members and empty anonymous structs do not
2218 // need to be explicitly initialized. FIXME: Anonymous structs that contain no
2219 // indirect fields don't need initializing.
2220 if (Field->isAnonymousStructOrUnion() &&
2221 (Field->getType()->isUnionType()
2222 ? !Field->getType()->getAsCXXRecordDecl()->hasVariantMembers()
2223 : Field->getType()->getAsCXXRecordDecl()->isEmpty()))
2224 return true;
2225
2226 if (!Inits.count(Ptr: Field)) {
2227 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2228 if (!Diagnosed) {
2229 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2230 CompatDiagId: diag_compat::constexpr_ctor_missing_init);
2231 Diagnosed = true;
2232 }
2233 SemaRef.Diag(Loc: Field->getLocation(),
2234 DiagID: diag::note_constexpr_ctor_missing_init);
2235 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2236 return false;
2237 }
2238 } else if (Field->isAnonymousStructOrUnion()) {
2239 const auto *RD = Field->getType()->castAsRecordDecl();
2240 for (auto *I : RD->fields())
2241 // If an anonymous union contains an anonymous struct of which any member
2242 // is initialized, all members must be initialized.
2243 if (!RD->isUnion() || Inits.count(Ptr: I))
2244 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2245 Kind))
2246 return false;
2247 }
2248 return true;
2249}
2250
2251/// Check the provided statement is allowed in a constexpr function
2252/// definition.
2253static bool
2254CheckConstexprFunctionStmt(Sema &SemaRef, const FunctionDecl *Dcl, Stmt *S,
2255 SmallVectorImpl<SourceLocation> &ReturnStmts,
2256 SourceLocation &Cxx1yLoc, SourceLocation &Cxx2aLoc,
2257 SourceLocation &Cxx2bLoc,
2258 Sema::CheckConstexprKind Kind) {
2259 // - its function-body shall be [...] a compound-statement that contains only
2260 switch (S->getStmtClass()) {
2261 case Stmt::NullStmtClass:
2262 // - null statements,
2263 return true;
2264
2265 case Stmt::DeclStmtClass: {
2266 auto *DS = cast<DeclStmt>(Val: S);
2267
2268 // Expansion statement 'declarations' have substatements, so we need to
2269 // handle them separately.
2270 if (DS->isSingleDecl()) {
2271 if (auto *ESD = dyn_cast<CXXExpansionStmtDecl>(Val: DS->getSingleDecl())) {
2272 // Don't check unexpanded expansion statements.
2273 if (!ESD->getInstantiations())
2274 return true;
2275 for (auto *BodyIt : ESD->getInstantiations()->getInstantiations()) {
2276 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2277 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2278 return false;
2279 }
2280 return true;
2281 }
2282 }
2283
2284 // - static_assert-declarations
2285 // - using-declarations,
2286 // - using-directives,
2287 // - typedef declarations and alias-declarations that do not define
2288 // classes or enumerations,
2289 if (!CheckConstexprDeclStmt(SemaRef, Dcl, DS, Cxx1yLoc, Kind))
2290 return false;
2291 return true;
2292 }
2293
2294 case Stmt::ReturnStmtClass:
2295 // - and exactly one return statement;
2296 if (isa<CXXConstructorDecl>(Val: Dcl)) {
2297 // C++1y allows return statements in constexpr constructors.
2298 if (!Cxx1yLoc.isValid())
2299 Cxx1yLoc = S->getBeginLoc();
2300 return true;
2301 }
2302
2303 ReturnStmts.push_back(Elt: S->getBeginLoc());
2304 return true;
2305
2306 case Stmt::AttributedStmtClass:
2307 // Attributes on a statement don't affect its formal kind and hence don't
2308 // affect its validity in a constexpr function.
2309 return CheckConstexprFunctionStmt(
2310 SemaRef, Dcl, S: cast<AttributedStmt>(Val: S)->getSubStmt(), ReturnStmts,
2311 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind);
2312
2313 case Stmt::CompoundStmtClass: {
2314 // C++1y allows compound-statements.
2315 if (!Cxx1yLoc.isValid())
2316 Cxx1yLoc = S->getBeginLoc();
2317
2318 CompoundStmt *CompStmt = cast<CompoundStmt>(Val: S);
2319 for (auto *BodyIt : CompStmt->body()) {
2320 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: BodyIt, ReturnStmts,
2321 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2322 return false;
2323 }
2324 return true;
2325 }
2326
2327 case Stmt::IfStmtClass: {
2328 // C++1y allows if-statements.
2329 if (!Cxx1yLoc.isValid())
2330 Cxx1yLoc = S->getBeginLoc();
2331
2332 IfStmt *If = cast<IfStmt>(Val: S);
2333 if (!CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getThen(), ReturnStmts,
2334 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2335 return false;
2336 if (If->getElse() &&
2337 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: If->getElse(), ReturnStmts,
2338 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2339 return false;
2340 return true;
2341 }
2342
2343 case Stmt::WhileStmtClass:
2344 case Stmt::DoStmtClass:
2345 case Stmt::ForStmtClass:
2346 case Stmt::CXXForRangeStmtClass:
2347 case Stmt::ContinueStmtClass:
2348 // C++1y allows all of these. We don't allow them as extensions in C++11,
2349 // because they don't make sense without variable mutation.
2350 if (!SemaRef.getLangOpts().CPlusPlus14)
2351 break;
2352 if (!Cxx1yLoc.isValid())
2353 Cxx1yLoc = S->getBeginLoc();
2354 for (Stmt *SubStmt : S->children()) {
2355 if (SubStmt &&
2356 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2357 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2358 return false;
2359 }
2360 return true;
2361
2362 case Stmt::SwitchStmtClass:
2363 case Stmt::CaseStmtClass:
2364 case Stmt::DefaultStmtClass:
2365 case Stmt::BreakStmtClass:
2366 // C++1y allows switch-statements, and since they don't need variable
2367 // mutation, we can reasonably allow them in C++11 as an extension.
2368 if (!Cxx1yLoc.isValid())
2369 Cxx1yLoc = S->getBeginLoc();
2370 for (Stmt *SubStmt : S->children()) {
2371 if (SubStmt &&
2372 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2373 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2374 return false;
2375 }
2376 return true;
2377
2378 case Stmt::LabelStmtClass:
2379 case Stmt::GotoStmtClass:
2380 case Stmt::IndirectGotoStmtClass:
2381 if (Cxx2bLoc.isInvalid())
2382 Cxx2bLoc = S->getBeginLoc();
2383 for (Stmt *SubStmt : S->children()) {
2384 if (SubStmt &&
2385 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2386 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2387 return false;
2388 }
2389 return true;
2390
2391 case Stmt::GCCAsmStmtClass:
2392 case Stmt::MSAsmStmtClass:
2393 // C++2a allows inline assembly statements.
2394 case Stmt::CXXTryStmtClass:
2395 if (Cxx2aLoc.isInvalid())
2396 Cxx2aLoc = S->getBeginLoc();
2397 for (Stmt *SubStmt : S->children()) {
2398 if (SubStmt &&
2399 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2400 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2401 return false;
2402 }
2403 return true;
2404
2405 case Stmt::CXXCatchStmtClass:
2406 // Do not bother checking the language mode (already covered by the
2407 // try block check).
2408 if (!CheckConstexprFunctionStmt(
2409 SemaRef, Dcl, S: cast<CXXCatchStmt>(Val: S)->getHandlerBlock(), ReturnStmts,
2410 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2411 return false;
2412 return true;
2413
2414 default:
2415 if (!isa<Expr>(Val: S))
2416 break;
2417
2418 // C++1y allows expression-statements.
2419 if (!Cxx1yLoc.isValid())
2420 Cxx1yLoc = S->getBeginLoc();
2421 return true;
2422 }
2423
2424 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2425 SemaRef.Diag(Loc: S->getBeginLoc(), DiagID: diag::err_constexpr_body_invalid_stmt)
2426 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval();
2427 }
2428 return false;
2429}
2430
2431/// Check the body for the given constexpr function declaration only contains
2432/// the permitted types of statement. C++11 [dcl.constexpr]p3,p4.
2433///
2434/// \return true if the body is OK, false if we have found or diagnosed a
2435/// problem.
2436static bool CheckConstexprFunctionBody(Sema &SemaRef, const FunctionDecl *Dcl,
2437 Stmt *Body,
2438 Sema::CheckConstexprKind Kind) {
2439 SmallVector<SourceLocation, 4> ReturnStmts;
2440
2441 if (isa<CXXTryStmt>(Val: Body)) {
2442 // C++11 [dcl.constexpr]p3:
2443 // The definition of a constexpr function shall satisfy the following
2444 // constraints: [...]
2445 // - its function-body shall be = delete, = default, or a
2446 // compound-statement
2447 //
2448 // C++11 [dcl.constexpr]p4:
2449 // In the definition of a constexpr constructor, [...]
2450 // - its function-body shall not be a function-try-block;
2451 //
2452 // This restriction is lifted in C++2a, as long as inner statements also
2453 // apply the general constexpr rules.
2454 switch (Kind) {
2455 case Sema::CheckConstexprKind::CheckValid:
2456 if (!SemaRef.getLangOpts().CPlusPlus20)
2457 return false;
2458 break;
2459
2460 case Sema::CheckConstexprKind::Diagnose:
2461 SemaRef.DiagCompat(Loc: Body->getBeginLoc(),
2462 CompatDiagId: diag_compat::constexpr_function_try_block)
2463 << isa<CXXConstructorDecl>(Val: Dcl);
2464 break;
2465 }
2466 }
2467
2468 // - its function-body shall be [...] a compound-statement that contains only
2469 // [... list of cases ...]
2470 //
2471 // Note that walking the children here is enough to properly check for
2472 // CompoundStmt and CXXTryStmt body.
2473 SourceLocation Cxx1yLoc, Cxx2aLoc, Cxx2bLoc;
2474 for (Stmt *SubStmt : Body->children()) {
2475 if (SubStmt &&
2476 !CheckConstexprFunctionStmt(SemaRef, Dcl, S: SubStmt, ReturnStmts,
2477 Cxx1yLoc, Cxx2aLoc, Cxx2bLoc, Kind))
2478 return false;
2479 }
2480
2481 if (Kind == Sema::CheckConstexprKind::CheckValid) {
2482 // If this is only valid as an extension, report that we don't satisfy the
2483 // constraints of the current language.
2484 if ((Cxx2bLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus23) ||
2485 (Cxx2aLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus20) ||
2486 (Cxx1yLoc.isValid() && !SemaRef.getLangOpts().CPlusPlus17))
2487 return false;
2488 } else if (Cxx2bLoc.isValid()) {
2489 SemaRef.DiagCompat(Loc: Cxx2bLoc, CompatDiagId: diag_compat::cxx23_constexpr_body_invalid_stmt)
2490 << isa<CXXConstructorDecl>(Val: Dcl);
2491 } else if (Cxx2aLoc.isValid()) {
2492 SemaRef.DiagCompat(Loc: Cxx2aLoc, CompatDiagId: diag_compat::cxx20_constexpr_body_invalid_stmt)
2493 << isa<CXXConstructorDecl>(Val: Dcl);
2494 } else if (Cxx1yLoc.isValid()) {
2495 SemaRef.DiagCompat(Loc: Cxx1yLoc, CompatDiagId: diag_compat::cxx14_constexpr_body_invalid_stmt)
2496 << isa<CXXConstructorDecl>(Val: Dcl);
2497 }
2498
2499 if (const CXXConstructorDecl *Constructor
2500 = dyn_cast<CXXConstructorDecl>(Val: Dcl)) {
2501 const CXXRecordDecl *RD = Constructor->getParent();
2502 // DR1359:
2503 // - every non-variant non-static data member and base class sub-object
2504 // shall be initialized;
2505 // DR1460:
2506 // - if the class is a union having variant members, exactly one of them
2507 // shall be initialized;
2508 if (RD->isUnion()) {
2509 if (Constructor->getNumCtorInitializers() == 0 &&
2510 RD->hasVariantMembers()) {
2511 if (Kind == Sema::CheckConstexprKind::Diagnose) {
2512 SemaRef.DiagCompat(Loc: Dcl->getLocation(),
2513 CompatDiagId: diag_compat::constexpr_union_ctor_no_init);
2514 } else if (!SemaRef.getLangOpts().CPlusPlus20) {
2515 return false;
2516 }
2517 }
2518 } else if (!Constructor->isDependentContext() &&
2519 !Constructor->isDelegatingConstructor()) {
2520 // Skip detailed checking if we have enough initializers, and we would
2521 // allow at most one initializer per member.
2522 bool AnyAnonStructUnionMembers = false;
2523 unsigned Fields = 0;
2524 for (CXXRecordDecl::field_iterator I = RD->field_begin(),
2525 E = RD->field_end(); I != E; ++I, ++Fields) {
2526 if (I->isAnonymousStructOrUnion()) {
2527 AnyAnonStructUnionMembers = true;
2528 break;
2529 }
2530 }
2531 // DR1460:
2532 // - if the class is a union-like class, but is not a union, for each of
2533 // its anonymous union members having variant members, exactly one of
2534 // them shall be initialized;
2535 if (AnyAnonStructUnionMembers ||
2536 Constructor->getNumCtorInitializers() != RD->getNumBases() + Fields) {
2537 // Check initialization of non-static data members. Base classes are
2538 // always initialized so do not need to be checked. Dependent bases
2539 // might not have initializers in the member initializer list.
2540 llvm::SmallPtrSet<Decl *, 16> Inits;
2541 for (const auto *I: Constructor->inits()) {
2542 if (FieldDecl *FD = I->getMember())
2543 Inits.insert(Ptr: FD);
2544 else if (IndirectFieldDecl *ID = I->getIndirectMember())
2545 Inits.insert(I: ID->chain_begin(), E: ID->chain_end());
2546 }
2547
2548 bool Diagnosed = false;
2549 for (auto *I : RD->fields())
2550 if (!CheckConstexprCtorInitializer(SemaRef, Dcl, Field: I, Inits, Diagnosed,
2551 Kind))
2552 return false;
2553 }
2554 }
2555 } else {
2556 if (ReturnStmts.empty()) {
2557 switch (Kind) {
2558 case Sema::CheckConstexprKind::Diagnose:
2559 if (!CheckConstexprMissingReturn(SemaRef, Dcl))
2560 return false;
2561 break;
2562
2563 case Sema::CheckConstexprKind::CheckValid:
2564 // The formal requirements don't include this rule in C++14, even
2565 // though the "must be able to produce a constant expression" rules
2566 // still imply it in some cases.
2567 if (!SemaRef.getLangOpts().CPlusPlus14)
2568 return false;
2569 break;
2570 }
2571 } else if (ReturnStmts.size() > 1) {
2572 switch (Kind) {
2573 case Sema::CheckConstexprKind::Diagnose:
2574 SemaRef.DiagCompat(Loc: ReturnStmts.back(),
2575 CompatDiagId: diag_compat::constexpr_body_multiple_return);
2576 for (unsigned I = 0; I < ReturnStmts.size() - 1; ++I)
2577 SemaRef.Diag(Loc: ReturnStmts[I],
2578 DiagID: diag::note_constexpr_body_previous_return);
2579 break;
2580
2581 case Sema::CheckConstexprKind::CheckValid:
2582 if (!SemaRef.getLangOpts().CPlusPlus14)
2583 return false;
2584 break;
2585 }
2586 }
2587 }
2588
2589 // C++11 [dcl.constexpr]p5:
2590 // if no function argument values exist such that the function invocation
2591 // substitution would produce a constant expression, the program is
2592 // ill-formed; no diagnostic required.
2593 // C++11 [dcl.constexpr]p3:
2594 // - every constructor call and implicit conversion used in initializing the
2595 // return value shall be one of those allowed in a constant expression.
2596 // C++11 [dcl.constexpr]p4:
2597 // - every constructor involved in initializing non-static data members and
2598 // base class sub-objects shall be a constexpr constructor.
2599 //
2600 // Note that this rule is distinct from the "requirements for a constexpr
2601 // function", so is not checked in CheckValid mode. Because the check for
2602 // constexpr potential is expensive, skip the check if the diagnostic is
2603 // disabled, the function is declared in a system header, or we're in C++23
2604 // or later mode (see https://wg21.link/P2448).
2605 bool SkipCheck =
2606 !SemaRef.getLangOpts().CheckConstexprFunctionBodies ||
2607 SemaRef.getSourceManager().isInSystemHeader(Loc: Dcl->getLocation()) ||
2608 SemaRef.getDiagnostics().isIgnored(
2609 DiagID: diag::ext_constexpr_function_never_constant_expr, Loc: Dcl->getLocation());
2610 SmallVector<PartialDiagnosticAt, 8> Diags;
2611 if (Kind == Sema::CheckConstexprKind::Diagnose && !SkipCheck &&
2612 !Expr::isPotentialConstantExpr(FD: Dcl, Diags)) {
2613 SemaRef.Diag(Loc: Dcl->getLocation(),
2614 DiagID: diag::ext_constexpr_function_never_constant_expr)
2615 << isa<CXXConstructorDecl>(Val: Dcl) << Dcl->isConsteval()
2616 << Dcl->getNameInfo().getSourceRange();
2617 for (const auto &Diag : Diags)
2618 SemaRef.Diag(Loc: Diag.first, PD: Diag.second);
2619 // Don't return false here: we allow this for compatibility in
2620 // system headers.
2621 }
2622
2623 return true;
2624}
2625
2626static bool CheckConstexprMissingReturn(Sema &SemaRef,
2627 const FunctionDecl *Dcl) {
2628 bool IsVoidOrDependentType = Dcl->getReturnType()->isVoidType() ||
2629 Dcl->getReturnType()->isDependentType();
2630 // Skip emitting a missing return error diagnostic for non-void functions
2631 // since C++23 no longer mandates constexpr functions to yield constant
2632 // expressions.
2633 if (SemaRef.getLangOpts().CPlusPlus23 && !IsVoidOrDependentType)
2634 return true;
2635
2636 // C++14 doesn't require constexpr functions to contain a 'return'
2637 // statement. We still do, unless the return type might be void, because
2638 // otherwise if there's no return statement, the function cannot
2639 // be used in a core constant expression.
2640 bool OK = SemaRef.getLangOpts().CPlusPlus14 && IsVoidOrDependentType;
2641 SemaRef.Diag(Loc: Dcl->getLocation(),
2642 DiagID: OK ? diag::warn_cxx11_compat_constexpr_body_no_return
2643 : diag::err_constexpr_body_no_return)
2644 << Dcl->isConsteval();
2645 return OK;
2646}
2647
2648bool Sema::CheckImmediateEscalatingFunctionDefinition(
2649 FunctionDecl *FD, const sema::FunctionScopeInfo *FSI) {
2650 if (!getLangOpts().CPlusPlus20 || !FD->isImmediateEscalating())
2651 return true;
2652 FD->setBodyContainsImmediateEscalatingExpressions(
2653 FSI->FoundImmediateEscalatingExpression);
2654 if (FSI->FoundImmediateEscalatingExpression) {
2655 auto it = UndefinedButUsed.find(Key: FD->getCanonicalDecl());
2656 if (it != UndefinedButUsed.end()) {
2657 Diag(Loc: it->second, DiagID: diag::err_immediate_function_used_before_definition)
2658 << it->first;
2659 Diag(Loc: FD->getLocation(), DiagID: diag::note_defined_here) << FD;
2660 if (FD->isImmediateFunction() && !FD->isConsteval())
2661 DiagnoseImmediateEscalatingReason(FD);
2662 return false;
2663 }
2664 }
2665 return true;
2666}
2667
2668void Sema::DiagnoseImmediateEscalatingReason(FunctionDecl *FD) {
2669 assert(FD->isImmediateEscalating() && !FD->isConsteval() &&
2670 "expected an immediate function");
2671 assert(FD->hasBody() && "expected the function to have a body");
2672 struct ImmediateEscalatingExpressionsVisitor : DynamicRecursiveASTVisitor {
2673 Sema &SemaRef;
2674
2675 const FunctionDecl *ImmediateFn;
2676 bool ImmediateFnIsConstructor;
2677 CXXConstructorDecl *CurrentConstructor = nullptr;
2678 CXXCtorInitializer *CurrentInit = nullptr;
2679
2680 ImmediateEscalatingExpressionsVisitor(Sema &SemaRef, FunctionDecl *FD)
2681 : SemaRef(SemaRef), ImmediateFn(FD),
2682 ImmediateFnIsConstructor(isa<CXXConstructorDecl>(Val: FD)) {
2683 ShouldVisitImplicitCode = true;
2684 ShouldVisitLambdaBody = false;
2685 }
2686
2687 void Diag(const Expr *E, const FunctionDecl *Fn, bool IsCall) {
2688 SourceLocation Loc = E->getBeginLoc();
2689 SourceRange Range = E->getSourceRange();
2690 if (CurrentConstructor && CurrentInit) {
2691 Loc = CurrentConstructor->getLocation();
2692 Range = CurrentInit->isWritten() ? CurrentInit->getSourceRange()
2693 : SourceRange();
2694 }
2695
2696 FieldDecl* InitializedField = CurrentInit ? CurrentInit->getAnyMember() : nullptr;
2697
2698 SemaRef.Diag(Loc, DiagID: diag::note_immediate_function_reason)
2699 << ImmediateFn << Fn << Fn->isConsteval() << IsCall
2700 << isa<CXXConstructorDecl>(Val: Fn) << ImmediateFnIsConstructor
2701 << (InitializedField != nullptr)
2702 << (CurrentInit && !CurrentInit->isWritten())
2703 << InitializedField << Range;
2704 }
2705 bool TraverseCallExpr(CallExpr *E) override {
2706 if (const auto *DR =
2707 dyn_cast<DeclRefExpr>(Val: E->getCallee()->IgnoreImplicit());
2708 DR && DR->isImmediateEscalating()) {
2709 Diag(E, Fn: E->getDirectCallee(), /*IsCall=*/true);
2710 return false;
2711 }
2712
2713 for (Expr *A : E->arguments())
2714 if (!TraverseStmt(S: A))
2715 return false;
2716
2717 return true;
2718 }
2719
2720 bool VisitDeclRefExpr(DeclRefExpr *E) override {
2721 if (const auto *ReferencedFn = dyn_cast<FunctionDecl>(Val: E->getDecl());
2722 ReferencedFn && E->isImmediateEscalating()) {
2723 Diag(E, Fn: ReferencedFn, /*IsCall=*/false);
2724 return false;
2725 }
2726
2727 return true;
2728 }
2729
2730 bool VisitCXXConstructExpr(CXXConstructExpr *E) override {
2731 CXXConstructorDecl *D = E->getConstructor();
2732 if (E->isImmediateEscalating()) {
2733 Diag(E, Fn: D, /*IsCall=*/true);
2734 return false;
2735 }
2736 return true;
2737 }
2738
2739 bool TraverseConstructorInitializer(CXXCtorInitializer *Init) override {
2740 llvm::SaveAndRestore RAII(CurrentInit, Init);
2741 return DynamicRecursiveASTVisitor::TraverseConstructorInitializer(Init);
2742 }
2743
2744 bool TraverseCXXConstructorDecl(CXXConstructorDecl *Ctr) override {
2745 llvm::SaveAndRestore RAII(CurrentConstructor, Ctr);
2746 return DynamicRecursiveASTVisitor::TraverseCXXConstructorDecl(D: Ctr);
2747 }
2748
2749 bool TraverseType(QualType T, bool TraverseQualifier) override {
2750 return true;
2751 }
2752 bool VisitBlockExpr(BlockExpr *T) override { return true; }
2753
2754 } Visitor(*this, FD);
2755 Visitor.TraverseDecl(D: FD);
2756}
2757
2758CXXRecordDecl *Sema::getCurrentClass(Scope *, const CXXScopeSpec *SS) {
2759 assert(getLangOpts().CPlusPlus && "No class names in C!");
2760
2761 if (SS && SS->isInvalid())
2762 return nullptr;
2763
2764 if (SS && SS->isNotEmpty()) {
2765 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2766 return dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2767 }
2768
2769 return dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2770}
2771
2772bool Sema::isCurrentClassName(const IdentifierInfo &II, Scope *S,
2773 const CXXScopeSpec *SS) {
2774 CXXRecordDecl *CurDecl = getCurrentClass(S, SS);
2775 return CurDecl && &II == CurDecl->getIdentifier();
2776}
2777
2778bool Sema::isCurrentClassNameTypo(IdentifierInfo *&II, const CXXScopeSpec *SS) {
2779 assert(getLangOpts().CPlusPlus && "No class names in C!");
2780
2781 if (!getLangOpts().SpellChecking)
2782 return false;
2783
2784 CXXRecordDecl *CurDecl;
2785 if (SS && SS->isSet() && !SS->isInvalid()) {
2786 DeclContext *DC = computeDeclContext(SS: *SS, EnteringContext: true);
2787 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: DC);
2788 } else
2789 CurDecl = dyn_cast_or_null<CXXRecordDecl>(Val: CurContext);
2790
2791 if (CurDecl && CurDecl->getIdentifier() && II != CurDecl->getIdentifier() &&
2792 3 * II->getName().edit_distance(Other: CurDecl->getIdentifier()->getName())
2793 < II->getLength()) {
2794 II = CurDecl->getIdentifier();
2795 return true;
2796 }
2797
2798 return false;
2799}
2800
2801CXXBaseSpecifier *Sema::CheckBaseSpecifier(CXXRecordDecl *Class,
2802 SourceRange SpecifierRange,
2803 bool Virtual, AccessSpecifier Access,
2804 TypeSourceInfo *TInfo,
2805 SourceLocation EllipsisLoc) {
2806 QualType BaseType = TInfo->getType();
2807 SourceLocation BaseLoc = TInfo->getTypeLoc().getBeginLoc();
2808 if (BaseType->containsErrors()) {
2809 // Already emitted a diagnostic when parsing the error type.
2810 return nullptr;
2811 }
2812
2813 if (EllipsisLoc.isValid() && !BaseType->containsUnexpandedParameterPack()) {
2814 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
2815 << TInfo->getTypeLoc().getSourceRange();
2816 EllipsisLoc = SourceLocation();
2817 }
2818
2819 auto *BaseDecl =
2820 dyn_cast_if_present<CXXRecordDecl>(Val: computeDeclContext(T: BaseType));
2821 // C++ [class.derived.general]p2:
2822 // A class-or-decltype shall denote a (possibly cv-qualified) class type
2823 // that is not an incompletely defined class; any cv-qualifiers are
2824 // ignored.
2825 if (BaseDecl) {
2826 // C++ [class.union.general]p4:
2827 // [...] A union shall not be used as a base class.
2828 if (BaseDecl->isUnion()) {
2829 Diag(Loc: BaseLoc, DiagID: diag::err_union_as_base_class) << SpecifierRange;
2830 return nullptr;
2831 }
2832
2833 if (BaseType.hasQualifiers()) {
2834 std::string Quals =
2835 BaseType.getQualifiers().getAsString(Policy: Context.getPrintingPolicy());
2836 Diag(Loc: BaseLoc, DiagID: diag::warn_qual_base_type)
2837 << Quals << llvm::count(Range&: Quals, Element: ' ') + 1 << BaseType;
2838 Diag(Loc: BaseLoc, DiagID: diag::note_base_class_specified_here) << BaseType;
2839 }
2840
2841 // For the MS ABI, propagate DLL attributes to base class templates.
2842 if (Context.getTargetInfo().getCXXABI().isMicrosoft() ||
2843 Context.getTargetInfo().getTriple().isPS()) {
2844 if (Attr *ClassAttr = getDLLAttr(D: Class)) {
2845 if (auto *BaseSpec =
2846 dyn_cast<ClassTemplateSpecializationDecl>(Val: BaseDecl)) {
2847 propagateDLLAttrToBaseClassTemplate(Class, ClassAttr, BaseTemplateSpec: BaseSpec,
2848 BaseLoc);
2849 }
2850 }
2851 }
2852
2853 if (RequireCompleteType(Loc: BaseLoc, T: BaseType, DiagID: diag::err_incomplete_base_class,
2854 Args: SpecifierRange)) {
2855 Class->setInvalidDecl();
2856 return nullptr;
2857 }
2858
2859 BaseDecl = BaseDecl->getDefinition();
2860 assert(BaseDecl && "Base type is not incomplete, but has no definition");
2861
2862 // Microsoft docs say:
2863 // "If a base-class has a code_seg attribute, derived classes must have the
2864 // same attribute."
2865 const auto *BaseCSA = BaseDecl->getAttr<CodeSegAttr>();
2866 const auto *DerivedCSA = Class->getAttr<CodeSegAttr>();
2867 if ((DerivedCSA || BaseCSA) &&
2868 (!BaseCSA || !DerivedCSA ||
2869 BaseCSA->getName() != DerivedCSA->getName())) {
2870 Diag(Loc: Class->getLocation(), DiagID: diag::err_mismatched_code_seg_base);
2871 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_base_class_specified_here)
2872 << BaseDecl;
2873 return nullptr;
2874 }
2875
2876 // A class which contains a flexible array member is not suitable for use as
2877 // a base class:
2878 // - If the layout determines that a base comes before another base,
2879 // the flexible array member would index into the subsequent base.
2880 // - If the layout determines that base comes before the derived class,
2881 // the flexible array member would index into the derived class.
2882 if (BaseDecl->hasFlexibleArrayMember()) {
2883 Diag(Loc: BaseLoc, DiagID: diag::err_base_class_has_flexible_array_member)
2884 << BaseDecl->getDeclName();
2885 return nullptr;
2886 }
2887
2888 // C++ [class]p3:
2889 // If a class is marked final and it appears as a base-type-specifier in
2890 // base-clause, the program is ill-formed.
2891 if (FinalAttr *FA = BaseDecl->getAttr<FinalAttr>()) {
2892 Diag(Loc: BaseLoc, DiagID: diag::err_class_marked_final_used_as_base)
2893 << BaseDecl->getDeclName() << FA->isSpelledAsSealed();
2894 Diag(Loc: BaseDecl->getLocation(), DiagID: diag::note_entity_declared_at)
2895 << BaseDecl->getDeclName() << FA->getRange();
2896 return nullptr;
2897 }
2898
2899 // If the base class is invalid the derived class is as well.
2900 if (BaseDecl->isInvalidDecl())
2901 Class->setInvalidDecl();
2902 } else if (BaseType->isDependentType()) {
2903 // Make sure that we don't make an ill-formed AST where the type of the
2904 // Class is non-dependent and its attached base class specifier is an
2905 // dependent type, which violates invariants in many clang code paths (e.g.
2906 // constexpr evaluator). If this case happens (in errory-recovery mode), we
2907 // explicitly mark the Class decl invalid. The diagnostic was already
2908 // emitted.
2909 if (!Class->isDependentContext())
2910 Class->setInvalidDecl();
2911 } else {
2912 // The base class is some non-dependent non-class type.
2913 Diag(Loc: BaseLoc, DiagID: diag::err_base_must_be_class) << SpecifierRange;
2914 return nullptr;
2915 }
2916
2917 // In HLSL, unspecified class access is public rather than private.
2918 if (getLangOpts().HLSL && Class->getTagKind() == TagTypeKind::Class &&
2919 Access == AS_none)
2920 Access = AS_public;
2921
2922 // Create the base specifier.
2923 return new (Context) CXXBaseSpecifier(
2924 SpecifierRange, Virtual, Class->getTagKind() == TagTypeKind::Class,
2925 Access, TInfo, EllipsisLoc);
2926}
2927
2928BaseResult Sema::ActOnBaseSpecifier(Decl *classdecl, SourceRange SpecifierRange,
2929 const ParsedAttributesView &Attributes,
2930 bool Virtual, AccessSpecifier Access,
2931 ParsedType basetype, SourceLocation BaseLoc,
2932 SourceLocation EllipsisLoc) {
2933 if (!classdecl)
2934 return true;
2935
2936 AdjustDeclIfTemplate(Decl&: classdecl);
2937 CXXRecordDecl *Class = dyn_cast<CXXRecordDecl>(Val: classdecl);
2938 if (!Class)
2939 return true;
2940
2941 // We haven't yet attached the base specifiers.
2942 Class->setIsParsingBaseSpecifiers();
2943
2944 // We do not support any C++11 attributes on base-specifiers yet.
2945 // Diagnose any attributes we see.
2946 for (const ParsedAttr &AL : Attributes) {
2947 if (AL.isInvalid() || AL.getKind() == ParsedAttr::IgnoredAttribute)
2948 continue;
2949 if (AL.getKind() == ParsedAttr::UnknownAttribute)
2950 DiagnoseUnknownAttribute(AL);
2951 else
2952 Diag(Loc: AL.getLoc(), DiagID: diag::err_base_specifier_attribute)
2953 << AL << AL.isRegularKeywordAttribute() << AL.getRange();
2954 }
2955
2956 TypeSourceInfo *TInfo = nullptr;
2957 GetTypeFromParser(Ty: basetype, TInfo: &TInfo);
2958
2959 if (EllipsisLoc.isInvalid() &&
2960 DiagnoseUnexpandedParameterPack(Loc: SpecifierRange.getBegin(), T: TInfo,
2961 UPPC: UPPC_BaseType))
2962 return true;
2963
2964 // C++ [class.union.general]p4:
2965 // [...] A union shall not have base classes.
2966 if (Class->isUnion()) {
2967 Diag(Loc: Class->getLocation(), DiagID: diag::err_base_clause_on_union)
2968 << SpecifierRange;
2969 return true;
2970 }
2971
2972 if (CXXBaseSpecifier *BaseSpec = CheckBaseSpecifier(Class, SpecifierRange,
2973 Virtual, Access, TInfo,
2974 EllipsisLoc))
2975 return BaseSpec;
2976
2977 Class->setInvalidDecl();
2978 return true;
2979}
2980
2981/// Use small set to collect indirect bases. As this is only used
2982/// locally, there's no need to abstract the small size parameter.
2983typedef llvm::SmallPtrSet<QualType, 4> IndirectBaseSet;
2984
2985/// Recursively add the bases of Type. Don't add Type itself.
2986static void
2987NoteIndirectBases(ASTContext &Context, IndirectBaseSet &Set,
2988 const QualType &Type)
2989{
2990 // Even though the incoming type is a base, it might not be
2991 // a class -- it could be a template parm, for instance.
2992 if (const auto *Decl = Type->getAsCXXRecordDecl()) {
2993 // Iterate over its bases.
2994 for (const auto &BaseSpec : Decl->bases()) {
2995 QualType Base = Context.getCanonicalType(T: BaseSpec.getType())
2996 .getUnqualifiedType();
2997 if (Set.insert(Ptr: Base).second)
2998 // If we've not already seen it, recurse.
2999 NoteIndirectBases(Context, Set, Type: Base);
3000 }
3001 }
3002}
3003
3004bool Sema::AttachBaseSpecifiers(CXXRecordDecl *Class,
3005 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3006 if (Bases.empty())
3007 return false;
3008
3009 // Used to keep track of which base types we have already seen, so
3010 // that we can properly diagnose redundant direct base types. Note
3011 // that the key is always the unqualified canonical type of the base
3012 // class.
3013 std::map<QualType, CXXBaseSpecifier*, QualTypeOrdering> KnownBaseTypes;
3014
3015 // Used to track indirect bases so we can see if a direct base is
3016 // ambiguous.
3017 IndirectBaseSet IndirectBaseTypes;
3018
3019 // Copy non-redundant base specifiers into permanent storage.
3020 unsigned NumGoodBases = 0;
3021 bool Invalid = false;
3022 for (unsigned idx = 0; idx < Bases.size(); ++idx) {
3023 QualType NewBaseType
3024 = Context.getCanonicalType(T: Bases[idx]->getType());
3025 NewBaseType = NewBaseType.getLocalUnqualifiedType();
3026
3027 CXXBaseSpecifier *&KnownBase = KnownBaseTypes[NewBaseType];
3028 if (KnownBase) {
3029 // C++ [class.mi]p3:
3030 // A class shall not be specified as a direct base class of a
3031 // derived class more than once.
3032 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::err_duplicate_base_class)
3033 << KnownBase->getType() << Bases[idx]->getSourceRange();
3034
3035 // Delete the duplicate base class specifier; we're going to
3036 // overwrite its pointer later.
3037 Context.Deallocate(Ptr: Bases[idx]);
3038
3039 Invalid = true;
3040 } else {
3041 // Okay, add this new base class.
3042 KnownBase = Bases[idx];
3043 Bases[NumGoodBases++] = Bases[idx];
3044
3045 if (NewBaseType->isDependentType())
3046 continue;
3047 // Note this base's direct & indirect bases, if there could be ambiguity.
3048 if (Bases.size() > 1)
3049 NoteIndirectBases(Context, Set&: IndirectBaseTypes, Type: NewBaseType);
3050
3051 if (const auto *RD = NewBaseType->getAsCXXRecordDecl()) {
3052 if (Class->isInterface() &&
3053 (!RD->isInterfaceLike() ||
3054 KnownBase->getAccessSpecifier() != AS_public)) {
3055 // The Microsoft extension __interface does not permit bases that
3056 // are not themselves public interfaces.
3057 Diag(Loc: KnownBase->getBeginLoc(), DiagID: diag::err_invalid_base_in_interface)
3058 << getRecordDiagFromTagKind(Tag: RD->getTagKind()) << RD
3059 << RD->getSourceRange();
3060 Invalid = true;
3061 }
3062 if (RD->hasAttr<WeakAttr>())
3063 Class->addAttr(A: WeakAttr::CreateImplicit(Ctx&: Context));
3064 }
3065 }
3066 }
3067
3068 // Attach the remaining base class specifiers to the derived class.
3069 Class->setBases(Bases: Bases.data(), NumBases: NumGoodBases);
3070
3071 // Check that the only base classes that are duplicate are virtual.
3072 for (unsigned idx = 0; idx < NumGoodBases; ++idx) {
3073 // Check whether this direct base is inaccessible due to ambiguity.
3074 QualType BaseType = Bases[idx]->getType();
3075
3076 // Skip all dependent types in templates being used as base specifiers.
3077 // Checks below assume that the base specifier is a CXXRecord.
3078 if (BaseType->isDependentType())
3079 continue;
3080
3081 CanQualType CanonicalBase = Context.getCanonicalType(T: BaseType)
3082 .getUnqualifiedType();
3083
3084 if (IndirectBaseTypes.count(Ptr: CanonicalBase)) {
3085 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3086 /*DetectVirtual=*/true);
3087 bool found
3088 = Class->isDerivedFrom(Base: CanonicalBase->getAsCXXRecordDecl(), Paths);
3089 assert(found);
3090 (void)found;
3091
3092 if (Paths.isAmbiguous(BaseType: CanonicalBase))
3093 Diag(Loc: Bases[idx]->getBeginLoc(), DiagID: diag::warn_inaccessible_base_class)
3094 << BaseType << getAmbiguousPathsDisplayString(Paths)
3095 << Bases[idx]->getSourceRange();
3096 else
3097 assert(Bases[idx]->isVirtual());
3098 }
3099
3100 // Delete the base class specifier, since its data has been copied
3101 // into the CXXRecordDecl.
3102 Context.Deallocate(Ptr: Bases[idx]);
3103 }
3104
3105 return Invalid;
3106}
3107
3108void Sema::ActOnBaseSpecifiers(Decl *ClassDecl,
3109 MutableArrayRef<CXXBaseSpecifier *> Bases) {
3110 if (!ClassDecl || Bases.empty())
3111 return;
3112
3113 AdjustDeclIfTemplate(Decl&: ClassDecl);
3114 AttachBaseSpecifiers(Class: cast<CXXRecordDecl>(Val: ClassDecl), Bases);
3115}
3116
3117bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3118 CXXRecordDecl *Base, CXXBasePaths &Paths) {
3119 if (!getLangOpts().CPlusPlus)
3120 return false;
3121
3122 if (!Base || !Derived)
3123 return false;
3124
3125 // If either the base or the derived type is invalid, don't try to
3126 // check whether one is derived from the other.
3127 if (Base->isInvalidDecl() || Derived->isInvalidDecl())
3128 return false;
3129
3130 // FIXME: In a modules build, do we need the entire path to be visible for us
3131 // to be able to use the inheritance relationship?
3132 if (!isCompleteType(Loc, T: Context.getCanonicalTagType(TD: Derived)) &&
3133 !Derived->isBeingDefined())
3134 return false;
3135
3136 return Derived->isDerivedFrom(Base, Paths);
3137}
3138
3139bool Sema::IsDerivedFrom(SourceLocation Loc, CXXRecordDecl *Derived,
3140 CXXRecordDecl *Base) {
3141 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3142 /*DetectVirtual=*/false);
3143 return IsDerivedFrom(Loc, Derived, Base, Paths);
3144}
3145
3146bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base) {
3147 CXXBasePaths Paths(/*FindAmbiguities=*/false, /*RecordPaths=*/false,
3148 /*DetectVirtual=*/false);
3149 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3150 Base: Base->getAsCXXRecordDecl(), Paths);
3151}
3152
3153bool Sema::IsDerivedFrom(SourceLocation Loc, QualType Derived, QualType Base,
3154 CXXBasePaths &Paths) {
3155 return IsDerivedFrom(Loc, Derived: Derived->getAsCXXRecordDecl(),
3156 Base: Base->getAsCXXRecordDecl(), Paths);
3157}
3158
3159static void BuildBasePathArray(const CXXBasePath &Path,
3160 CXXCastPath &BasePathArray) {
3161 // We first go backward and check if we have a virtual base.
3162 // FIXME: It would be better if CXXBasePath had the base specifier for
3163 // the nearest virtual base.
3164 unsigned Start = 0;
3165 for (unsigned I = Path.size(); I != 0; --I) {
3166 if (Path[I - 1].Base->isVirtual()) {
3167 Start = I - 1;
3168 break;
3169 }
3170 }
3171
3172 // Now add all bases.
3173 for (unsigned I = Start, E = Path.size(); I != E; ++I)
3174 BasePathArray.push_back(Elt: const_cast<CXXBaseSpecifier*>(Path[I].Base));
3175}
3176
3177
3178void Sema::BuildBasePathArray(const CXXBasePaths &Paths,
3179 CXXCastPath &BasePathArray) {
3180 assert(BasePathArray.empty() && "Base path array must be empty!");
3181 assert(Paths.isRecordingPaths() && "Must record paths!");
3182 return ::BuildBasePathArray(Path: Paths.front(), BasePathArray);
3183}
3184
3185bool
3186Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3187 unsigned InaccessibleBaseID,
3188 unsigned AmbiguousBaseConvID,
3189 SourceLocation Loc, SourceRange Range,
3190 DeclarationName Name,
3191 CXXCastPath *BasePath,
3192 bool IgnoreAccess) {
3193 // First, determine whether the path from Derived to Base is
3194 // ambiguous. This is slightly more expensive than checking whether
3195 // the Derived to Base conversion exists, because here we need to
3196 // explore multiple paths to determine if there is an ambiguity.
3197 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3198 /*DetectVirtual=*/false);
3199 bool DerivationOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3200 if (!DerivationOkay)
3201 return true;
3202
3203 const CXXBasePath *Path = nullptr;
3204 if (!Paths.isAmbiguous(BaseType: Context.getCanonicalType(T: Base).getUnqualifiedType()))
3205 Path = &Paths.front();
3206
3207 // For MSVC compatibility, check if Derived directly inherits from Base. Clang
3208 // warns about this hierarchy under -Winaccessible-base, but MSVC allows the
3209 // user to access such bases.
3210 if (!Path && getLangOpts().MSVCCompat) {
3211 for (const CXXBasePath &PossiblePath : Paths) {
3212 if (PossiblePath.size() == 1) {
3213 Path = &PossiblePath;
3214 if (AmbiguousBaseConvID)
3215 Diag(Loc, DiagID: diag::ext_ms_ambiguous_direct_base)
3216 << Base << Derived << Range;
3217 break;
3218 }
3219 }
3220 }
3221
3222 if (Path) {
3223 if (!IgnoreAccess) {
3224 // Check that the base class can be accessed.
3225 switch (
3226 CheckBaseClassAccess(AccessLoc: Loc, Base, Derived, Path: *Path, DiagID: InaccessibleBaseID)) {
3227 case AR_inaccessible:
3228 return true;
3229 case AR_accessible:
3230 case AR_dependent:
3231 case AR_delayed:
3232 break;
3233 }
3234 }
3235
3236 // Build a base path if necessary.
3237 if (BasePath)
3238 ::BuildBasePathArray(Path: *Path, BasePathArray&: *BasePath);
3239 return false;
3240 }
3241
3242 if (AmbiguousBaseConvID) {
3243 // We know that the derived-to-base conversion is ambiguous, and
3244 // we're going to produce a diagnostic. Perform the derived-to-base
3245 // search just one more time to compute all of the possible paths so
3246 // that we can print them out. This is more expensive than any of
3247 // the previous derived-to-base checks we've done, but at this point
3248 // performance isn't as much of an issue.
3249 Paths.clear();
3250 Paths.setRecordingPaths(true);
3251 bool StillOkay = IsDerivedFrom(Loc, Derived, Base, Paths);
3252 assert(StillOkay && "Can only be used with a derived-to-base conversion");
3253 (void)StillOkay;
3254
3255 // Build up a textual representation of the ambiguous paths, e.g.,
3256 // D -> B -> A, that will be used to illustrate the ambiguous
3257 // conversions in the diagnostic. We only print one of the paths
3258 // to each base class subobject.
3259 std::string PathDisplayStr = getAmbiguousPathsDisplayString(Paths);
3260
3261 Diag(Loc, DiagID: AmbiguousBaseConvID)
3262 << Derived << Base << PathDisplayStr << Range << Name;
3263 }
3264 return true;
3265}
3266
3267bool
3268Sema::CheckDerivedToBaseConversion(QualType Derived, QualType Base,
3269 SourceLocation Loc, SourceRange Range,
3270 CXXCastPath *BasePath,
3271 bool IgnoreAccess) {
3272 return CheckDerivedToBaseConversion(
3273 Derived, Base, InaccessibleBaseID: diag::err_upcast_to_inaccessible_base,
3274 AmbiguousBaseConvID: diag::err_ambiguous_derived_to_base_conv, Loc, Range, Name: DeclarationName(),
3275 BasePath, IgnoreAccess);
3276}
3277
3278std::string Sema::getAmbiguousPathsDisplayString(CXXBasePaths &Paths) {
3279 std::string PathDisplayStr;
3280 std::set<unsigned> DisplayedPaths;
3281 for (const CXXBasePath &Path : Paths) {
3282 if (DisplayedPaths.insert(x: Path.back().SubobjectNumber).second) {
3283 // We haven't displayed a path to this particular base
3284 // class subobject yet.
3285 PathDisplayStr += "\n ";
3286 PathDisplayStr += QualType(Context.getCanonicalTagType(TD: Paths.getOrigin()))
3287 .getAsString();
3288 for (const CXXBasePathElement &Element : Path)
3289 PathDisplayStr += " -> " + Element.Base->getType().getAsString();
3290 }
3291 }
3292
3293 return PathDisplayStr;
3294}
3295
3296//===----------------------------------------------------------------------===//
3297// C++ class member Handling
3298//===----------------------------------------------------------------------===//
3299
3300bool Sema::ActOnAccessSpecifier(AccessSpecifier Access, SourceLocation ASLoc,
3301 SourceLocation ColonLoc,
3302 const ParsedAttributesView &Attrs) {
3303 assert(Access != AS_none && "Invalid kind for syntactic access specifier!");
3304 AccessSpecDecl *ASDecl = AccessSpecDecl::Create(C&: Context, AS: Access, DC: CurContext,
3305 ASLoc, ColonLoc);
3306 CurContext->addHiddenDecl(D: ASDecl);
3307 return ProcessAccessDeclAttributeList(ASDecl, AttrList: Attrs);
3308}
3309
3310void Sema::CheckOverrideControl(NamedDecl *D) {
3311 if (D->isInvalidDecl())
3312 return;
3313
3314 // We only care about "override" and "final" declarations.
3315 if (!D->hasAttr<OverrideAttr>() && !D->hasAttr<FinalAttr>())
3316 return;
3317
3318 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3319
3320 // We can't check dependent instance methods.
3321 if (MD && MD->isInstance() &&
3322 (MD->getParent()->hasAnyDependentBases() ||
3323 MD->getType()->isDependentType()))
3324 return;
3325
3326 if (MD && !MD->isVirtual()) {
3327 // If we have a non-virtual method, check if it hides a virtual method.
3328 // (In that case, it's most likely the method has the wrong type.)
3329 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
3330 FindHiddenVirtualMethods(MD, OverloadedMethods);
3331
3332 if (!OverloadedMethods.empty()) {
3333 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3334 Diag(Loc: OA->getLocation(),
3335 DiagID: diag::override_keyword_hides_virtual_member_function)
3336 << "override" << (OverloadedMethods.size() > 1);
3337 } else if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3338 Diag(Loc: FA->getLocation(),
3339 DiagID: diag::override_keyword_hides_virtual_member_function)
3340 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3341 << (OverloadedMethods.size() > 1);
3342 }
3343 NoteHiddenVirtualMethods(MD, OverloadedMethods);
3344 MD->setInvalidDecl();
3345 return;
3346 }
3347 // Fall through into the general case diagnostic.
3348 // FIXME: We might want to attempt typo correction here.
3349 }
3350
3351 if (!MD || !MD->isVirtual()) {
3352 if (OverrideAttr *OA = D->getAttr<OverrideAttr>()) {
3353 Diag(Loc: OA->getLocation(),
3354 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3355 << "override" << FixItHint::CreateRemoval(RemoveRange: OA->getLocation());
3356 D->dropAttr<OverrideAttr>();
3357 }
3358 if (FinalAttr *FA = D->getAttr<FinalAttr>()) {
3359 Diag(Loc: FA->getLocation(),
3360 DiagID: diag::override_keyword_only_allowed_on_virtual_member_functions)
3361 << (FA->isSpelledAsSealed() ? "sealed" : "final")
3362 << FixItHint::CreateRemoval(RemoveRange: FA->getLocation());
3363 D->dropAttr<FinalAttr>();
3364 }
3365 return;
3366 }
3367
3368 // C++11 [class.virtual]p5:
3369 // If a function is marked with the virt-specifier override and
3370 // does not override a member function of a base class, the program is
3371 // ill-formed.
3372 bool HasOverriddenMethods = MD->size_overridden_methods() != 0;
3373 if (MD->hasAttr<OverrideAttr>() && !HasOverriddenMethods)
3374 Diag(Loc: MD->getLocation(), DiagID: diag::err_function_marked_override_not_overriding)
3375 << MD->getDeclName();
3376}
3377
3378void Sema::DiagnoseAbsenceOfOverrideControl(NamedDecl *D, bool Inconsistent) {
3379 if (D->isInvalidDecl() || D->hasAttr<OverrideAttr>())
3380 return;
3381 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D);
3382 if (!MD || MD->isImplicit() || MD->hasAttr<FinalAttr>())
3383 return;
3384
3385 SourceLocation Loc = MD->getLocation();
3386 SourceLocation SpellingLoc = Loc;
3387 if (getSourceManager().isMacroArgExpansion(Loc))
3388 SpellingLoc = getSourceManager().getImmediateExpansionRange(Loc).getBegin();
3389 SpellingLoc = getSourceManager().getSpellingLoc(Loc: SpellingLoc);
3390 if (SpellingLoc.isValid() && getSourceManager().isInSystemHeader(Loc: SpellingLoc))
3391 return;
3392
3393 if (MD->size_overridden_methods() > 0) {
3394 auto EmitDiag = [&](unsigned DiagInconsistent, unsigned DiagSuggest) {
3395 unsigned DiagID =
3396 Inconsistent && !Diags.isIgnored(DiagID: DiagInconsistent, Loc: MD->getLocation())
3397 ? DiagInconsistent
3398 : DiagSuggest;
3399 Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
3400 const CXXMethodDecl *OMD = *MD->begin_overridden_methods();
3401 Diag(Loc: OMD->getLocation(), DiagID: diag::note_overridden_virtual_function);
3402 };
3403 if (isa<CXXDestructorDecl>(Val: MD))
3404 EmitDiag(
3405 diag::warn_inconsistent_destructor_marked_not_override_overriding,
3406 diag::warn_suggest_destructor_marked_not_override_overriding);
3407 else
3408 EmitDiag(diag::warn_inconsistent_function_marked_not_override_overriding,
3409 diag::warn_suggest_function_marked_not_override_overriding);
3410 }
3411}
3412
3413bool Sema::CheckIfOverriddenFunctionIsMarkedFinal(const CXXMethodDecl *New,
3414 const CXXMethodDecl *Old) {
3415 FinalAttr *FA = Old->getAttr<FinalAttr>();
3416 if (!FA)
3417 return false;
3418
3419 Diag(Loc: New->getLocation(), DiagID: diag::err_final_function_overridden)
3420 << New->getDeclName()
3421 << FA->isSpelledAsSealed();
3422 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
3423 return true;
3424}
3425
3426static bool InitializationHasSideEffects(const FieldDecl &FD) {
3427 const Type *T = FD.getType()->getBaseElementTypeUnsafe();
3428 // FIXME: Destruction of ObjC lifetime types has side-effects.
3429 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
3430 return !RD->isCompleteDefinition() ||
3431 !RD->hasTrivialDefaultConstructor() ||
3432 !RD->hasTrivialDestructor();
3433 return false;
3434}
3435
3436void Sema::CheckShadowInheritedFields(const SourceLocation &Loc,
3437 DeclarationName FieldName,
3438 const CXXRecordDecl *RD,
3439 bool DeclIsField) {
3440 if (Diags.isIgnored(DiagID: diag::warn_shadow_field, Loc))
3441 return;
3442
3443 // To record a shadowed field in a base
3444 std::map<CXXRecordDecl*, NamedDecl*> Bases;
3445 auto FieldShadowed = [&](const CXXBaseSpecifier *Specifier,
3446 CXXBasePath &Path) {
3447 const auto Base = Specifier->getType()->getAsCXXRecordDecl();
3448 // Record an ambiguous path directly
3449 if (Bases.find(x: Base) != Bases.end())
3450 return true;
3451 for (const auto Field : Base->lookup(Name: FieldName)) {
3452 if ((isa<FieldDecl>(Val: Field) || isa<IndirectFieldDecl>(Val: Field)) &&
3453 Field->getAccess() != AS_private) {
3454 assert(Field->getAccess() != AS_none);
3455 assert(Bases.find(Base) == Bases.end());
3456 Bases[Base] = Field;
3457 return true;
3458 }
3459 }
3460 return false;
3461 };
3462
3463 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
3464 /*DetectVirtual=*/true);
3465 if (!RD->lookupInBases(BaseMatches: FieldShadowed, Paths))
3466 return;
3467
3468 for (const auto &P : Paths) {
3469 auto Base = P.back().Base->getType()->getAsCXXRecordDecl();
3470 auto It = Bases.find(x: Base);
3471 // Skip duplicated bases
3472 if (It == Bases.end())
3473 continue;
3474 auto BaseField = It->second;
3475 assert(BaseField->getAccess() != AS_private);
3476 if (AS_none !=
3477 CXXRecordDecl::MergeAccess(PathAccess: P.Access, DeclAccess: BaseField->getAccess())) {
3478 Diag(Loc, DiagID: diag::warn_shadow_field)
3479 << FieldName << RD << Base << DeclIsField;
3480 Diag(Loc: BaseField->getLocation(), DiagID: diag::note_shadow_field);
3481 Bases.erase(position: It);
3482 }
3483 }
3484}
3485
3486template <typename AttrType>
3487inline static bool HasAttribute(const QualType &T) {
3488 if (const TagDecl *TD = T->getAsTagDecl())
3489 return TD->hasAttr<AttrType>();
3490 if (const TypedefType *TDT = T->getAs<TypedefType>())
3491 return TDT->getDecl()->hasAttr<AttrType>();
3492 return false;
3493}
3494
3495static bool IsUnusedPrivateField(const FieldDecl *FD) {
3496 if (FD->getAccess() == AS_private && FD->getDeclName()) {
3497 QualType FieldType = FD->getType();
3498 if (HasAttribute<WarnUnusedAttr>(T: FieldType))
3499 return true;
3500
3501 return !FD->isImplicit() && !FD->hasAttr<UnusedAttr>() &&
3502 !FD->getParent()->isDependentContext() &&
3503 !HasAttribute<UnusedAttr>(T: FieldType) &&
3504 !InitializationHasSideEffects(FD: *FD);
3505 }
3506 return false;
3507}
3508
3509NamedDecl *
3510Sema::ActOnCXXMemberDeclarator(Scope *S, AccessSpecifier AS, Declarator &D,
3511 MultiTemplateParamsArg TemplateParameterLists,
3512 Expr *BitWidth, const VirtSpecifiers &VS,
3513 InClassInitStyle InitStyle) {
3514 const DeclSpec &DS = D.getDeclSpec();
3515 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
3516 DeclarationName Name = NameInfo.getName();
3517 SourceLocation Loc = NameInfo.getLoc();
3518
3519 // For anonymous bitfields, the location should point to the type.
3520 if (Loc.isInvalid())
3521 Loc = D.getBeginLoc();
3522
3523 assert(isa<CXXRecordDecl>(CurContext));
3524 assert(!DS.isFriendSpecified());
3525
3526 bool isFunc = D.isDeclarationOfFunction();
3527 const ParsedAttr *MSPropertyAttr =
3528 D.getDeclSpec().getAttributes().getMSPropertyAttr();
3529
3530 if (cast<CXXRecordDecl>(Val: CurContext)->isInterface()) {
3531 // The Microsoft extension __interface only permits public member functions
3532 // and prohibits constructors, destructors, operators, non-public member
3533 // functions, static methods and data members.
3534 unsigned InvalidDecl;
3535 bool ShowDeclName = true;
3536 if (!isFunc &&
3537 (DS.getStorageClassSpec() == DeclSpec::SCS_typedef || MSPropertyAttr))
3538 InvalidDecl = 0;
3539 else if (!isFunc)
3540 InvalidDecl = 1;
3541 else if (AS != AS_public)
3542 InvalidDecl = 2;
3543 else if (DS.getStorageClassSpec() == DeclSpec::SCS_static)
3544 InvalidDecl = 3;
3545 else switch (Name.getNameKind()) {
3546 case DeclarationName::CXXConstructorName:
3547 InvalidDecl = 4;
3548 ShowDeclName = false;
3549 break;
3550
3551 case DeclarationName::CXXDestructorName:
3552 InvalidDecl = 5;
3553 ShowDeclName = false;
3554 break;
3555
3556 case DeclarationName::CXXOperatorName:
3557 case DeclarationName::CXXConversionFunctionName:
3558 InvalidDecl = 6;
3559 break;
3560
3561 default:
3562 InvalidDecl = 0;
3563 break;
3564 }
3565
3566 if (InvalidDecl) {
3567 if (ShowDeclName)
3568 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3569 << (InvalidDecl-1) << Name;
3570 else
3571 Diag(Loc, DiagID: diag::err_invalid_member_in_interface)
3572 << (InvalidDecl-1) << "";
3573 return nullptr;
3574 }
3575 }
3576
3577 // HLSL prohibits user defined constructors and destructors.
3578 if (getLangOpts().HLSL) {
3579 switch (Name.getNameKind()) {
3580 case DeclarationName::CXXConstructorName:
3581 case DeclarationName::CXXDestructorName:
3582 Diag(Loc, DiagID: diag::err_hlsl_cstor_dstor);
3583 return nullptr;
3584 default:
3585 break;
3586 }
3587 }
3588
3589 // C++ 9.2p6: A member shall not be declared to have automatic storage
3590 // duration (auto, register) or with the extern storage-class-specifier.
3591 // C++ 7.1.1p8: The mutable specifier can be applied only to names of class
3592 // data members and cannot be applied to names declared const or static,
3593 // and cannot be applied to reference members.
3594 switch (DS.getStorageClassSpec()) {
3595 case DeclSpec::SCS_unspecified:
3596 case DeclSpec::SCS_typedef:
3597 case DeclSpec::SCS_static:
3598 break;
3599 case DeclSpec::SCS_mutable:
3600 if (isFunc) {
3601 Diag(Loc: DS.getStorageClassSpecLoc(), DiagID: diag::err_mutable_function);
3602
3603 // FIXME: It would be nicer if the keyword was ignored only for this
3604 // declarator. Otherwise we could get follow-up errors.
3605 D.getMutableDeclSpec().ClearStorageClassSpecs();
3606 }
3607 break;
3608 default:
3609 Diag(Loc: DS.getStorageClassSpecLoc(),
3610 DiagID: diag::err_storageclass_invalid_for_member);
3611 D.getMutableDeclSpec().ClearStorageClassSpecs();
3612 break;
3613 }
3614
3615 bool isInstField = (DS.getStorageClassSpec() == DeclSpec::SCS_unspecified ||
3616 DS.getStorageClassSpec() == DeclSpec::SCS_mutable) &&
3617 !isFunc && TemplateParameterLists.empty();
3618
3619 if (DS.hasConstexprSpecifier() && isInstField) {
3620 SemaDiagnosticBuilder B =
3621 Diag(Loc: DS.getConstexprSpecLoc(), DiagID: diag::err_invalid_constexpr_member);
3622 SourceLocation ConstexprLoc = DS.getConstexprSpecLoc();
3623 if (InitStyle == ICIS_NoInit) {
3624 B << 0 << 0;
3625 if (D.getDeclSpec().getTypeQualifiers() & DeclSpec::TQ_const)
3626 B << FixItHint::CreateRemoval(RemoveRange: ConstexprLoc);
3627 else {
3628 B << FixItHint::CreateReplacement(RemoveRange: ConstexprLoc, Code: "const");
3629 D.getMutableDeclSpec().ClearConstexprSpec();
3630 const char *PrevSpec;
3631 unsigned DiagID;
3632 bool Failed = D.getMutableDeclSpec().SetTypeQual(
3633 T: DeclSpec::TQ_const, Loc: ConstexprLoc, PrevSpec, DiagID, Lang: getLangOpts());
3634 (void)Failed;
3635 assert(!Failed && "Making a constexpr member const shouldn't fail");
3636 }
3637 } else {
3638 B << 1;
3639 const char *PrevSpec;
3640 unsigned DiagID;
3641 if (D.getMutableDeclSpec().SetStorageClassSpec(
3642 S&: *this, SC: DeclSpec::SCS_static, Loc: ConstexprLoc, PrevSpec, DiagID,
3643 Policy: Context.getPrintingPolicy())) {
3644 assert(DS.getStorageClassSpec() == DeclSpec::SCS_mutable &&
3645 "This is the only DeclSpec that should fail to be applied");
3646 B << 1;
3647 } else {
3648 B << 0 << FixItHint::CreateInsertion(InsertionLoc: ConstexprLoc, Code: "static ");
3649 isInstField = false;
3650 }
3651 }
3652 }
3653
3654 NamedDecl *Member;
3655 if (isInstField) {
3656 CXXScopeSpec &SS = D.getCXXScopeSpec();
3657
3658 // Data members must have identifiers for names.
3659 if (!Name.isIdentifier()) {
3660 Diag(Loc, DiagID: diag::err_bad_variable_name)
3661 << Name;
3662 return nullptr;
3663 }
3664
3665 IdentifierInfo *II = Name.getAsIdentifierInfo();
3666 if (D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId) {
3667 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_with_template_arguments)
3668 << II
3669 << SourceRange(D.getName().TemplateId->LAngleLoc,
3670 D.getName().TemplateId->RAngleLoc)
3671 << D.getName().TemplateId->LAngleLoc;
3672 D.SetIdentifier(Id: II, IdLoc: Loc);
3673 }
3674
3675 if (SS.isSet() && !SS.isInvalid()) {
3676 // The user provided a superfluous scope specifier inside a class
3677 // definition:
3678 //
3679 // class X {
3680 // int X::member;
3681 // };
3682 if (DeclContext *DC = computeDeclContext(SS, EnteringContext: false)) {
3683 TemplateIdAnnotation *TemplateId =
3684 D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId
3685 ? D.getName().TemplateId
3686 : nullptr;
3687 diagnoseQualifiedDeclaration(SS, DC, Name, Loc: D.getIdentifierLoc(),
3688 TemplateId,
3689 /*IsMemberSpecialization=*/false);
3690 } else {
3691 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_member_qualification)
3692 << Name << SS.getRange();
3693 }
3694 SS.clear();
3695 }
3696
3697 if (MSPropertyAttr) {
3698 Member = HandleMSProperty(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3699 BitfieldWidth: BitWidth, InitStyle, AS, MSPropertyAttr: *MSPropertyAttr);
3700 if (!Member)
3701 return nullptr;
3702 isInstField = false;
3703 } else {
3704 Member = HandleField(S, TagD: cast<CXXRecordDecl>(Val: CurContext), DeclStart: Loc, D,
3705 BitfieldWidth: BitWidth, InitStyle, AS);
3706 if (!Member)
3707 return nullptr;
3708 }
3709
3710 CheckShadowInheritedFields(Loc, FieldName: Name, RD: cast<CXXRecordDecl>(Val: CurContext));
3711 } else {
3712 Member = HandleDeclarator(S, D, TemplateParameterLists);
3713 if (!Member)
3714 return nullptr;
3715
3716 // Non-instance-fields can't have a bitfield.
3717 if (BitWidth) {
3718 if (Member->isInvalidDecl()) {
3719 // don't emit another diagnostic.
3720 } else if (isa<VarDecl>(Val: Member) || isa<VarTemplateDecl>(Val: Member)) {
3721 // C++ 9.6p3: A bit-field shall not be a static member.
3722 // "static member 'A' cannot be a bit-field"
3723 Diag(Loc, DiagID: diag::err_static_not_bitfield)
3724 << Name << BitWidth->getSourceRange();
3725 } else if (isa<TypedefDecl>(Val: Member)) {
3726 // "typedef member 'x' cannot be a bit-field"
3727 Diag(Loc, DiagID: diag::err_typedef_not_bitfield)
3728 << Name << BitWidth->getSourceRange();
3729 } else {
3730 // A function typedef ("typedef int f(); f a;").
3731 // C++ 9.6p3: A bit-field shall have integral or enumeration type.
3732 Diag(Loc, DiagID: diag::err_not_integral_type_bitfield)
3733 << Name << cast<ValueDecl>(Val: Member)->getType()
3734 << BitWidth->getSourceRange();
3735 }
3736
3737 BitWidth = nullptr;
3738 Member->setInvalidDecl();
3739 }
3740
3741 NamedDecl *NonTemplateMember = Member;
3742 if (FunctionTemplateDecl *FunTmpl = dyn_cast<FunctionTemplateDecl>(Val: Member))
3743 NonTemplateMember = FunTmpl->getTemplatedDecl();
3744 else if (VarTemplateDecl *VarTmpl = dyn_cast<VarTemplateDecl>(Val: Member))
3745 NonTemplateMember = VarTmpl->getTemplatedDecl();
3746
3747 Member->setAccess(AS);
3748
3749 // If we have declared a member function template or static data member
3750 // template, set the access of the templated declaration as well.
3751 if (NonTemplateMember != Member)
3752 NonTemplateMember->setAccess(AS);
3753
3754 // C++ [temp.deduct.guide]p3:
3755 // A deduction guide [...] for a member class template [shall be
3756 // declared] with the same access [as the template].
3757 if (auto *DG = dyn_cast<CXXDeductionGuideDecl>(Val: NonTemplateMember)) {
3758 auto *TD = DG->getDeducedTemplate();
3759 // Access specifiers are only meaningful if both the template and the
3760 // deduction guide are from the same scope.
3761 if (AS != TD->getAccess() &&
3762 TD->getDeclContext()->getRedeclContext()->Equals(
3763 DC: DG->getDeclContext()->getRedeclContext())) {
3764 Diag(Loc: DG->getBeginLoc(), DiagID: diag::err_deduction_guide_wrong_access);
3765 Diag(Loc: TD->getBeginLoc(), DiagID: diag::note_deduction_guide_template_access)
3766 << TD->getAccess();
3767 const AccessSpecDecl *LastAccessSpec = nullptr;
3768 for (const auto *D : cast<CXXRecordDecl>(Val: CurContext)->decls()) {
3769 if (const auto *AccessSpec = dyn_cast<AccessSpecDecl>(Val: D))
3770 LastAccessSpec = AccessSpec;
3771 }
3772 assert(LastAccessSpec && "differing access with no access specifier");
3773 Diag(Loc: LastAccessSpec->getBeginLoc(), DiagID: diag::note_deduction_guide_access)
3774 << AS;
3775 }
3776 }
3777 }
3778
3779 if (VS.isOverrideSpecified())
3780 Member->addAttr(A: OverrideAttr::Create(Ctx&: Context, Range: VS.getOverrideLoc()));
3781 if (VS.isFinalSpecified())
3782 Member->addAttr(A: FinalAttr::Create(Ctx&: Context, Range: VS.getFinalLoc(),
3783 S: VS.isFinalSpelledSealed()
3784 ? FinalAttr::Keyword_sealed
3785 : FinalAttr::Keyword_final));
3786
3787 if (VS.getLastLocation().isValid()) {
3788 // Update the end location of a method that has a virt-specifiers.
3789 if (CXXMethodDecl *MD = dyn_cast_or_null<CXXMethodDecl>(Val: Member))
3790 MD->setRangeEnd(VS.getLastLocation());
3791 }
3792
3793 CheckOverrideControl(D: Member);
3794
3795 assert((Name || isInstField) && "No identifier for non-field ?");
3796
3797 if (isInstField) {
3798 FieldDecl *FD = cast<FieldDecl>(Val: Member);
3799 FieldCollector->Add(D: FD);
3800
3801 if (!Diags.isIgnored(DiagID: diag::warn_unused_private_field, Loc: FD->getLocation()) &&
3802 IsUnusedPrivateField(FD)) {
3803 // Remember all explicit private FieldDecls that have a name, no side
3804 // effects and are not part of a dependent type declaration.
3805 UnusedPrivateFields.insert(X: FD);
3806 }
3807 }
3808
3809 return Member;
3810}
3811
3812namespace {
3813 class UninitializedFieldVisitor
3814 : public EvaluatedExprVisitor<UninitializedFieldVisitor> {
3815 Sema &S;
3816 // List of Decls to generate a warning on. Also remove Decls that become
3817 // initialized.
3818 llvm::SmallPtrSetImpl<ValueDecl*> &Decls;
3819 // List of base classes of the record. Classes are removed after their
3820 // initializers.
3821 llvm::SmallPtrSetImpl<QualType> &BaseClasses;
3822 // Vector of decls to be removed from the Decl set prior to visiting the
3823 // nodes. These Decls may have been initialized in the prior initializer.
3824 llvm::SmallVector<ValueDecl*, 4> DeclsToRemove;
3825 // If non-null, add a note to the warning pointing back to the constructor.
3826 const CXXConstructorDecl *Constructor;
3827 // Variables to hold state when processing an initializer list. When
3828 // InitList is true, special case initialization of FieldDecls matching
3829 // InitListFieldDecl.
3830 bool InitList;
3831 FieldDecl *InitListFieldDecl;
3832 llvm::SmallVector<unsigned, 4> InitFieldIndex;
3833
3834 public:
3835 typedef EvaluatedExprVisitor<UninitializedFieldVisitor> Inherited;
3836 UninitializedFieldVisitor(Sema &S,
3837 llvm::SmallPtrSetImpl<ValueDecl*> &Decls,
3838 llvm::SmallPtrSetImpl<QualType> &BaseClasses)
3839 : Inherited(S.Context), S(S), Decls(Decls), BaseClasses(BaseClasses),
3840 Constructor(nullptr), InitList(false), InitListFieldDecl(nullptr) {}
3841
3842 // Returns true if the use of ME is not an uninitialized use.
3843 bool IsInitListMemberExprInitialized(MemberExpr *ME,
3844 bool CheckReferenceOnly) {
3845 llvm::SmallVector<FieldDecl*, 4> Fields;
3846 bool ReferenceField = false;
3847 while (ME) {
3848 FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl());
3849 if (!FD)
3850 return false;
3851 Fields.push_back(Elt: FD);
3852 if (FD->getType()->isReferenceType())
3853 ReferenceField = true;
3854 ME = dyn_cast<MemberExpr>(Val: ME->getBase()->IgnoreParenImpCasts());
3855 }
3856
3857 // Binding a reference to an uninitialized field is not an
3858 // uninitialized use.
3859 if (CheckReferenceOnly && !ReferenceField)
3860 return true;
3861
3862 // Discard the first field since it is the field decl that is being
3863 // initialized.
3864 auto UsedFields = llvm::drop_begin(RangeOrContainer: llvm::reverse(C&: Fields));
3865 auto UsedIter = UsedFields.begin();
3866 const auto UsedEnd = UsedFields.end();
3867
3868 for (const unsigned Orig : InitFieldIndex) {
3869 if (UsedIter == UsedEnd)
3870 break;
3871 const unsigned UsedIndex = (*UsedIter)->getFieldIndex();
3872 if (UsedIndex < Orig)
3873 return true;
3874 if (UsedIndex > Orig)
3875 break;
3876 ++UsedIter;
3877 }
3878
3879 return false;
3880 }
3881
3882 void HandleMemberExpr(MemberExpr *ME, bool CheckReferenceOnly,
3883 bool AddressOf) {
3884 if (isa<EnumConstantDecl>(Val: ME->getMemberDecl()))
3885 return;
3886
3887 // FieldME is the inner-most MemberExpr that is not an anonymous struct
3888 // or union.
3889 MemberExpr *FieldME = ME;
3890
3891 bool AllPODFields = FieldME->getType().isPODType(Context: S.Context);
3892
3893 Expr *Base = ME;
3894 while (MemberExpr *SubME =
3895 dyn_cast<MemberExpr>(Val: Base->IgnoreParenImpCasts())) {
3896
3897 if (isa<VarDecl>(Val: SubME->getMemberDecl()))
3898 return;
3899
3900 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: SubME->getMemberDecl()))
3901 if (!FD->isAnonymousStructOrUnion())
3902 FieldME = SubME;
3903
3904 if (!FieldME->getType().isPODType(Context: S.Context))
3905 AllPODFields = false;
3906
3907 Base = SubME->getBase();
3908 }
3909
3910 if (!isa<CXXThisExpr>(Val: Base->IgnoreParenImpCasts())) {
3911 Visit(S: Base);
3912 return;
3913 }
3914
3915 if (AddressOf && AllPODFields)
3916 return;
3917
3918 ValueDecl* FoundVD = FieldME->getMemberDecl();
3919
3920 if (ImplicitCastExpr *BaseCast = dyn_cast<ImplicitCastExpr>(Val: Base)) {
3921 while (isa<ImplicitCastExpr>(Val: BaseCast->getSubExpr())) {
3922 BaseCast = cast<ImplicitCastExpr>(Val: BaseCast->getSubExpr());
3923 }
3924
3925 if (BaseCast->getCastKind() == CK_UncheckedDerivedToBase) {
3926 QualType T = BaseCast->getType();
3927 if (T->isPointerType() &&
3928 BaseClasses.count(Ptr: T->getPointeeType())) {
3929 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag::warn_base_class_is_uninit)
3930 << T->getPointeeType() << FoundVD;
3931 }
3932 }
3933 }
3934
3935 if (!Decls.count(Ptr: FoundVD))
3936 return;
3937
3938 const bool IsReference = FoundVD->getType()->isReferenceType();
3939
3940 if (InitList && !AddressOf && FoundVD == InitListFieldDecl) {
3941 // Special checking for initializer lists.
3942 if (IsInitListMemberExprInitialized(ME, CheckReferenceOnly)) {
3943 return;
3944 }
3945 } else {
3946 // Prevent double warnings on use of unbounded references.
3947 if (CheckReferenceOnly && !IsReference)
3948 return;
3949 }
3950
3951 unsigned diag = IsReference
3952 ? diag::warn_reference_field_is_uninit
3953 : diag::warn_field_is_uninit;
3954 S.Diag(Loc: FieldME->getExprLoc(), DiagID: diag) << FoundVD;
3955 if (Constructor)
3956 S.Diag(Loc: Constructor->getLocation(),
3957 DiagID: diag::note_uninit_in_this_constructor)
3958 << (Constructor->isDefaultConstructor() && Constructor->isImplicit());
3959
3960 }
3961
3962 void HandleValue(Expr *E, bool AddressOf) {
3963 E = E->IgnoreParens();
3964
3965 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E)) {
3966 HandleMemberExpr(ME, CheckReferenceOnly: false /*CheckReferenceOnly*/,
3967 AddressOf /*AddressOf*/);
3968 return;
3969 }
3970
3971 if (ConditionalOperator *CO = dyn_cast<ConditionalOperator>(Val: E)) {
3972 Visit(S: CO->getCond());
3973 HandleValue(E: CO->getTrueExpr(), AddressOf);
3974 HandleValue(E: CO->getFalseExpr(), AddressOf);
3975 return;
3976 }
3977
3978 if (BinaryConditionalOperator *BCO =
3979 dyn_cast<BinaryConditionalOperator>(Val: E)) {
3980 Visit(S: BCO->getCond());
3981 HandleValue(E: BCO->getFalseExpr(), AddressOf);
3982 return;
3983 }
3984
3985 if (OpaqueValueExpr *OVE = dyn_cast<OpaqueValueExpr>(Val: E)) {
3986 HandleValue(E: OVE->getSourceExpr(), AddressOf);
3987 return;
3988 }
3989
3990 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(Val: E)) {
3991 switch (BO->getOpcode()) {
3992 default:
3993 break;
3994 case(BO_PtrMemD):
3995 case(BO_PtrMemI):
3996 HandleValue(E: BO->getLHS(), AddressOf);
3997 Visit(S: BO->getRHS());
3998 return;
3999 case(BO_Comma):
4000 Visit(S: BO->getLHS());
4001 HandleValue(E: BO->getRHS(), AddressOf);
4002 return;
4003 }
4004 }
4005
4006 Visit(S: E);
4007 }
4008
4009 void CheckInitListExpr(InitListExpr *ILE) {
4010 InitFieldIndex.push_back(Elt: 0);
4011 for (auto *Child : ILE->children()) {
4012 if (InitListExpr *SubList = dyn_cast<InitListExpr>(Val: Child)) {
4013 CheckInitListExpr(ILE: SubList);
4014 } else {
4015 Visit(S: Child);
4016 }
4017 ++InitFieldIndex.back();
4018 }
4019 InitFieldIndex.pop_back();
4020 }
4021
4022 void CheckInitializer(Expr *E, const CXXConstructorDecl *FieldConstructor,
4023 FieldDecl *Field, const Type *BaseClass) {
4024 // Remove Decls that may have been initialized in the previous
4025 // initializer.
4026 for (ValueDecl* VD : DeclsToRemove)
4027 Decls.erase(Ptr: VD);
4028 DeclsToRemove.clear();
4029
4030 Constructor = FieldConstructor;
4031 InitListExpr *ILE = dyn_cast<InitListExpr>(Val: E);
4032
4033 if (ILE && Field) {
4034 InitList = true;
4035 InitListFieldDecl = Field;
4036 InitFieldIndex.clear();
4037 CheckInitListExpr(ILE);
4038 } else {
4039 InitList = false;
4040 Visit(S: E);
4041 }
4042
4043 if (Field)
4044 Decls.erase(Ptr: Field);
4045 if (BaseClass)
4046 BaseClasses.erase(Ptr: BaseClass->getCanonicalTypeInternal());
4047 }
4048
4049 void VisitMemberExpr(MemberExpr *ME) {
4050 // All uses of unbounded reference fields will warn.
4051 HandleMemberExpr(ME, CheckReferenceOnly: true /*CheckReferenceOnly*/, AddressOf: false /*AddressOf*/);
4052 }
4053
4054 void VisitImplicitCastExpr(ImplicitCastExpr *E) {
4055 if (E->getCastKind() == CK_LValueToRValue) {
4056 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4057 return;
4058 }
4059
4060 Inherited::VisitImplicitCastExpr(S: E);
4061 }
4062
4063 void VisitCXXConstructExpr(CXXConstructExpr *E) {
4064 if (E->getConstructor()->isCopyConstructor()) {
4065 Expr *ArgExpr = E->getArg(Arg: 0);
4066 if (InitListExpr *ILE = dyn_cast<InitListExpr>(Val: ArgExpr))
4067 if (ILE->getNumInits() == 1)
4068 ArgExpr = ILE->getInit(Init: 0);
4069 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(Val: ArgExpr))
4070 if (ICE->getCastKind() == CK_NoOp)
4071 ArgExpr = ICE->getSubExpr();
4072 HandleValue(E: ArgExpr, AddressOf: false /*AddressOf*/);
4073 return;
4074 }
4075 Inherited::VisitCXXConstructExpr(S: E);
4076 }
4077
4078 void VisitCXXMemberCallExpr(CXXMemberCallExpr *E) {
4079 Expr *Callee = E->getCallee();
4080 if (isa<MemberExpr>(Val: Callee)) {
4081 HandleValue(E: Callee, AddressOf: false /*AddressOf*/);
4082 for (auto *Arg : E->arguments())
4083 Visit(S: Arg);
4084 return;
4085 }
4086
4087 Inherited::VisitCXXMemberCallExpr(S: E);
4088 }
4089
4090 void VisitCallExpr(CallExpr *E) {
4091 // Treat std::move as a use.
4092 if (E->isCallToStdMove()) {
4093 HandleValue(E: E->getArg(Arg: 0), /*AddressOf=*/false);
4094 return;
4095 }
4096
4097 Inherited::VisitCallExpr(CE: E);
4098 }
4099
4100 void VisitCXXOperatorCallExpr(CXXOperatorCallExpr *E) {
4101 Expr *Callee = E->getCallee();
4102
4103 if (isa<UnresolvedLookupExpr>(Val: Callee))
4104 return Inherited::VisitCXXOperatorCallExpr(S: E);
4105
4106 Visit(S: Callee);
4107 for (auto *Arg : E->arguments())
4108 HandleValue(E: Arg->IgnoreParenImpCasts(), AddressOf: false /*AddressOf*/);
4109 }
4110
4111 void VisitBinaryOperator(BinaryOperator *E) {
4112 // If a field assignment is detected, remove the field from the
4113 // uninitiailized field set.
4114 if (E->getOpcode() == BO_Assign)
4115 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getLHS()))
4116 if (FieldDecl *FD = dyn_cast<FieldDecl>(Val: ME->getMemberDecl()))
4117 if (!FD->getType()->isReferenceType())
4118 DeclsToRemove.push_back(Elt: FD);
4119
4120 if (E->isCompoundAssignmentOp()) {
4121 HandleValue(E: E->getLHS(), AddressOf: false /*AddressOf*/);
4122 Visit(S: E->getRHS());
4123 return;
4124 }
4125
4126 Inherited::VisitBinaryOperator(S: E);
4127 }
4128
4129 void VisitUnaryOperator(UnaryOperator *E) {
4130 if (E->isIncrementDecrementOp()) {
4131 HandleValue(E: E->getSubExpr(), AddressOf: false /*AddressOf*/);
4132 return;
4133 }
4134 if (E->getOpcode() == UO_AddrOf) {
4135 if (MemberExpr *ME = dyn_cast<MemberExpr>(Val: E->getSubExpr())) {
4136 HandleValue(E: ME->getBase(), AddressOf: true /*AddressOf*/);
4137 return;
4138 }
4139 }
4140
4141 Inherited::VisitUnaryOperator(S: E);
4142 }
4143 };
4144
4145 // Diagnose value-uses of fields to initialize themselves, e.g.
4146 // foo(foo)
4147 // where foo is not also a parameter to the constructor.
4148 // Also diagnose across field uninitialized use such as
4149 // x(y), y(x)
4150 // TODO: implement -Wuninitialized and fold this into that framework.
4151 static void DiagnoseUninitializedFields(
4152 Sema &SemaRef, const CXXConstructorDecl *Constructor) {
4153
4154 if (SemaRef.getDiagnostics().isIgnored(DiagID: diag::warn_field_is_uninit,
4155 Loc: Constructor->getLocation())) {
4156 return;
4157 }
4158
4159 if (Constructor->isInvalidDecl())
4160 return;
4161
4162 const CXXRecordDecl *RD = Constructor->getParent();
4163
4164 if (RD->isDependentContext())
4165 return;
4166
4167 // Holds fields that are uninitialized.
4168 llvm::SmallPtrSet<ValueDecl*, 4> UninitializedFields;
4169
4170 // At the beginning, all fields are uninitialized.
4171 for (auto *I : RD->decls()) {
4172 if (auto *FD = dyn_cast<FieldDecl>(Val: I)) {
4173 UninitializedFields.insert(Ptr: FD);
4174 } else if (auto *IFD = dyn_cast<IndirectFieldDecl>(Val: I)) {
4175 UninitializedFields.insert(Ptr: IFD->getAnonField());
4176 }
4177 }
4178
4179 llvm::SmallPtrSet<QualType, 4> UninitializedBaseClasses;
4180 for (const auto &I : RD->bases()) {
4181 // Virtual bases are initialized from the most derived class, so an
4182 // abstract base class constructor can assume it to be initialized.
4183 if (I.isVirtual() && RD->isAbstract())
4184 continue;
4185 UninitializedBaseClasses.insert(Ptr: I.getType().getCanonicalType());
4186 }
4187
4188 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4189 return;
4190
4191 UninitializedFieldVisitor UninitializedChecker(SemaRef,
4192 UninitializedFields,
4193 UninitializedBaseClasses);
4194
4195 for (const auto *FieldInit : Constructor->inits()) {
4196 if (UninitializedFields.empty() && UninitializedBaseClasses.empty())
4197 break;
4198
4199 Expr *InitExpr = FieldInit->getInit();
4200 if (!InitExpr)
4201 continue;
4202
4203 if (CXXDefaultInitExpr *Default =
4204 dyn_cast<CXXDefaultInitExpr>(Val: InitExpr)) {
4205 InitExpr = Default->getExpr();
4206 if (!InitExpr)
4207 continue;
4208 // In class initializers will point to the constructor.
4209 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: Constructor,
4210 Field: FieldInit->getAnyMember(),
4211 BaseClass: FieldInit->getBaseClass());
4212 } else {
4213 UninitializedChecker.CheckInitializer(E: InitExpr, FieldConstructor: nullptr,
4214 Field: FieldInit->getAnyMember(),
4215 BaseClass: FieldInit->getBaseClass());
4216 }
4217 }
4218 }
4219} // namespace
4220
4221void Sema::ActOnStartCXXInClassMemberInitializer() {
4222 // Create a synthetic function scope to represent the call to the constructor
4223 // that notionally surrounds a use of this initializer.
4224 PushFunctionScope();
4225}
4226
4227void Sema::ActOnStartTrailingRequiresClause(Scope *S, Declarator &D) {
4228 if (!D.isFunctionDeclarator())
4229 return;
4230 auto &FTI = D.getFunctionTypeInfo();
4231 if (!FTI.Params)
4232 return;
4233 for (auto &Param : ArrayRef<DeclaratorChunk::ParamInfo>(FTI.Params,
4234 FTI.NumParams)) {
4235 auto *ParamDecl = cast<NamedDecl>(Val: Param.Param);
4236 if (ParamDecl->getDeclName())
4237 PushOnScopeChains(D: ParamDecl, S, /*AddToContext=*/false);
4238 }
4239}
4240
4241ExprResult Sema::ActOnFinishTrailingRequiresClause(ExprResult ConstraintExpr) {
4242 return ActOnRequiresClause(ConstraintExpr);
4243}
4244
4245ExprResult Sema::ActOnRequiresClause(ExprResult ConstraintExpr) {
4246 if (ConstraintExpr.isInvalid())
4247 return ExprError();
4248
4249 if (DiagnoseUnexpandedParameterPack(E: ConstraintExpr.get(),
4250 UPPC: UPPC_RequiresClause))
4251 return ExprError();
4252
4253 return ConstraintExpr;
4254}
4255
4256ExprResult Sema::ConvertMemberDefaultInitExpression(FieldDecl *FD,
4257 Expr *InitExpr,
4258 SourceLocation InitLoc) {
4259 InitializedEntity Entity =
4260 InitializedEntity::InitializeMemberFromDefaultMemberInitializer(Member: FD);
4261 return ConvertMemberDefaultInitExpression(FD, Entity, InitExpr, InitLoc);
4262}
4263
4264ExprResult Sema::ConvertMemberDefaultInitExpression(
4265 FieldDecl *FD, const InitializedEntity &Entity, Expr *InitExpr,
4266 SourceLocation InitLoc) {
4267 InitializationKind Kind =
4268 FD->getInClassInitStyle() == ICIS_ListInit
4269 ? InitializationKind::CreateDirectList(InitLoc: InitExpr->getBeginLoc(),
4270 LBraceLoc: InitExpr->getBeginLoc(),
4271 RBraceLoc: InitExpr->getEndLoc())
4272 : InitializationKind::CreateCopy(InitLoc: InitExpr->getBeginLoc(), EqualLoc: InitLoc);
4273 InitializationSequence Seq(*this, Entity, Kind, InitExpr);
4274 return Seq.Perform(S&: *this, Entity, Kind, Args: InitExpr);
4275}
4276
4277void Sema::ActOnFinishCXXInClassMemberInitializer(Decl *D,
4278 SourceLocation InitLoc,
4279 ExprResult InitExpr) {
4280 // Pop the notional constructor scope we created earlier.
4281 PopFunctionScopeInfo(WP: nullptr, D);
4282
4283 // Microsoft C++'s property declaration cannot have a default member
4284 // initializer.
4285 if (isa<MSPropertyDecl>(Val: D)) {
4286 D->setInvalidDecl();
4287 return;
4288 }
4289
4290 FieldDecl *FD = dyn_cast<FieldDecl>(Val: D);
4291 assert((FD && FD->getInClassInitStyle() != ICIS_NoInit) &&
4292 "must set init style when field is created");
4293
4294 if (!InitExpr.isUsable() ||
4295 DiagnoseUnexpandedParameterPack(E: InitExpr.get(), UPPC: UPPC_Initializer)) {
4296 FD->setInvalidDecl();
4297 ExprResult RecoveryInit =
4298 CreateRecoveryExpr(Begin: InitLoc, End: InitLoc, SubExprs: {}, T: FD->getType());
4299 if (RecoveryInit.isUsable())
4300 FD->setInClassInitializer(RecoveryInit.get());
4301 return;
4302 }
4303
4304 if (!FD->getType()->isDependentType() && !InitExpr.get()->isTypeDependent()) {
4305 InitExpr = ConvertMemberDefaultInitExpression(FD, InitExpr: InitExpr.get(), InitLoc);
4306 // C++11 [class.base.init]p7:
4307 // The initialization of each base and member constitutes a
4308 // full-expression.
4309 if (!InitExpr.isInvalid())
4310 InitExpr = ActOnFinishFullExpr(Expr: InitExpr.get(), /*DiscarededValue=*/DiscardedValue: false);
4311 if (InitExpr.isInvalid()) {
4312 FD->setInvalidDecl();
4313 return;
4314 }
4315 }
4316
4317 FD->setInClassInitializer(InitExpr.get());
4318}
4319
4320/// Find the direct and/or virtual base specifiers that
4321/// correspond to the given base type, for use in base initialization
4322/// within a constructor.
4323static bool FindBaseInitializer(Sema &SemaRef,
4324 CXXRecordDecl *ClassDecl,
4325 QualType BaseType,
4326 const CXXBaseSpecifier *&DirectBaseSpec,
4327 const CXXBaseSpecifier *&VirtualBaseSpec) {
4328 // First, check for a direct base class.
4329 DirectBaseSpec = nullptr;
4330 for (const auto &Base : ClassDecl->bases()) {
4331 if (SemaRef.Context.hasSameUnqualifiedType(T1: BaseType, T2: Base.getType())) {
4332 // We found a direct base of this type. That's what we're
4333 // initializing.
4334 DirectBaseSpec = &Base;
4335 break;
4336 }
4337 }
4338
4339 // Check for a virtual base class.
4340 // FIXME: We might be able to short-circuit this if we know in advance that
4341 // there are no virtual bases.
4342 VirtualBaseSpec = nullptr;
4343 if (!DirectBaseSpec || !DirectBaseSpec->isVirtual()) {
4344 // We haven't found a base yet; search the class hierarchy for a
4345 // virtual base class.
4346 CXXBasePaths Paths(/*FindAmbiguities=*/true, /*RecordPaths=*/true,
4347 /*DetectVirtual=*/false);
4348 if (SemaRef.IsDerivedFrom(Loc: ClassDecl->getLocation(),
4349 Derived: SemaRef.Context.getCanonicalTagType(TD: ClassDecl),
4350 Base: BaseType, Paths)) {
4351 for (const CXXBasePath &Path : Paths) {
4352 if (Path.back().Base->isVirtual()) {
4353 VirtualBaseSpec = Path.back().Base;
4354 break;
4355 }
4356 }
4357 }
4358 }
4359
4360 return DirectBaseSpec || VirtualBaseSpec;
4361}
4362
4363MemInitResult
4364Sema::ActOnMemInitializer(Decl *ConstructorD,
4365 Scope *S,
4366 CXXScopeSpec &SS,
4367 IdentifierInfo *MemberOrBase,
4368 ParsedType TemplateTypeTy,
4369 const DeclSpec &DS,
4370 SourceLocation IdLoc,
4371 Expr *InitList,
4372 SourceLocation EllipsisLoc) {
4373 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4374 DS, IdLoc, Init: InitList,
4375 EllipsisLoc);
4376}
4377
4378MemInitResult
4379Sema::ActOnMemInitializer(Decl *ConstructorD,
4380 Scope *S,
4381 CXXScopeSpec &SS,
4382 IdentifierInfo *MemberOrBase,
4383 ParsedType TemplateTypeTy,
4384 const DeclSpec &DS,
4385 SourceLocation IdLoc,
4386 SourceLocation LParenLoc,
4387 ArrayRef<Expr *> Args,
4388 SourceLocation RParenLoc,
4389 SourceLocation EllipsisLoc) {
4390 Expr *List = ParenListExpr::Create(Ctx: Context, LParenLoc, Exprs: Args, RParenLoc);
4391 return BuildMemInitializer(ConstructorD, S, SS, MemberOrBase, TemplateTypeTy,
4392 DS, IdLoc, Init: List, EllipsisLoc);
4393}
4394
4395namespace {
4396
4397// Callback to only accept typo corrections that can be a valid C++ member
4398// initializer: either a non-static field member or a base class.
4399class MemInitializerValidatorCCC final : public CorrectionCandidateCallback {
4400public:
4401 explicit MemInitializerValidatorCCC(CXXRecordDecl *ClassDecl)
4402 : ClassDecl(ClassDecl) {}
4403
4404 bool ValidateCandidate(const TypoCorrection &candidate) override {
4405 if (NamedDecl *ND = candidate.getCorrectionDecl()) {
4406 if (FieldDecl *Member = dyn_cast<FieldDecl>(Val: ND))
4407 return Member->getDeclContext()->getRedeclContext()->Equals(DC: ClassDecl);
4408 return isa<TypeDecl>(Val: ND);
4409 }
4410 return false;
4411 }
4412
4413 std::unique_ptr<CorrectionCandidateCallback> clone() override {
4414 return std::make_unique<MemInitializerValidatorCCC>(args&: *this);
4415 }
4416
4417private:
4418 CXXRecordDecl *ClassDecl;
4419};
4420
4421}
4422
4423bool Sema::DiagRedefinedPlaceholderFieldDecl(SourceLocation Loc,
4424 RecordDecl *ClassDecl,
4425 const IdentifierInfo *Name) {
4426 DeclContextLookupResult Result = ClassDecl->lookup(Name);
4427 DeclContextLookupResult::iterator Found =
4428 llvm::find_if(Range&: Result, P: [this](const NamedDecl *Elem) {
4429 return isa<FieldDecl, IndirectFieldDecl>(Val: Elem) &&
4430 Elem->isPlaceholderVar(LangOpts: getLangOpts());
4431 });
4432 // We did not find a placeholder variable
4433 if (Found == Result.end())
4434 return false;
4435 Diag(Loc, DiagID: diag::err_using_placeholder_variable) << Name;
4436 for (DeclContextLookupResult::iterator It = Found; It != Result.end(); It++) {
4437 const NamedDecl *ND = *It;
4438 if (ND->getDeclContext() != ND->getDeclContext())
4439 break;
4440 if (isa<FieldDecl, IndirectFieldDecl>(Val: ND) &&
4441 ND->isPlaceholderVar(LangOpts: getLangOpts()))
4442 Diag(Loc: ND->getLocation(), DiagID: diag::note_reference_placeholder) << ND;
4443 }
4444 return true;
4445}
4446
4447ValueDecl *
4448Sema::tryLookupUnambiguousFieldDecl(RecordDecl *ClassDecl,
4449 const IdentifierInfo *MemberOrBase) {
4450 ValueDecl *ND = nullptr;
4451 for (auto *D : ClassDecl->lookup(Name: MemberOrBase)) {
4452 if (isa<FieldDecl, IndirectFieldDecl>(Val: D)) {
4453 bool IsPlaceholder = D->isPlaceholderVar(LangOpts: getLangOpts());
4454 if (ND) {
4455 if (IsPlaceholder && D->getDeclContext() == ND->getDeclContext())
4456 return nullptr;
4457 break;
4458 }
4459 if (!IsPlaceholder)
4460 return cast<ValueDecl>(Val: D);
4461 ND = cast<ValueDecl>(Val: D);
4462 }
4463 }
4464 return ND;
4465}
4466
4467ValueDecl *Sema::tryLookupCtorInitMemberDecl(CXXRecordDecl *ClassDecl,
4468 CXXScopeSpec &SS,
4469 ParsedType TemplateTypeTy,
4470 IdentifierInfo *MemberOrBase) {
4471 if (SS.getScopeRep() || TemplateTypeTy)
4472 return nullptr;
4473 return tryLookupUnambiguousFieldDecl(ClassDecl, MemberOrBase);
4474}
4475
4476MemInitResult
4477Sema::BuildMemInitializer(Decl *ConstructorD,
4478 Scope *S,
4479 CXXScopeSpec &SS,
4480 IdentifierInfo *MemberOrBase,
4481 ParsedType TemplateTypeTy,
4482 const DeclSpec &DS,
4483 SourceLocation IdLoc,
4484 Expr *Init,
4485 SourceLocation EllipsisLoc) {
4486 if (!ConstructorD || !Init)
4487 return true;
4488
4489 AdjustDeclIfTemplate(Decl&: ConstructorD);
4490
4491 CXXConstructorDecl *Constructor
4492 = dyn_cast<CXXConstructorDecl>(Val: ConstructorD);
4493 if (!Constructor) {
4494 // The user wrote a constructor initializer on a function that is
4495 // not a C++ constructor. Ignore the error for now, because we may
4496 // have more member initializers coming; we'll diagnose it just
4497 // once in ActOnMemInitializers.
4498 return true;
4499 }
4500
4501 CXXRecordDecl *ClassDecl = Constructor->getParent();
4502
4503 // C++ [class.base.init]p2:
4504 // Names in a mem-initializer-id are looked up in the scope of the
4505 // constructor's class and, if not found in that scope, are looked
4506 // up in the scope containing the constructor's definition.
4507 // [Note: if the constructor's class contains a member with the
4508 // same name as a direct or virtual base class of the class, a
4509 // mem-initializer-id naming the member or base class and composed
4510 // of a single identifier refers to the class member. A
4511 // mem-initializer-id for the hidden base class may be specified
4512 // using a qualified name. ]
4513
4514 // Look for a member, first.
4515 if (ValueDecl *Member = tryLookupCtorInitMemberDecl(
4516 ClassDecl, SS, TemplateTypeTy, MemberOrBase)) {
4517 if (EllipsisLoc.isValid())
4518 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_member_init)
4519 << MemberOrBase
4520 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4521
4522 return BuildMemberInitializer(Member, Init, IdLoc);
4523 }
4524 // It didn't name a member, so see if it names a class.
4525 QualType BaseType;
4526 TypeSourceInfo *TInfo = nullptr;
4527
4528 if (TemplateTypeTy) {
4529 BaseType = GetTypeFromParser(Ty: TemplateTypeTy, TInfo: &TInfo);
4530 if (BaseType.isNull())
4531 return true;
4532 } else if (DS.getTypeSpecType() == TST_decltype) {
4533 BaseType = BuildDecltypeType(E: DS.getRepAsExpr());
4534 } else if (DS.getTypeSpecType() == TST_decltype_auto) {
4535 Diag(Loc: DS.getTypeSpecTypeLoc(), DiagID: diag::err_decltype_auto_invalid);
4536 return true;
4537 } else if (DS.getTypeSpecType() == TST_typename_pack_indexing) {
4538 BaseType =
4539 BuildPackIndexingType(Pattern: DS.getRepAsType().get(), IndexExpr: DS.getPackIndexingExpr(),
4540 Loc: DS.getBeginLoc(), EllipsisLoc: DS.getEllipsisLoc());
4541 } else {
4542 LookupResult R(*this, MemberOrBase, IdLoc, LookupOrdinaryName);
4543 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
4544
4545 TypeDecl *TyD = R.getAsSingle<TypeDecl>();
4546 if (!TyD) {
4547 if (R.isAmbiguous()) return true;
4548
4549 // We don't want access-control diagnostics here.
4550 R.suppressDiagnostics();
4551
4552 if (SS.isSet() && isDependentScopeSpecifier(SS)) {
4553 bool NotUnknownSpecialization = false;
4554 DeclContext *DC = computeDeclContext(SS, EnteringContext: false);
4555 if (CXXRecordDecl *Record = dyn_cast_or_null<CXXRecordDecl>(Val: DC))
4556 NotUnknownSpecialization = !Record->hasAnyDependentBases();
4557
4558 if (!NotUnknownSpecialization) {
4559 // When the scope specifier can refer to a member of an unknown
4560 // specialization, we take it as a type name.
4561 BaseType = CheckTypenameType(
4562 Keyword: ElaboratedTypeKeyword::None, KeywordLoc: SourceLocation(),
4563 QualifierLoc: SS.getWithLocInContext(Context), II: *MemberOrBase, IILoc: IdLoc);
4564 if (BaseType.isNull())
4565 return true;
4566
4567 TInfo = Context.CreateTypeSourceInfo(T: BaseType);
4568 DependentNameTypeLoc TL =
4569 TInfo->getTypeLoc().castAs<DependentNameTypeLoc>();
4570 if (!TL.isNull()) {
4571 TL.setNameLoc(IdLoc);
4572 TL.setElaboratedKeywordLoc(SourceLocation());
4573 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4574 }
4575
4576 R.clear();
4577 R.setLookupName(MemberOrBase);
4578 }
4579 }
4580
4581 if (getLangOpts().MSVCCompat && !getLangOpts().CPlusPlus20) {
4582 if (auto UnqualifiedBase = R.getAsSingle<ClassTemplateDecl>()) {
4583 auto *TempSpec = cast<TemplateSpecializationType>(
4584 Val: UnqualifiedBase->getCanonicalInjectedSpecializationType(Ctx: Context));
4585 TemplateName TN = TempSpec->getTemplateName();
4586 for (auto const &Base : ClassDecl->bases()) {
4587 auto BaseTemplate =
4588 Base.getType()->getAs<TemplateSpecializationType>();
4589 if (BaseTemplate &&
4590 Context.hasSameTemplateName(X: BaseTemplate->getTemplateName(), Y: TN,
4591 /*IgnoreDeduced=*/true)) {
4592 Diag(Loc: IdLoc, DiagID: diag::ext_unqualified_base_class)
4593 << SourceRange(IdLoc, Init->getSourceRange().getEnd());
4594 BaseType = Base.getType();
4595 break;
4596 }
4597 }
4598 }
4599 }
4600
4601 // If no results were found, try to correct typos.
4602 TypoCorrection Corr;
4603 MemInitializerValidatorCCC CCC(ClassDecl);
4604 if (R.empty() && BaseType.isNull() &&
4605 (Corr =
4606 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS,
4607 CCC, Mode: CorrectTypoKind::ErrorRecovery, MemberContext: ClassDecl))) {
4608 if (FieldDecl *Member = Corr.getCorrectionDeclAs<FieldDecl>()) {
4609 // We have found a non-static data member with a similar
4610 // name to what was typed; complain and initialize that
4611 // member.
4612 diagnoseTypo(Correction: Corr,
4613 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4614 << MemberOrBase << true);
4615 return BuildMemberInitializer(Member, Init, IdLoc);
4616 } else if (TypeDecl *Type = Corr.getCorrectionDeclAs<TypeDecl>()) {
4617 const CXXBaseSpecifier *DirectBaseSpec;
4618 const CXXBaseSpecifier *VirtualBaseSpec;
4619 if (FindBaseInitializer(SemaRef&: *this, ClassDecl,
4620 BaseType: Context.getTypeDeclType(Decl: Type),
4621 DirectBaseSpec, VirtualBaseSpec)) {
4622 // We have found a direct or virtual base class with a
4623 // similar name to what was typed; complain and initialize
4624 // that base class.
4625 diagnoseTypo(Correction: Corr,
4626 TypoDiag: PDiag(DiagID: diag::err_mem_init_not_member_or_class_suggest)
4627 << MemberOrBase << false,
4628 PrevNote: PDiag() /*Suppress note, we provide our own.*/);
4629
4630 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec ? DirectBaseSpec
4631 : VirtualBaseSpec;
4632 Diag(Loc: BaseSpec->getBeginLoc(), DiagID: diag::note_base_class_specified_here)
4633 << BaseSpec->getType() << BaseSpec->getSourceRange();
4634
4635 TyD = Type;
4636 }
4637 }
4638 }
4639
4640 if (!TyD && BaseType.isNull()) {
4641 Diag(Loc: IdLoc, DiagID: diag::err_mem_init_not_member_or_class)
4642 << MemberOrBase << SourceRange(IdLoc,Init->getSourceRange().getEnd());
4643 return true;
4644 }
4645 }
4646
4647 if (BaseType.isNull()) {
4648 MarkAnyDeclReferenced(Loc: TyD->getLocation(), D: TyD, /*OdrUse=*/MightBeOdrUse: false);
4649
4650 TypeLocBuilder TLB;
4651 // FIXME: This is missing building the UsingType for TyD, if any.
4652 if (const auto *TD = dyn_cast<TagDecl>(Val: TyD)) {
4653 BaseType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
4654 Qualifier: SS.getScopeRep(), TD, /*OwnsTag=*/false);
4655 auto TL = TLB.push<TagTypeLoc>(T: BaseType);
4656 TL.setElaboratedKeywordLoc(SourceLocation());
4657 TL.setQualifierLoc(SS.getWithLocInContext(Context));
4658 TL.setNameLoc(IdLoc);
4659 } else if (auto *TN = dyn_cast<TypedefNameDecl>(Val: TyD)) {
4660 BaseType = Context.getTypedefType(Keyword: ElaboratedTypeKeyword::None,
4661 Qualifier: SS.getScopeRep(), Decl: TN);
4662 TLB.push<TypedefTypeLoc>(T: BaseType).set(
4663 /*ElaboratedKeywordLoc=*/SourceLocation(),
4664 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4665 } else if (auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: TyD)) {
4666 BaseType = Context.getUnresolvedUsingType(Keyword: ElaboratedTypeKeyword::None,
4667 Qualifier: SS.getScopeRep(), D: UD);
4668 TLB.push<UnresolvedUsingTypeLoc>(T: BaseType).set(
4669 /*ElaboratedKeywordLoc=*/SourceLocation(),
4670 QualifierLoc: SS.getWithLocInContext(Context), NameLoc: IdLoc);
4671 } else {
4672 // FIXME: What else can appear here?
4673 assert(SS.isEmpty());
4674 BaseType = Context.getTypeDeclType(Decl: TyD);
4675 TLB.pushTypeSpec(T: BaseType).setNameLoc(IdLoc);
4676 }
4677 TInfo = TLB.getTypeSourceInfo(Context, T: BaseType);
4678 }
4679 }
4680
4681 if (!TInfo)
4682 TInfo = Context.getTrivialTypeSourceInfo(T: BaseType, Loc: IdLoc);
4683
4684 return BuildBaseInitializer(BaseType, BaseTInfo: TInfo, Init, ClassDecl, EllipsisLoc);
4685}
4686
4687MemInitResult
4688Sema::BuildMemberInitializer(ValueDecl *Member, Expr *Init,
4689 SourceLocation IdLoc) {
4690 FieldDecl *DirectMember = dyn_cast<FieldDecl>(Val: Member);
4691 IndirectFieldDecl *IndirectMember = dyn_cast<IndirectFieldDecl>(Val: Member);
4692 assert((DirectMember || IndirectMember) &&
4693 "Member must be a FieldDecl or IndirectFieldDecl");
4694
4695 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4696 return true;
4697
4698 if (Member->isInvalidDecl())
4699 return true;
4700
4701 MultiExprArg Args;
4702 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4703 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4704 } else if (InitListExpr *InitList = dyn_cast<InitListExpr>(Val: Init)) {
4705 Args = MultiExprArg(InitList->getInits(), InitList->getNumInits());
4706 } else if (auto *ParenListInit = dyn_cast<CXXParenListInitExpr>(Val: Init)) {
4707 // Template instantiation reverts the elements to their syntactic form;
4708 // redo the initialization from the written arguments.
4709 Args = ParenListInit->getUserSpecifiedInitExprs();
4710 } else {
4711 // Template instantiation doesn't reconstruct ParenListExprs for us.
4712 Args = Init;
4713 }
4714
4715 SourceRange InitRange = Init->getSourceRange();
4716
4717 if (Member->getType()->isDependentType() || Init->isTypeDependent()) {
4718 // Can't check initialization for a member of dependent type or when
4719 // any of the arguments are type-dependent expressions.
4720 DiscardCleanupsInEvaluationContext();
4721 } else {
4722 bool InitList = false;
4723 if (isa<InitListExpr>(Val: Init)) {
4724 InitList = true;
4725 Args = Init;
4726 }
4727
4728 // Initialize the member.
4729 InitializedEntity MemberEntity =
4730 DirectMember ? InitializedEntity::InitializeMember(Member: DirectMember, Parent: nullptr)
4731 : InitializedEntity::InitializeMember(Member: IndirectMember,
4732 Parent: nullptr);
4733 InitializationKind Kind =
4734 InitList ? InitializationKind::CreateDirectList(
4735 InitLoc: IdLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4736 : InitializationKind::CreateDirect(InitLoc: IdLoc, LParenLoc: InitRange.getBegin(),
4737 RParenLoc: InitRange.getEnd());
4738
4739 InitializationSequence InitSeq(*this, MemberEntity, Kind, Args);
4740 ExprResult MemberInit = InitSeq.Perform(S&: *this, Entity: MemberEntity, Kind, Args,
4741 ResultType: nullptr);
4742 if (!MemberInit.isInvalid()) {
4743 // C++11 [class.base.init]p7:
4744 // The initialization of each base and member constitutes a
4745 // full-expression.
4746 MemberInit = ActOnFinishFullExpr(Expr: MemberInit.get(), CC: InitRange.getBegin(),
4747 /*DiscardedValue*/ false);
4748 }
4749
4750 if (MemberInit.isInvalid()) {
4751 // Args were sensible expressions but we couldn't initialize the member
4752 // from them. Preserve them in a RecoveryExpr instead.
4753 Init = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(), SubExprs: Args,
4754 T: Member->getType())
4755 .get();
4756 if (!Init)
4757 return true;
4758 } else {
4759 Init = MemberInit.get();
4760 }
4761 }
4762
4763 if (DirectMember) {
4764 return new (Context) CXXCtorInitializer(Context, DirectMember, IdLoc,
4765 InitRange.getBegin(), Init,
4766 InitRange.getEnd());
4767 } else {
4768 return new (Context) CXXCtorInitializer(Context, IndirectMember, IdLoc,
4769 InitRange.getBegin(), Init,
4770 InitRange.getEnd());
4771 }
4772}
4773
4774MemInitResult
4775Sema::BuildDelegatingInitializer(TypeSourceInfo *TInfo, Expr *Init,
4776 CXXRecordDecl *ClassDecl) {
4777 SourceLocation NameLoc = TInfo->getTypeLoc().getSourceRange().getBegin();
4778 if (!LangOpts.CPlusPlus11)
4779 return Diag(Loc: NameLoc, DiagID: diag::err_delegating_ctor)
4780 << TInfo->getTypeLoc().getSourceRange();
4781 Diag(Loc: NameLoc, DiagID: diag::warn_cxx98_compat_delegating_ctor);
4782
4783 bool InitList = true;
4784 MultiExprArg Args = Init;
4785 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4786 InitList = false;
4787 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4788 }
4789
4790 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
4791
4792 SourceRange InitRange = Init->getSourceRange();
4793 // Initialize the object.
4794 InitializedEntity DelegationEntity =
4795 InitializedEntity::InitializeDelegation(Type: ClassType);
4796 InitializationKind Kind =
4797 InitList ? InitializationKind::CreateDirectList(
4798 InitLoc: NameLoc, LBraceLoc: Init->getBeginLoc(), RBraceLoc: Init->getEndLoc())
4799 : InitializationKind::CreateDirect(InitLoc: NameLoc, LParenLoc: InitRange.getBegin(),
4800 RParenLoc: InitRange.getEnd());
4801 InitializationSequence InitSeq(*this, DelegationEntity, Kind, Args);
4802 ExprResult DelegationInit = InitSeq.Perform(S&: *this, Entity: DelegationEntity, Kind,
4803 Args, ResultType: nullptr);
4804 if (!DelegationInit.isInvalid()) {
4805 assert((DelegationInit.get()->containsErrors() ||
4806 cast<CXXConstructExpr>(DelegationInit.get())->getConstructor()) &&
4807 "Delegating constructor with no target?");
4808
4809 // C++11 [class.base.init]p7:
4810 // The initialization of each base and member constitutes a
4811 // full-expression.
4812 DelegationInit = ActOnFinishFullExpr(
4813 Expr: DelegationInit.get(), CC: InitRange.getBegin(), /*DiscardedValue*/ false);
4814 }
4815
4816 if (DelegationInit.isInvalid()) {
4817 DelegationInit = CreateRecoveryExpr(Begin: InitRange.getBegin(),
4818 End: InitRange.getEnd(), SubExprs: Args, T: ClassType);
4819 if (DelegationInit.isInvalid())
4820 return true;
4821 } else {
4822 // If we are in a dependent context, template instantiation will
4823 // perform this type-checking again. Just save the arguments that we
4824 // received in a ParenListExpr.
4825 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4826 // of the information that we have about the base
4827 // initializer. However, deconstructing the ASTs is a dicey process,
4828 // and this approach is far more likely to get the corner cases right.
4829 if (CurContext->isDependentContext())
4830 DelegationInit = Init;
4831 }
4832
4833 return new (Context) CXXCtorInitializer(Context, TInfo, InitRange.getBegin(),
4834 DelegationInit.getAs<Expr>(),
4835 InitRange.getEnd());
4836}
4837
4838MemInitResult
4839Sema::BuildBaseInitializer(QualType BaseType, TypeSourceInfo *BaseTInfo,
4840 Expr *Init, CXXRecordDecl *ClassDecl,
4841 SourceLocation EllipsisLoc) {
4842 SourceLocation BaseLoc = BaseTInfo->getTypeLoc().getBeginLoc();
4843
4844 if (!BaseType->isDependentType() && !BaseType->isRecordType())
4845 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_does_not_name_class)
4846 << BaseType << BaseTInfo->getTypeLoc().getSourceRange();
4847
4848 // C++ [class.base.init]p2:
4849 // [...] Unless the mem-initializer-id names a nonstatic data
4850 // member of the constructor's class or a direct or virtual base
4851 // of that class, the mem-initializer is ill-formed. A
4852 // mem-initializer-list can initialize a base class using any
4853 // name that denotes that base class type.
4854
4855 // We can store the initializers in "as-written" form and delay analysis until
4856 // instantiation if the constructor is dependent. But not for dependent
4857 // (broken) code in a non-template! SetCtorInitializers does not expect this.
4858 bool Dependent = CurContext->isDependentContext() &&
4859 (BaseType->isDependentType() || Init->isTypeDependent());
4860
4861 SourceRange InitRange = Init->getSourceRange();
4862 if (EllipsisLoc.isValid()) {
4863 // This is a pack expansion.
4864 if (!BaseType->containsUnexpandedParameterPack()) {
4865 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
4866 << SourceRange(BaseLoc, InitRange.getEnd());
4867
4868 EllipsisLoc = SourceLocation();
4869 }
4870 } else {
4871 // Check for any unexpanded parameter packs.
4872 if (DiagnoseUnexpandedParameterPack(Loc: BaseLoc, T: BaseTInfo, UPPC: UPPC_Initializer))
4873 return true;
4874
4875 if (DiagnoseUnexpandedParameterPack(E: Init, UPPC: UPPC_Initializer))
4876 return true;
4877 }
4878
4879 // Check for direct and virtual base classes.
4880 const CXXBaseSpecifier *DirectBaseSpec = nullptr;
4881 const CXXBaseSpecifier *VirtualBaseSpec = nullptr;
4882 if (!Dependent) {
4883 if (declaresSameEntity(D1: ClassDecl, D2: BaseType->getAsCXXRecordDecl()))
4884 return BuildDelegatingInitializer(TInfo: BaseTInfo, Init, ClassDecl);
4885
4886 FindBaseInitializer(SemaRef&: *this, ClassDecl, BaseType, DirectBaseSpec,
4887 VirtualBaseSpec);
4888
4889 // C++ [base.class.init]p2:
4890 // Unless the mem-initializer-id names a nonstatic data member of the
4891 // constructor's class or a direct or virtual base of that class, the
4892 // mem-initializer is ill-formed.
4893 if (!DirectBaseSpec && !VirtualBaseSpec) {
4894 // If the class has any dependent bases, then it's possible that
4895 // one of those types will resolve to the same type as
4896 // BaseType. Therefore, just treat this as a dependent base
4897 // class initialization. FIXME: Should we try to check the
4898 // initialization anyway? It seems odd.
4899 if (ClassDecl->hasAnyDependentBases())
4900 Dependent = true;
4901 else
4902 return Diag(Loc: BaseLoc, DiagID: diag::err_not_direct_base_or_virtual)
4903 << BaseType << Context.getCanonicalTagType(TD: ClassDecl)
4904 << BaseTInfo->getTypeLoc().getSourceRange();
4905 }
4906 }
4907
4908 if (Dependent) {
4909 DiscardCleanupsInEvaluationContext();
4910
4911 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4912 /*IsVirtual=*/false,
4913 InitRange.getBegin(), Init,
4914 InitRange.getEnd(), EllipsisLoc);
4915 }
4916
4917 // C++ [base.class.init]p2:
4918 // If a mem-initializer-id is ambiguous because it designates both
4919 // a direct non-virtual base class and an inherited virtual base
4920 // class, the mem-initializer is ill-formed.
4921 if (DirectBaseSpec && VirtualBaseSpec)
4922 return Diag(Loc: BaseLoc, DiagID: diag::err_base_init_direct_and_virtual)
4923 << BaseType << BaseTInfo->getTypeLoc().getLocalSourceRange();
4924
4925 const CXXBaseSpecifier *BaseSpec = DirectBaseSpec;
4926 if (!BaseSpec)
4927 BaseSpec = VirtualBaseSpec;
4928
4929 // Initialize the base.
4930 bool InitList = true;
4931 MultiExprArg Args = Init;
4932 if (ParenListExpr *ParenList = dyn_cast<ParenListExpr>(Val: Init)) {
4933 InitList = false;
4934 Args = MultiExprArg(ParenList->getExprs(), ParenList->getNumExprs());
4935 }
4936
4937 InitializedEntity BaseEntity =
4938 InitializedEntity::InitializeBase(Context, Base: BaseSpec, IsInheritedVirtualBase: VirtualBaseSpec);
4939 InitializationKind Kind =
4940 InitList ? InitializationKind::CreateDirectList(InitLoc: BaseLoc)
4941 : InitializationKind::CreateDirect(InitLoc: BaseLoc, LParenLoc: InitRange.getBegin(),
4942 RParenLoc: InitRange.getEnd());
4943 InitializationSequence InitSeq(*this, BaseEntity, Kind, Args);
4944 ExprResult BaseInit = InitSeq.Perform(S&: *this, Entity: BaseEntity, Kind, Args, ResultType: nullptr);
4945 if (!BaseInit.isInvalid()) {
4946 // C++11 [class.base.init]p7:
4947 // The initialization of each base and member constitutes a
4948 // full-expression.
4949 BaseInit = ActOnFinishFullExpr(Expr: BaseInit.get(), CC: InitRange.getBegin(),
4950 /*DiscardedValue*/ false);
4951 }
4952
4953 if (BaseInit.isInvalid()) {
4954 BaseInit = CreateRecoveryExpr(Begin: InitRange.getBegin(), End: InitRange.getEnd(),
4955 SubExprs: Args, T: BaseType);
4956 if (BaseInit.isInvalid())
4957 return true;
4958 } else {
4959 // If we are in a dependent context, template instantiation will
4960 // perform this type-checking again. Just save the arguments that we
4961 // received in a ParenListExpr.
4962 // FIXME: This isn't quite ideal, since our ASTs don't capture all
4963 // of the information that we have about the base
4964 // initializer. However, deconstructing the ASTs is a dicey process,
4965 // and this approach is far more likely to get the corner cases right.
4966 if (CurContext->isDependentContext())
4967 BaseInit = Init;
4968 }
4969
4970 return new (Context) CXXCtorInitializer(Context, BaseTInfo,
4971 BaseSpec->isVirtual(),
4972 InitRange.getBegin(),
4973 BaseInit.getAs<Expr>(),
4974 InitRange.getEnd(), EllipsisLoc);
4975}
4976
4977// Create a static_cast\<T&&>(expr).
4978static Expr *CastForMoving(Sema &SemaRef, Expr *E) {
4979 QualType TargetType =
4980 SemaRef.BuildReferenceType(T: E->getType(), /*SpelledAsLValue*/ LValueRef: false,
4981 Loc: SourceLocation(), Entity: DeclarationName());
4982 SourceLocation ExprLoc = E->getBeginLoc();
4983 TypeSourceInfo *TargetLoc = SemaRef.Context.getTrivialTypeSourceInfo(
4984 T: TargetType, Loc: ExprLoc);
4985
4986 return SemaRef.BuildCXXNamedCast(OpLoc: ExprLoc, Kind: tok::kw_static_cast, Ty: TargetLoc, E,
4987 AngleBrackets: SourceRange(ExprLoc, ExprLoc),
4988 Parens: E->getSourceRange()).get();
4989}
4990
4991/// ImplicitInitializerKind - How an implicit base or member initializer should
4992/// initialize its base or member.
4993enum ImplicitInitializerKind {
4994 IIK_Default,
4995 IIK_Copy,
4996 IIK_Move,
4997 IIK_Inherit
4998};
4999
5000static bool
5001BuildImplicitBaseInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5002 ImplicitInitializerKind ImplicitInitKind,
5003 CXXBaseSpecifier *BaseSpec,
5004 bool IsInheritedVirtualBase,
5005 CXXCtorInitializer *&CXXBaseInit) {
5006 InitializedEntity InitEntity
5007 = InitializedEntity::InitializeBase(Context&: SemaRef.Context, Base: BaseSpec,
5008 IsInheritedVirtualBase);
5009
5010 ExprResult BaseInit;
5011
5012 switch (ImplicitInitKind) {
5013 case IIK_Inherit:
5014 case IIK_Default: {
5015 InitializationKind InitKind
5016 = InitializationKind::CreateDefault(InitLoc: Constructor->getLocation());
5017 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5018 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5019 break;
5020 }
5021
5022 case IIK_Move:
5023 case IIK_Copy: {
5024 bool Moving = ImplicitInitKind == IIK_Move;
5025 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5026 QualType ParamType = Param->getType().getNonReferenceType();
5027
5028 Expr *CopyCtorArg =
5029 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5030 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5031 NameLoc: Constructor->getLocation(), T: ParamType,
5032 VK: VK_LValue, FoundD: nullptr);
5033
5034 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: CopyCtorArg));
5035
5036 // Cast to the base class to avoid ambiguities.
5037 QualType ArgTy =
5038 SemaRef.Context.getQualifiedType(T: BaseSpec->getType().getUnqualifiedType(),
5039 Qs: ParamType.getQualifiers());
5040
5041 if (Moving) {
5042 CopyCtorArg = CastForMoving(SemaRef, E: CopyCtorArg);
5043 }
5044
5045 CXXCastPath BasePath;
5046 BasePath.push_back(Elt: BaseSpec);
5047 CopyCtorArg = SemaRef.ImpCastExprToType(E: CopyCtorArg, Type: ArgTy,
5048 CK: CK_UncheckedDerivedToBase,
5049 VK: Moving ? VK_XValue : VK_LValue,
5050 BasePath: &BasePath).get();
5051
5052 InitializationKind InitKind
5053 = InitializationKind::CreateDirect(InitLoc: Constructor->getLocation(),
5054 LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5055 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, CopyCtorArg);
5056 BaseInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: CopyCtorArg);
5057 break;
5058 }
5059 }
5060
5061 BaseInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: BaseInit);
5062 if (BaseInit.isInvalid())
5063 return true;
5064
5065 CXXBaseInit =
5066 new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5067 SemaRef.Context.getTrivialTypeSourceInfo(T: BaseSpec->getType(),
5068 Loc: SourceLocation()),
5069 BaseSpec->isVirtual(),
5070 SourceLocation(),
5071 BaseInit.getAs<Expr>(),
5072 SourceLocation(),
5073 SourceLocation());
5074
5075 return false;
5076}
5077
5078static bool RefersToRValueRef(Expr *MemRef) {
5079 ValueDecl *Referenced = cast<MemberExpr>(Val: MemRef)->getMemberDecl();
5080 return Referenced->getType()->isRValueReferenceType();
5081}
5082
5083static bool
5084BuildImplicitMemberInitializer(Sema &SemaRef, CXXConstructorDecl *Constructor,
5085 ImplicitInitializerKind ImplicitInitKind,
5086 FieldDecl *Field, IndirectFieldDecl *Indirect,
5087 CXXCtorInitializer *&CXXMemberInit) {
5088 if (Field->isInvalidDecl())
5089 return true;
5090
5091 SourceLocation Loc = Constructor->getLocation();
5092
5093 if (ImplicitInitKind == IIK_Copy || ImplicitInitKind == IIK_Move) {
5094 bool Moving = ImplicitInitKind == IIK_Move;
5095 ParmVarDecl *Param = Constructor->getParamDecl(i: 0);
5096 QualType ParamType = Param->getType().getNonReferenceType();
5097
5098 // Suppress copying zero-width bitfields.
5099 if (Field->isZeroLengthBitField())
5100 return false;
5101
5102 Expr *MemberExprBase =
5103 DeclRefExpr::Create(Context: SemaRef.Context, QualifierLoc: NestedNameSpecifierLoc(),
5104 TemplateKWLoc: SourceLocation(), D: Param, RefersToEnclosingVariableOrCapture: false,
5105 NameLoc: Loc, T: ParamType, VK: VK_LValue, FoundD: nullptr);
5106
5107 SemaRef.MarkDeclRefReferenced(E: cast<DeclRefExpr>(Val: MemberExprBase));
5108
5109 if (Moving) {
5110 MemberExprBase = CastForMoving(SemaRef, E: MemberExprBase);
5111 }
5112
5113 // Build a reference to this field within the parameter.
5114 CXXScopeSpec SS;
5115 LookupResult MemberLookup(SemaRef, Field->getDeclName(), Loc,
5116 Sema::LookupMemberName);
5117 MemberLookup.addDecl(D: Indirect ? cast<ValueDecl>(Val: Indirect)
5118 : cast<ValueDecl>(Val: Field), AS: AS_public);
5119 MemberLookup.resolveKind();
5120 ExprResult CtorArg
5121 = SemaRef.BuildMemberReferenceExpr(Base: MemberExprBase,
5122 BaseType: ParamType, OpLoc: Loc,
5123 /*IsArrow=*/false,
5124 SS,
5125 /*TemplateKWLoc=*/SourceLocation(),
5126 /*FirstQualifierInScope=*/nullptr,
5127 R&: MemberLookup,
5128 /*TemplateArgs=*/nullptr,
5129 /*S*/nullptr);
5130 if (CtorArg.isInvalid())
5131 return true;
5132
5133 // C++11 [class.copy]p15:
5134 // - if a member m has rvalue reference type T&&, it is direct-initialized
5135 // with static_cast<T&&>(x.m);
5136 if (RefersToRValueRef(MemRef: CtorArg.get())) {
5137 CtorArg = CastForMoving(SemaRef, E: CtorArg.get());
5138 }
5139
5140 InitializedEntity Entity =
5141 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5142 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5143
5144 // Direct-initialize to use the copy constructor.
5145 InitializationKind InitKind =
5146 InitializationKind::CreateDirect(InitLoc: Loc, LParenLoc: SourceLocation(), RParenLoc: SourceLocation());
5147
5148 Expr *CtorArgE = CtorArg.getAs<Expr>();
5149 InitializationSequence InitSeq(SemaRef, Entity, InitKind, CtorArgE);
5150 ExprResult MemberInit =
5151 InitSeq.Perform(S&: SemaRef, Entity, Kind: InitKind, Args: MultiExprArg(&CtorArgE, 1));
5152 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5153 if (MemberInit.isInvalid())
5154 return true;
5155
5156 if (Indirect)
5157 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5158 SemaRef.Context, Indirect, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5159 else
5160 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(
5161 SemaRef.Context, Field, Loc, Loc, MemberInit.getAs<Expr>(), Loc);
5162 return false;
5163 }
5164
5165 assert((ImplicitInitKind == IIK_Default || ImplicitInitKind == IIK_Inherit) &&
5166 "Unhandled implicit init kind!");
5167
5168 QualType FieldBaseElementType =
5169 SemaRef.Context.getBaseElementType(QT: Field->getType());
5170
5171 if (FieldBaseElementType->isRecordType()) {
5172 InitializedEntity InitEntity =
5173 Indirect ? InitializedEntity::InitializeMemberImplicit(Member: Indirect)
5174 : InitializedEntity::InitializeMemberImplicit(Member: Field);
5175 InitializationKind InitKind =
5176 InitializationKind::CreateDefault(InitLoc: Loc);
5177
5178 InitializationSequence InitSeq(SemaRef, InitEntity, InitKind, {});
5179 ExprResult MemberInit = InitSeq.Perform(S&: SemaRef, Entity: InitEntity, Kind: InitKind, Args: {});
5180
5181 MemberInit = SemaRef.MaybeCreateExprWithCleanups(SubExpr: MemberInit);
5182 if (MemberInit.isInvalid())
5183 return true;
5184
5185 if (Indirect)
5186 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5187 Indirect, Loc,
5188 Loc,
5189 MemberInit.get(),
5190 Loc);
5191 else
5192 CXXMemberInit = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context,
5193 Field, Loc, Loc,
5194 MemberInit.get(),
5195 Loc);
5196 return false;
5197 }
5198
5199 if (!Field->getParent()->isUnion()) {
5200 if (FieldBaseElementType->isReferenceType()) {
5201 SemaRef.Diag(Loc: Constructor->getLocation(),
5202 DiagID: diag::err_uninitialized_member_in_ctor)
5203 << (int)Constructor->isImplicit()
5204 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 0
5205 << Field->getDeclName();
5206 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5207 return true;
5208 }
5209
5210 if (FieldBaseElementType.isConstQualified()) {
5211 SemaRef.Diag(Loc: Constructor->getLocation(),
5212 DiagID: diag::err_uninitialized_member_in_ctor)
5213 << (int)Constructor->isImplicit()
5214 << SemaRef.Context.getCanonicalTagType(TD: Constructor->getParent()) << 1
5215 << Field->getDeclName();
5216 SemaRef.Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
5217 return true;
5218 }
5219 }
5220
5221 if (FieldBaseElementType.hasNonTrivialObjCLifetime()) {
5222 // ARC and Weak:
5223 // Default-initialize Objective-C pointers to NULL.
5224 CXXMemberInit
5225 = new (SemaRef.Context) CXXCtorInitializer(SemaRef.Context, Field,
5226 Loc, Loc,
5227 new (SemaRef.Context) ImplicitValueInitExpr(Field->getType()),
5228 Loc);
5229 return false;
5230 }
5231
5232 // Nothing to initialize.
5233 CXXMemberInit = nullptr;
5234 return false;
5235}
5236
5237namespace {
5238struct BaseAndFieldInfo {
5239 Sema &S;
5240 CXXConstructorDecl *Ctor;
5241 bool AnyErrorsInInits;
5242 ImplicitInitializerKind IIK;
5243 llvm::DenseMap<const void *, CXXCtorInitializer*> AllBaseFields;
5244 SmallVector<CXXCtorInitializer*, 8> AllToInit;
5245 llvm::DenseMap<TagDecl*, FieldDecl*> ActiveUnionMember;
5246
5247 BaseAndFieldInfo(Sema &S, CXXConstructorDecl *Ctor, bool ErrorsInInits)
5248 : S(S), Ctor(Ctor), AnyErrorsInInits(ErrorsInInits) {
5249 bool Generated = Ctor->isImplicit() || Ctor->isDefaulted();
5250 if (Ctor->getInheritedConstructor())
5251 IIK = IIK_Inherit;
5252 else if (Generated && Ctor->isCopyConstructor())
5253 IIK = IIK_Copy;
5254 else if (Generated && Ctor->isMoveConstructor())
5255 IIK = IIK_Move;
5256 else
5257 IIK = IIK_Default;
5258 }
5259
5260 bool isImplicitCopyOrMove() const {
5261 switch (IIK) {
5262 case IIK_Copy:
5263 case IIK_Move:
5264 return true;
5265
5266 case IIK_Default:
5267 case IIK_Inherit:
5268 return false;
5269 }
5270
5271 llvm_unreachable("Invalid ImplicitInitializerKind!");
5272 }
5273
5274 bool addFieldInitializer(CXXCtorInitializer *Init) {
5275 AllToInit.push_back(Elt: Init);
5276
5277 // Check whether this initializer makes the field "used".
5278 if (Init->getInit()->HasSideEffects(Ctx: S.Context))
5279 S.UnusedPrivateFields.remove(X: Init->getAnyMember());
5280
5281 return false;
5282 }
5283
5284 bool isInactiveUnionMember(FieldDecl *Field) {
5285 RecordDecl *Record = Field->getParent();
5286 if (!Record->isUnion())
5287 return false;
5288
5289 if (FieldDecl *Active =
5290 ActiveUnionMember.lookup(Val: Record->getCanonicalDecl()))
5291 return Active != Field->getCanonicalDecl();
5292
5293 // In an implicit copy or move constructor, ignore any in-class initializer.
5294 if (isImplicitCopyOrMove())
5295 return true;
5296
5297 // If there's no explicit initialization, the field is active only if it
5298 // has an in-class initializer...
5299 if (Field->hasInClassInitializer())
5300 return false;
5301 // ... or it's an anonymous struct or union whose class has an in-class
5302 // initializer.
5303 if (!Field->isAnonymousStructOrUnion())
5304 return true;
5305 CXXRecordDecl *FieldRD = Field->getType()->getAsCXXRecordDecl();
5306 return !FieldRD->hasInClassInitializer();
5307 }
5308
5309 /// Determine whether the given field is, or is within, a union member
5310 /// that is inactive (because there was an initializer given for a different
5311 /// member of the union, or because the union was not initialized at all).
5312 bool isWithinInactiveUnionMember(FieldDecl *Field,
5313 IndirectFieldDecl *Indirect) {
5314 if (!Indirect)
5315 return isInactiveUnionMember(Field);
5316
5317 for (auto *C : Indirect->chain()) {
5318 FieldDecl *Field = dyn_cast<FieldDecl>(Val: C);
5319 if (Field && isInactiveUnionMember(Field))
5320 return true;
5321 }
5322 return false;
5323 }
5324};
5325}
5326
5327/// Determine whether the given type is an incomplete or zero-lenfgth
5328/// array type.
5329static bool isIncompleteOrZeroLengthArrayType(ASTContext &Context, QualType T) {
5330 if (T->isIncompleteArrayType())
5331 return true;
5332
5333 while (const ConstantArrayType *ArrayT = Context.getAsConstantArrayType(T)) {
5334 if (ArrayT->isZeroSize())
5335 return true;
5336
5337 T = ArrayT->getElementType();
5338 }
5339
5340 return false;
5341}
5342
5343static bool CollectFieldInitializer(Sema &SemaRef, BaseAndFieldInfo &Info,
5344 FieldDecl *Field,
5345 IndirectFieldDecl *Indirect = nullptr) {
5346 if (Field->isInvalidDecl())
5347 return false;
5348
5349 // Overwhelmingly common case: we have a direct initializer for this field.
5350 if (CXXCtorInitializer *Init =
5351 Info.AllBaseFields.lookup(Val: Field->getCanonicalDecl()))
5352 return Info.addFieldInitializer(Init);
5353
5354 // C++11 [class.base.init]p8:
5355 // if the entity is a non-static data member that has a
5356 // brace-or-equal-initializer and either
5357 // -- the constructor's class is a union and no other variant member of that
5358 // union is designated by a mem-initializer-id or
5359 // -- the constructor's class is not a union, and, if the entity is a member
5360 // of an anonymous union, no other member of that union is designated by
5361 // a mem-initializer-id,
5362 // the entity is initialized as specified in [dcl.init].
5363 //
5364 // We also apply the same rules to handle anonymous structs within anonymous
5365 // unions.
5366 if (Info.isWithinInactiveUnionMember(Field, Indirect))
5367 return false;
5368
5369 if (Field->hasInClassInitializer() && !Info.isImplicitCopyOrMove()) {
5370 ExprResult DIE =
5371 SemaRef.BuildCXXCtorDefaultInitExpr(Loc: Info.Ctor->getLocation(), Field);
5372 if (DIE.isInvalid())
5373 return true;
5374
5375 auto Entity = InitializedEntity::InitializeMemberImplicit(Member: Field);
5376 SemaRef.checkInitializerLifetime(Entity, Init: DIE.get());
5377
5378 CXXCtorInitializer *Init;
5379 if (Indirect)
5380 Init = new (SemaRef.Context)
5381 CXXCtorInitializer(SemaRef.Context, Indirect, SourceLocation(),
5382 SourceLocation(), DIE.get(), SourceLocation());
5383 else
5384 Init = new (SemaRef.Context)
5385 CXXCtorInitializer(SemaRef.Context, Field, SourceLocation(),
5386 SourceLocation(), DIE.get(), SourceLocation());
5387 return Info.addFieldInitializer(Init);
5388 }
5389
5390 // Don't initialize incomplete or zero-length arrays.
5391 if (isIncompleteOrZeroLengthArrayType(Context&: SemaRef.Context, T: Field->getType()))
5392 return false;
5393
5394 // Don't try to build an implicit initializer if there were semantic
5395 // errors in any of the initializers (and therefore we might be
5396 // missing some that the user actually wrote).
5397 if (Info.AnyErrorsInInits)
5398 return false;
5399
5400 CXXCtorInitializer *Init = nullptr;
5401 if (BuildImplicitMemberInitializer(SemaRef&: Info.S, Constructor: Info.Ctor, ImplicitInitKind: Info.IIK, Field,
5402 Indirect, CXXMemberInit&: Init))
5403 return true;
5404
5405 if (!Init)
5406 return false;
5407
5408 return Info.addFieldInitializer(Init);
5409}
5410
5411bool
5412Sema::SetDelegatingInitializer(CXXConstructorDecl *Constructor,
5413 CXXCtorInitializer *Initializer) {
5414 assert(Initializer->isDelegatingInitializer());
5415 Constructor->setNumCtorInitializers(1);
5416 CXXCtorInitializer **initializer =
5417 new (Context) CXXCtorInitializer*[1];
5418 memcpy(dest: initializer, src: &Initializer, n: sizeof (CXXCtorInitializer*));
5419 Constructor->setCtorInitializers(initializer);
5420
5421 if (CXXDestructorDecl *Dtor = LookupDestructor(Class: Constructor->getParent())) {
5422 MarkFunctionReferenced(Loc: Initializer->getSourceLocation(), Func: Dtor);
5423 DiagnoseUseOfDecl(D: Dtor, Locs: Initializer->getSourceLocation());
5424 }
5425
5426 DelegatingCtorDecls.push_back(LocalValue: Constructor);
5427
5428 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
5429
5430 return false;
5431}
5432
5433static CXXDestructorDecl *LookupDestructorIfRelevant(Sema &S,
5434 CXXRecordDecl *Class) {
5435 if (Class->isInvalidDecl())
5436 return nullptr;
5437 if (Class->hasIrrelevantDestructor())
5438 return nullptr;
5439
5440 // Dtor might still be missing, e.g because it's invalid.
5441 return S.LookupDestructor(Class);
5442}
5443
5444static void MarkFieldDestructorReferenced(Sema &S, SourceLocation Location,
5445 FieldDecl *Field) {
5446 if (Field->isInvalidDecl())
5447 return;
5448
5449 // Don't destroy incomplete or zero-length arrays.
5450 if (isIncompleteOrZeroLengthArrayType(Context&: S.Context, T: Field->getType()))
5451 return;
5452
5453 QualType FieldType = S.Context.getBaseElementType(QT: Field->getType());
5454
5455 auto *FieldClassDecl = FieldType->getAsCXXRecordDecl();
5456 if (!FieldClassDecl)
5457 return;
5458
5459 // The destructor for an implicit anonymous union member is never invoked.
5460 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion())
5461 return;
5462
5463 auto *Dtor = LookupDestructorIfRelevant(S, Class: FieldClassDecl);
5464 if (!Dtor)
5465 return;
5466
5467 S.CheckDestructorAccess(Loc: Field->getLocation(), Dtor,
5468 PDiag: S.PDiag(DiagID: diag::err_access_dtor_field)
5469 << Field->getDeclName() << FieldType);
5470
5471 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5472 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5473}
5474
5475static void MarkBaseDestructorsReferenced(Sema &S, SourceLocation Location,
5476 CXXRecordDecl *ClassDecl) {
5477 if (ClassDecl->isDependentContext())
5478 return;
5479
5480 // We only potentially invoke the destructors of potentially constructed
5481 // subobjects.
5482 bool VisitVirtualBases = !ClassDecl->isAbstract();
5483
5484 // If the destructor exists and has already been marked used in the MS ABI,
5485 // then virtual base destructors have already been checked and marked used.
5486 // Skip checking them again to avoid duplicate diagnostics.
5487 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
5488 CXXDestructorDecl *Dtor = ClassDecl->getDestructor();
5489 if (Dtor && Dtor->isUsed())
5490 VisitVirtualBases = false;
5491 }
5492
5493 llvm::SmallPtrSet<const CXXRecordDecl *, 8> DirectVirtualBases;
5494
5495 // Bases.
5496 for (const auto &Base : ClassDecl->bases()) {
5497 auto *BaseClassDecl = Base.getType()->getAsCXXRecordDecl();
5498 if (!BaseClassDecl)
5499 continue;
5500
5501 // Remember direct virtual bases.
5502 if (Base.isVirtual()) {
5503 if (!VisitVirtualBases)
5504 continue;
5505 DirectVirtualBases.insert(Ptr: BaseClassDecl);
5506 }
5507
5508 auto *Dtor = LookupDestructorIfRelevant(S, Class: BaseClassDecl);
5509 if (!Dtor)
5510 continue;
5511
5512 // FIXME: caret should be on the start of the class name
5513 S.CheckDestructorAccess(Loc: Base.getBeginLoc(), Dtor,
5514 PDiag: S.PDiag(DiagID: diag::err_access_dtor_base)
5515 << Base.getType() << Base.getSourceRange(),
5516 objectType: S.Context.getCanonicalTagType(TD: ClassDecl));
5517
5518 S.MarkFunctionReferenced(Loc: Location, Func: Dtor);
5519 S.DiagnoseUseOfDecl(D: Dtor, Locs: Location);
5520 }
5521
5522 if (VisitVirtualBases)
5523 S.MarkVirtualBaseDestructorsReferenced(Location, ClassDecl,
5524 DirectVirtualBases: &DirectVirtualBases);
5525}
5526
5527bool Sema::SetCtorInitializers(CXXConstructorDecl *Constructor, bool AnyErrors,
5528 ArrayRef<CXXCtorInitializer *> Initializers) {
5529 if (Constructor->isDependentContext()) {
5530 // Just store the initializers as written, they will be checked during
5531 // instantiation.
5532 if (!Initializers.empty()) {
5533 Constructor->setNumCtorInitializers(Initializers.size());
5534 CXXCtorInitializer **baseOrMemberInitializers =
5535 new (Context) CXXCtorInitializer*[Initializers.size()];
5536 memcpy(dest: baseOrMemberInitializers, src: Initializers.data(),
5537 n: Initializers.size() * sizeof(CXXCtorInitializer*));
5538 Constructor->setCtorInitializers(baseOrMemberInitializers);
5539 }
5540
5541 // Let template instantiation know whether we had errors.
5542 if (AnyErrors)
5543 Constructor->setInvalidDecl();
5544
5545 return false;
5546 }
5547
5548 BaseAndFieldInfo Info(*this, Constructor, AnyErrors);
5549
5550 // We need to build the initializer AST according to order of construction
5551 // and not what user specified in the Initializers list.
5552 CXXRecordDecl *ClassDecl = Constructor->getParent()->getDefinition();
5553 if (!ClassDecl)
5554 return true;
5555
5556 bool HadError = false;
5557
5558 for (CXXCtorInitializer *Member : Initializers) {
5559 if (Member->isBaseInitializer())
5560 Info.AllBaseFields[Member->getBaseClass()->getAsCanonical<RecordType>()] =
5561 Member;
5562 else {
5563 Info.AllBaseFields[Member->getAnyMember()->getCanonicalDecl()] = Member;
5564
5565 if (IndirectFieldDecl *F = Member->getIndirectMember()) {
5566 for (auto *C : F->chain()) {
5567 FieldDecl *FD = dyn_cast<FieldDecl>(Val: C);
5568 if (FD && FD->getParent()->isUnion())
5569 Info.ActiveUnionMember.insert(KV: std::make_pair(
5570 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5571 }
5572 } else if (FieldDecl *FD = Member->getMember()) {
5573 if (FD->getParent()->isUnion())
5574 Info.ActiveUnionMember.insert(KV: std::make_pair(
5575 x: FD->getParent()->getCanonicalDecl(), y: FD->getCanonicalDecl()));
5576 }
5577 }
5578 }
5579
5580 // Keep track of the direct virtual bases.
5581 llvm::SmallPtrSet<CXXBaseSpecifier *, 16> DirectVBases;
5582 for (auto &I : ClassDecl->bases()) {
5583 if (I.isVirtual())
5584 DirectVBases.insert(Ptr: &I);
5585 }
5586
5587 // Push virtual bases before others.
5588 for (auto &VBase : ClassDecl->vbases()) {
5589 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5590 Val: VBase.getType()->getAsCanonical<RecordType>())) {
5591 // [class.base.init]p7, per DR257:
5592 // A mem-initializer where the mem-initializer-id names a virtual base
5593 // class is ignored during execution of a constructor of any class that
5594 // is not the most derived class.
5595 if (ClassDecl->isAbstract()) {
5596 // FIXME: Provide a fixit to remove the base specifier. This requires
5597 // tracking the location of the associated comma for a base specifier.
5598 Diag(Loc: Value->getSourceLocation(), DiagID: diag::warn_abstract_vbase_init_ignored)
5599 << VBase.getType() << ClassDecl;
5600 DiagnoseAbstractType(RD: ClassDecl);
5601 }
5602
5603 Info.AllToInit.push_back(Elt: Value);
5604 } else if (!AnyErrors && !ClassDecl->isAbstract()) {
5605 // [class.base.init]p8, per DR257:
5606 // If a given [...] base class is not named by a mem-initializer-id
5607 // [...] and the entity is not a virtual base class of an abstract
5608 // class, then [...] the entity is default-initialized.
5609 bool IsInheritedVirtualBase = !DirectVBases.count(Ptr: &VBase);
5610 CXXCtorInitializer *CXXBaseInit;
5611 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5612 BaseSpec: &VBase, IsInheritedVirtualBase,
5613 CXXBaseInit)) {
5614 HadError = true;
5615 continue;
5616 }
5617
5618 Info.AllToInit.push_back(Elt: CXXBaseInit);
5619 }
5620 }
5621
5622 // Non-virtual bases.
5623 for (auto &Base : ClassDecl->bases()) {
5624 // Virtuals are in the virtual base list and already constructed.
5625 if (Base.isVirtual())
5626 continue;
5627
5628 if (CXXCtorInitializer *Value = Info.AllBaseFields.lookup(
5629 Val: Base.getType()->getAsCanonical<RecordType>())) {
5630 Info.AllToInit.push_back(Elt: Value);
5631 } else if (!AnyErrors) {
5632 CXXCtorInitializer *CXXBaseInit;
5633 if (BuildImplicitBaseInitializer(SemaRef&: *this, Constructor, ImplicitInitKind: Info.IIK,
5634 BaseSpec: &Base, /*IsInheritedVirtualBase=*/false,
5635 CXXBaseInit)) {
5636 HadError = true;
5637 continue;
5638 }
5639
5640 Info.AllToInit.push_back(Elt: CXXBaseInit);
5641 }
5642 }
5643
5644 // Fields.
5645 for (auto *Mem : ClassDecl->decls()) {
5646 if (auto *F = dyn_cast<FieldDecl>(Val: Mem)) {
5647 // C++ [class.bit]p2:
5648 // A declaration for a bit-field that omits the identifier declares an
5649 // unnamed bit-field. Unnamed bit-fields are not members and cannot be
5650 // initialized.
5651 if (F->isUnnamedBitField())
5652 continue;
5653
5654 // If we're not generating the implicit copy/move constructor, then we'll
5655 // handle anonymous struct/union fields based on their individual
5656 // indirect fields.
5657 if (F->isAnonymousStructOrUnion() && !Info.isImplicitCopyOrMove())
5658 continue;
5659
5660 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F))
5661 HadError = true;
5662 continue;
5663 }
5664
5665 // Beyond this point, we only consider default initialization.
5666 if (Info.isImplicitCopyOrMove())
5667 continue;
5668
5669 if (auto *F = dyn_cast<IndirectFieldDecl>(Val: Mem)) {
5670 if (F->getType()->isIncompleteArrayType()) {
5671 assert(ClassDecl->hasFlexibleArrayMember() &&
5672 "Incomplete array type is not valid");
5673 continue;
5674 }
5675
5676 // Initialize each field of an anonymous struct individually.
5677 if (CollectFieldInitializer(SemaRef&: *this, Info, Field: F->getAnonField(), Indirect: F))
5678 HadError = true;
5679
5680 continue;
5681 }
5682 }
5683
5684 unsigned NumInitializers = Info.AllToInit.size();
5685 if (NumInitializers > 0) {
5686 Constructor->setNumCtorInitializers(NumInitializers);
5687 CXXCtorInitializer **baseOrMemberInitializers =
5688 new (Context) CXXCtorInitializer*[NumInitializers];
5689 memcpy(dest: baseOrMemberInitializers, src: Info.AllToInit.data(),
5690 n: NumInitializers * sizeof(CXXCtorInitializer*));
5691 Constructor->setCtorInitializers(baseOrMemberInitializers);
5692
5693 SourceLocation Location = Constructor->getLocation();
5694
5695 // Constructors implicitly reference the base and member
5696 // destructors.
5697
5698 for (CXXCtorInitializer *Initializer : Info.AllToInit) {
5699 FieldDecl *Field = Initializer->getAnyMember();
5700 if (!Field)
5701 continue;
5702
5703 // C++ [class.base.init]p12:
5704 // In a non-delegating constructor, the destructor for each
5705 // potentially constructed subobject of class type is potentially
5706 // invoked.
5707 MarkFieldDestructorReferenced(S&: *this, Location, Field);
5708 }
5709
5710 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl: Constructor->getParent());
5711 }
5712
5713 return HadError;
5714}
5715
5716static void PopulateKeysForFields(FieldDecl *Field, SmallVectorImpl<const void*> &IdealInits) {
5717 if (const RecordType *RT = Field->getType()->getAsCanonical<RecordType>()) {
5718 const RecordDecl *RD = RT->getDecl();
5719 if (RD->isAnonymousStructOrUnion()) {
5720 for (auto *Field : RD->getDefinitionOrSelf()->fields())
5721 PopulateKeysForFields(Field, IdealInits);
5722 return;
5723 }
5724 }
5725 IdealInits.push_back(Elt: Field->getCanonicalDecl());
5726}
5727
5728static const void *GetKeyForBase(ASTContext &Context, QualType BaseType) {
5729 return Context.getCanonicalType(T: BaseType).getTypePtr();
5730}
5731
5732static const void *GetKeyForMember(ASTContext &Context,
5733 CXXCtorInitializer *Member) {
5734 if (!Member->isAnyMemberInitializer())
5735 return GetKeyForBase(Context, BaseType: QualType(Member->getBaseClass(), 0));
5736
5737 return Member->getAnyMember()->getCanonicalDecl();
5738}
5739
5740static void AddInitializerToDiag(const Sema::SemaDiagnosticBuilder &Diag,
5741 const CXXCtorInitializer *Previous,
5742 const CXXCtorInitializer *Current) {
5743 if (Previous->isAnyMemberInitializer())
5744 Diag << 0 << Previous->getAnyMember();
5745 else
5746 Diag << 1 << Previous->getTypeSourceInfo()->getType();
5747
5748 if (Current->isAnyMemberInitializer())
5749 Diag << 0 << Current->getAnyMember();
5750 else
5751 Diag << 1 << Current->getTypeSourceInfo()->getType();
5752}
5753
5754static void DiagnoseBaseOrMemInitializerOrder(
5755 Sema &SemaRef, const CXXConstructorDecl *Constructor,
5756 ArrayRef<CXXCtorInitializer *> Inits) {
5757 if (Constructor->getDeclContext()->isDependentContext())
5758 return;
5759
5760 // Don't check initializers order unless the warning is enabled at the
5761 // location of at least one initializer.
5762 bool ShouldCheckOrder = false;
5763 for (const CXXCtorInitializer *Init : Inits) {
5764 if (!SemaRef.Diags.isIgnored(DiagID: diag::warn_initializer_out_of_order,
5765 Loc: Init->getSourceLocation())) {
5766 ShouldCheckOrder = true;
5767 break;
5768 }
5769 }
5770 if (!ShouldCheckOrder)
5771 return;
5772
5773 // Build the list of bases and members in the order that they'll
5774 // actually be initialized. The explicit initializers should be in
5775 // this same order but may be missing things.
5776 SmallVector<const void*, 32> IdealInitKeys;
5777
5778 const CXXRecordDecl *ClassDecl = Constructor->getParent();
5779
5780 // 1. Virtual bases.
5781 for (const auto &VBase : ClassDecl->vbases())
5782 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: VBase.getType()));
5783
5784 // 2. Non-virtual bases.
5785 for (const auto &Base : ClassDecl->bases()) {
5786 if (Base.isVirtual())
5787 continue;
5788 IdealInitKeys.push_back(Elt: GetKeyForBase(Context&: SemaRef.Context, BaseType: Base.getType()));
5789 }
5790
5791 // 3. Direct fields.
5792 for (auto *Field : ClassDecl->fields()) {
5793 if (Field->isUnnamedBitField())
5794 continue;
5795
5796 PopulateKeysForFields(Field, IdealInits&: IdealInitKeys);
5797 }
5798
5799 unsigned NumIdealInits = IdealInitKeys.size();
5800 unsigned IdealIndex = 0;
5801
5802 // Track initializers that are in an incorrect order for either a warning or
5803 // note if multiple ones occur.
5804 SmallVector<unsigned> WarnIndexes;
5805 // Correlates the index of an initializer in the init-list to the index of
5806 // the field/base in the class.
5807 SmallVector<std::pair<unsigned, unsigned>, 32> CorrelatedInitOrder;
5808
5809 for (unsigned InitIndex = 0; InitIndex != Inits.size(); ++InitIndex) {
5810 const void *InitKey = GetKeyForMember(Context&: SemaRef.Context, Member: Inits[InitIndex]);
5811
5812 // Scan forward to try to find this initializer in the idealized
5813 // initializers list.
5814 for (; IdealIndex != NumIdealInits; ++IdealIndex)
5815 if (InitKey == IdealInitKeys[IdealIndex])
5816 break;
5817
5818 // If we didn't find this initializer, it must be because we
5819 // scanned past it on a previous iteration. That can only
5820 // happen if we're out of order; emit a warning.
5821 if (IdealIndex == NumIdealInits && InitIndex) {
5822 WarnIndexes.push_back(Elt: InitIndex);
5823
5824 // Move back to the initializer's location in the ideal list.
5825 for (IdealIndex = 0; IdealIndex != NumIdealInits; ++IdealIndex)
5826 if (InitKey == IdealInitKeys[IdealIndex])
5827 break;
5828
5829 assert(IdealIndex < NumIdealInits &&
5830 "initializer not found in initializer list");
5831 }
5832 CorrelatedInitOrder.emplace_back(Args&: IdealIndex, Args&: InitIndex);
5833 }
5834
5835 if (WarnIndexes.empty())
5836 return;
5837
5838 // Sort based on the ideal order, first in the pair.
5839 llvm::sort(C&: CorrelatedInitOrder, Comp: llvm::less_first());
5840
5841 // Introduce a new scope as SemaDiagnosticBuilder needs to be destroyed to
5842 // emit the diagnostic before we can try adding notes.
5843 {
5844 Sema::SemaDiagnosticBuilder D = SemaRef.Diag(
5845 Loc: Inits[WarnIndexes.front() - 1]->getSourceLocation(),
5846 DiagID: WarnIndexes.size() == 1 ? diag::warn_initializer_out_of_order
5847 : diag::warn_some_initializers_out_of_order);
5848
5849 for (unsigned I = 0; I < CorrelatedInitOrder.size(); ++I) {
5850 if (CorrelatedInitOrder[I].second == I)
5851 continue;
5852 // Ideally we would be using InsertFromRange here, but clang doesn't
5853 // appear to handle InsertFromRange correctly when the source range is
5854 // modified by another fix-it.
5855 D << FixItHint::CreateReplacement(
5856 RemoveRange: Inits[I]->getSourceRange(),
5857 Code: Lexer::getSourceText(
5858 Range: CharSourceRange::getTokenRange(
5859 R: Inits[CorrelatedInitOrder[I].second]->getSourceRange()),
5860 SM: SemaRef.getSourceManager(), LangOpts: SemaRef.getLangOpts()));
5861 }
5862
5863 // If there is only 1 item out of order, the warning expects the name and
5864 // type of each being added to it.
5865 if (WarnIndexes.size() == 1) {
5866 AddInitializerToDiag(Diag: D, Previous: Inits[WarnIndexes.front() - 1],
5867 Current: Inits[WarnIndexes.front()]);
5868 return;
5869 }
5870 }
5871 // More than 1 item to warn, create notes letting the user know which ones
5872 // are bad.
5873 for (unsigned WarnIndex : WarnIndexes) {
5874 const clang::CXXCtorInitializer *PrevInit = Inits[WarnIndex - 1];
5875 auto D = SemaRef.Diag(Loc: PrevInit->getSourceLocation(),
5876 DiagID: diag::note_initializer_out_of_order);
5877 AddInitializerToDiag(Diag: D, Previous: PrevInit, Current: Inits[WarnIndex]);
5878 D << PrevInit->getSourceRange();
5879 }
5880}
5881
5882namespace {
5883bool CheckRedundantInit(Sema &S,
5884 CXXCtorInitializer *Init,
5885 CXXCtorInitializer *&PrevInit) {
5886 if (!PrevInit) {
5887 PrevInit = Init;
5888 return false;
5889 }
5890
5891 if (FieldDecl *Field = Init->getAnyMember())
5892 S.Diag(Loc: Init->getSourceLocation(),
5893 DiagID: diag::err_multiple_mem_initialization)
5894 << Field->getDeclName()
5895 << Init->getSourceRange();
5896 else {
5897 const Type *BaseClass = Init->getBaseClass();
5898 assert(BaseClass && "neither field nor base");
5899 S.Diag(Loc: Init->getSourceLocation(),
5900 DiagID: diag::err_multiple_base_initialization)
5901 << QualType(BaseClass, 0)
5902 << Init->getSourceRange();
5903 }
5904 S.Diag(Loc: PrevInit->getSourceLocation(), DiagID: diag::note_previous_initializer)
5905 << 0 << PrevInit->getSourceRange();
5906
5907 return true;
5908}
5909
5910typedef std::pair<NamedDecl *, CXXCtorInitializer *> UnionEntry;
5911typedef llvm::DenseMap<RecordDecl*, UnionEntry> RedundantUnionMap;
5912
5913bool CheckRedundantUnionInit(Sema &S,
5914 CXXCtorInitializer *Init,
5915 RedundantUnionMap &Unions) {
5916 FieldDecl *Field = Init->getAnyMember();
5917 RecordDecl *Parent = Field->getParent();
5918 NamedDecl *Child = Field;
5919
5920 while (Parent->isAnonymousStructOrUnion() || Parent->isUnion()) {
5921 if (Parent->isUnion()) {
5922 UnionEntry &En = Unions[Parent];
5923 if (En.first && En.first != Child) {
5924 S.Diag(Loc: Init->getSourceLocation(),
5925 DiagID: diag::err_multiple_mem_union_initialization)
5926 << Field->getDeclName()
5927 << Init->getSourceRange();
5928 S.Diag(Loc: En.second->getSourceLocation(), DiagID: diag::note_previous_initializer)
5929 << 0 << En.second->getSourceRange();
5930 return true;
5931 }
5932 if (!En.first) {
5933 En.first = Child;
5934 En.second = Init;
5935 }
5936 if (!Parent->isAnonymousStructOrUnion())
5937 return false;
5938 }
5939
5940 Child = Parent;
5941 Parent = cast<RecordDecl>(Val: Parent->getDeclContext());
5942 }
5943
5944 return false;
5945}
5946} // namespace
5947
5948void Sema::ActOnMemInitializers(Decl *ConstructorDecl,
5949 SourceLocation ColonLoc,
5950 ArrayRef<CXXCtorInitializer*> MemInits,
5951 bool AnyErrors) {
5952 if (!ConstructorDecl)
5953 return;
5954
5955 AdjustDeclIfTemplate(Decl&: ConstructorDecl);
5956
5957 CXXConstructorDecl *Constructor
5958 = dyn_cast<CXXConstructorDecl>(Val: ConstructorDecl);
5959
5960 if (!Constructor) {
5961 Diag(Loc: ColonLoc, DiagID: diag::err_only_constructors_take_base_inits);
5962 return;
5963 }
5964
5965 // Mapping for the duplicate initializers check.
5966 // For member initializers, this is keyed with a FieldDecl*.
5967 // For base initializers, this is keyed with a Type*.
5968 llvm::DenseMap<const void *, CXXCtorInitializer *> Members;
5969
5970 // Mapping for the inconsistent anonymous-union initializers check.
5971 RedundantUnionMap MemberUnions;
5972
5973 bool HadError = false;
5974 for (unsigned i = 0; i < MemInits.size(); i++) {
5975 CXXCtorInitializer *Init = MemInits[i];
5976
5977 // Set the source order index.
5978 Init->setSourceOrder(i);
5979
5980 if (Init->isAnyMemberInitializer()) {
5981 const void *Key = GetKeyForMember(Context, Member: Init);
5982 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]) ||
5983 CheckRedundantUnionInit(S&: *this, Init, Unions&: MemberUnions))
5984 HadError = true;
5985 } else if (Init->isBaseInitializer()) {
5986 const void *Key = GetKeyForMember(Context, Member: Init);
5987 if (CheckRedundantInit(S&: *this, Init, PrevInit&: Members[Key]))
5988 HadError = true;
5989 } else {
5990 assert(Init->isDelegatingInitializer());
5991 // This must be the only initializer
5992 if (MemInits.size() != 1) {
5993 Diag(Loc: Init->getSourceLocation(),
5994 DiagID: diag::err_delegating_initializer_alone)
5995 << Init->getSourceRange() << MemInits[i ? 0 : 1]->getSourceRange();
5996 // We will treat this as being the only initializer.
5997 }
5998 SetDelegatingInitializer(Constructor, Initializer: MemInits[i]);
5999 // Return immediately as the initializer is set.
6000 return;
6001 }
6002 }
6003
6004 if (HadError)
6005 return;
6006
6007 DiagnoseBaseOrMemInitializerOrder(SemaRef&: *this, Constructor, Inits: MemInits);
6008
6009 SetCtorInitializers(Constructor, AnyErrors, Initializers: MemInits);
6010
6011 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6012}
6013
6014void Sema::MarkBaseAndMemberDestructorsReferenced(SourceLocation Location,
6015 CXXRecordDecl *ClassDecl) {
6016 // Ignore dependent contexts. Also ignore unions, since their members never
6017 // have destructors implicitly called.
6018 if (ClassDecl->isDependentContext() || ClassDecl->isUnion())
6019 return;
6020
6021 // FIXME: all the access-control diagnostics are positioned on the
6022 // field/base declaration. That's probably good; that said, the
6023 // user might reasonably want to know why the destructor is being
6024 // emitted, and we currently don't say.
6025
6026 // Non-static data members.
6027 for (auto *Field : ClassDecl->fields()) {
6028 MarkFieldDestructorReferenced(S&: *this, Location, Field);
6029 }
6030
6031 MarkBaseDestructorsReferenced(S&: *this, Location, ClassDecl);
6032}
6033
6034void Sema::MarkVirtualBaseDestructorsReferenced(
6035 SourceLocation Location, CXXRecordDecl *ClassDecl,
6036 llvm::SmallPtrSetImpl<const CXXRecordDecl *> *DirectVirtualBases) {
6037 // Virtual bases.
6038 for (const auto &VBase : ClassDecl->vbases()) {
6039 auto *BaseClassDecl = VBase.getType()->getAsCXXRecordDecl();
6040 if (!BaseClassDecl)
6041 continue;
6042
6043 // Ignore already visited direct virtual bases.
6044 if (DirectVirtualBases && DirectVirtualBases->count(Ptr: BaseClassDecl))
6045 continue;
6046
6047 auto *Dtor = LookupDestructorIfRelevant(S&: *this, Class: BaseClassDecl);
6048 if (!Dtor)
6049 continue;
6050
6051 CanQualType CT = Context.getCanonicalTagType(TD: ClassDecl);
6052 if (CheckDestructorAccess(Loc: ClassDecl->getLocation(), Dtor,
6053 PDiag: PDiag(DiagID: diag::err_access_dtor_vbase)
6054 << CT << VBase.getType(),
6055 objectType: CT) == AR_accessible) {
6056 CheckDerivedToBaseConversion(
6057 Derived: CT, Base: VBase.getType(), InaccessibleBaseID: diag::err_access_dtor_vbase, AmbiguousBaseConvID: 0,
6058 Loc: ClassDecl->getLocation(), Range: SourceRange(), Name: DeclarationName(), BasePath: nullptr);
6059 }
6060
6061 MarkFunctionReferenced(Loc: Location, Func: Dtor);
6062 DiagnoseUseOfDecl(D: Dtor, Locs: Location);
6063 }
6064}
6065
6066void Sema::ActOnDefaultCtorInitializers(Decl *CDtorDecl) {
6067 if (!CDtorDecl)
6068 return;
6069
6070 if (CXXConstructorDecl *Constructor
6071 = dyn_cast<CXXConstructorDecl>(Val: CDtorDecl)) {
6072 if (CXXRecordDecl *ClassDecl = Constructor->getParent();
6073 !ClassDecl || ClassDecl->isInvalidDecl()) {
6074 return;
6075 }
6076 SetCtorInitializers(Constructor, /*AnyErrors=*/false);
6077 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
6078 }
6079}
6080
6081bool Sema::isAbstractType(SourceLocation Loc, QualType T) {
6082 if (!getLangOpts().CPlusPlus)
6083 return false;
6084
6085 const auto *RD = Context.getBaseElementType(QT: T)->getAsCXXRecordDecl();
6086 if (!RD)
6087 return false;
6088
6089 // FIXME: Per [temp.inst]p1, we are supposed to trigger instantiation of a
6090 // class template specialization here, but doing so breaks a lot of code.
6091
6092 // We can't answer whether something is abstract until it has a
6093 // definition. If it's currently being defined, we'll walk back
6094 // over all the declarations when we have a full definition.
6095 const CXXRecordDecl *Def = RD->getDefinition();
6096 if (!Def || Def->isBeingDefined())
6097 return false;
6098
6099 return RD->isAbstract();
6100}
6101
6102bool Sema::RequireNonAbstractType(SourceLocation Loc, QualType T,
6103 TypeDiagnoser &Diagnoser) {
6104 if (!isAbstractType(Loc, T))
6105 return false;
6106
6107 T = Context.getBaseElementType(QT: T);
6108 Diagnoser.diagnose(S&: *this, Loc, T);
6109 DiagnoseAbstractType(RD: T->getAsCXXRecordDecl());
6110 return true;
6111}
6112
6113void Sema::DiagnoseAbstractType(const CXXRecordDecl *RD) {
6114 // Check if we've already emitted the list of pure virtual functions
6115 // for this class.
6116 if (PureVirtualClassDiagSet && PureVirtualClassDiagSet->count(Ptr: RD))
6117 return;
6118
6119 // If the diagnostic is suppressed, don't emit the notes. We're only
6120 // going to emit them once, so try to attach them to a diagnostic we're
6121 // actually going to show.
6122 if (Diags.isLastDiagnosticIgnored())
6123 return;
6124
6125 CXXFinalOverriderMap FinalOverriders;
6126 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
6127
6128 // Keep a set of seen pure methods so we won't diagnose the same method
6129 // more than once.
6130 llvm::SmallPtrSet<const CXXMethodDecl *, 8> SeenPureMethods;
6131
6132 for (const auto &M : FinalOverriders) {
6133 for (const auto &SO : M.second) {
6134 // C++ [class.abstract]p4:
6135 // A class is abstract if it contains or inherits at least one
6136 // pure virtual function for which the final overrider is pure
6137 // virtual.
6138
6139 if (SO.second.size() != 1)
6140 continue;
6141 const CXXMethodDecl *Method = SO.second.front().Method;
6142
6143 if (!Method->isPureVirtual())
6144 continue;
6145
6146 if (!SeenPureMethods.insert(Ptr: Method).second)
6147 continue;
6148
6149 Diag(Loc: Method->getLocation(), DiagID: diag::note_pure_virtual_function)
6150 << Method->getDeclName() << RD->getDeclName();
6151 }
6152 }
6153
6154 if (!PureVirtualClassDiagSet)
6155 PureVirtualClassDiagSet.reset(p: new RecordDeclSetTy);
6156 PureVirtualClassDiagSet->insert(Ptr: RD);
6157}
6158
6159namespace {
6160struct AbstractUsageInfo {
6161 Sema &S;
6162 CXXRecordDecl *Record;
6163 CanQualType AbstractType;
6164 bool Invalid;
6165
6166 AbstractUsageInfo(Sema &S, CXXRecordDecl *Record)
6167 : S(S), Record(Record),
6168 AbstractType(S.Context.getCanonicalTagType(TD: Record)), Invalid(false) {}
6169
6170 void DiagnoseAbstractType() {
6171 if (Invalid) return;
6172 S.DiagnoseAbstractType(RD: Record);
6173 Invalid = true;
6174 }
6175
6176 void CheckType(const NamedDecl *D, TypeLoc TL, Sema::AbstractDiagSelID Sel);
6177};
6178
6179struct CheckAbstractUsage {
6180 AbstractUsageInfo &Info;
6181 const NamedDecl *Ctx;
6182
6183 CheckAbstractUsage(AbstractUsageInfo &Info, const NamedDecl *Ctx)
6184 : Info(Info), Ctx(Ctx) {}
6185
6186 void Visit(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6187 switch (TL.getTypeLocClass()) {
6188#define ABSTRACT_TYPELOC(CLASS, PARENT)
6189#define TYPELOC(CLASS, PARENT) \
6190 case TypeLoc::CLASS: Check(TL.castAs<CLASS##TypeLoc>(), Sel); break;
6191#include "clang/AST/TypeLocNodes.def"
6192 }
6193 }
6194
6195 void Check(FunctionProtoTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6196 Visit(TL: TL.getReturnLoc(), Sel: Sema::AbstractReturnType);
6197 for (unsigned I = 0, E = TL.getNumParams(); I != E; ++I) {
6198 if (!TL.getParam(i: I))
6199 continue;
6200
6201 TypeSourceInfo *TSI = TL.getParam(i: I)->getTypeSourceInfo();
6202 if (TSI) Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractParamType);
6203 }
6204 }
6205
6206 void Check(ArrayTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6207 Visit(TL: TL.getElementLoc(), Sel: Sema::AbstractArrayType);
6208 }
6209
6210 void Check(TemplateSpecializationTypeLoc TL, Sema::AbstractDiagSelID Sel) {
6211 // Visit the type parameters from a permissive context.
6212 for (unsigned I = 0, E = TL.getNumArgs(); I != E; ++I) {
6213 TemplateArgumentLoc TAL = TL.getArgLoc(i: I);
6214 if (TAL.getArgument().getKind() == TemplateArgument::Type)
6215 if (TypeSourceInfo *TSI = TAL.getTypeSourceInfo())
6216 Visit(TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6217 // TODO: other template argument types?
6218 }
6219 }
6220
6221 // Visit pointee types from a permissive context.
6222#define CheckPolymorphic(Type) \
6223 void Check(Type TL, Sema::AbstractDiagSelID Sel) { \
6224 Visit(TL.getNextTypeLoc(), Sema::AbstractNone); \
6225 }
6226 CheckPolymorphic(PointerTypeLoc)
6227 CheckPolymorphic(ReferenceTypeLoc)
6228 CheckPolymorphic(MemberPointerTypeLoc)
6229 CheckPolymorphic(BlockPointerTypeLoc)
6230 CheckPolymorphic(AtomicTypeLoc)
6231
6232 /// Handle all the types we haven't given a more specific
6233 /// implementation for above.
6234 void Check(TypeLoc TL, Sema::AbstractDiagSelID Sel) {
6235 // Every other kind of type that we haven't called out already
6236 // that has an inner type is either (1) sugar or (2) contains that
6237 // inner type in some way as a subobject.
6238 if (TypeLoc Next = TL.getNextTypeLoc())
6239 return Visit(TL: Next, Sel);
6240
6241 // If there's no inner type and we're in a permissive context,
6242 // don't diagnose.
6243 if (Sel == Sema::AbstractNone) return;
6244
6245 // Check whether the type matches the abstract type.
6246 QualType T = TL.getType();
6247 if (T->isArrayType()) {
6248 Sel = Sema::AbstractArrayType;
6249 T = Info.S.Context.getBaseElementType(QT: T);
6250 }
6251 CanQualType CT = T->getCanonicalTypeUnqualified();
6252 if (CT != Info.AbstractType) return;
6253
6254 // It matched; do some magic.
6255 // FIXME: These should be at most warnings. See P0929R2, CWG1640, CWG1646.
6256 if (Sel == Sema::AbstractArrayType) {
6257 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_array_of_abstract_type)
6258 << T << TL.getSourceRange();
6259 } else {
6260 Info.S.Diag(Loc: Ctx->getLocation(), DiagID: diag::err_abstract_type_in_decl)
6261 << Sel << T << TL.getSourceRange();
6262 }
6263 Info.DiagnoseAbstractType();
6264 }
6265};
6266
6267void AbstractUsageInfo::CheckType(const NamedDecl *D, TypeLoc TL,
6268 Sema::AbstractDiagSelID Sel) {
6269 CheckAbstractUsage(*this, D).Visit(TL, Sel);
6270}
6271
6272}
6273
6274/// Check for invalid uses of an abstract type in a function declaration.
6275static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6276 FunctionDecl *FD) {
6277 // Only definitions are required to refer to complete and
6278 // non-abstract types.
6279 if (!FD->doesThisDeclarationHaveABody())
6280 return;
6281
6282 // For safety's sake, just ignore it if we don't have type source
6283 // information. This should never happen for non-implicit methods,
6284 // but...
6285 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6286 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractNone);
6287}
6288
6289/// Check for invalid uses of an abstract type in a variable0 declaration.
6290static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6291 VarDecl *VD) {
6292 // No need to do the check on definitions, which require that
6293 // the type is complete.
6294 if (VD->isThisDeclarationADefinition())
6295 return;
6296
6297 Info.CheckType(D: VD, TL: VD->getTypeSourceInfo()->getTypeLoc(),
6298 Sel: Sema::AbstractVariableType);
6299}
6300
6301/// Check for invalid uses of an abstract type within a class definition.
6302static void CheckAbstractClassUsage(AbstractUsageInfo &Info,
6303 CXXRecordDecl *RD) {
6304 for (auto *D : RD->decls()) {
6305 if (D->isImplicit()) continue;
6306
6307 // Step through friends to the befriended declaration.
6308 if (auto *FD = dyn_cast<FriendDecl>(Val: D)) {
6309 D = FD->getFriendDecl();
6310 if (!D) continue;
6311 }
6312
6313 // Functions and function templates.
6314 if (auto *FD = dyn_cast<FunctionDecl>(Val: D)) {
6315 CheckAbstractClassUsage(Info, FD);
6316 } else if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: D)) {
6317 CheckAbstractClassUsage(Info, FD: FTD->getTemplatedDecl());
6318
6319 // Fields and static variables.
6320 } else if (auto *FD = dyn_cast<FieldDecl>(Val: D)) {
6321 if (TypeSourceInfo *TSI = FD->getTypeSourceInfo())
6322 Info.CheckType(D: FD, TL: TSI->getTypeLoc(), Sel: Sema::AbstractFieldType);
6323 } else if (auto *VD = dyn_cast<VarDecl>(Val: D)) {
6324 CheckAbstractClassUsage(Info, VD);
6325 } else if (auto *VTD = dyn_cast<VarTemplateDecl>(Val: D)) {
6326 CheckAbstractClassUsage(Info, VD: VTD->getTemplatedDecl());
6327
6328 // Nested classes and class templates.
6329 } else if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
6330 CheckAbstractClassUsage(Info, RD);
6331 } else if (auto *CTD = dyn_cast<ClassTemplateDecl>(Val: D)) {
6332 CheckAbstractClassUsage(Info, RD: CTD->getTemplatedDecl());
6333 }
6334 }
6335}
6336
6337static void ReferenceDllExportedMembers(Sema &S, CXXRecordDecl *Class) {
6338 Attr *ClassAttr = getDLLAttr(D: Class);
6339 if (!ClassAttr)
6340 return;
6341
6342 assert(ClassAttr->getKind() == attr::DLLExport);
6343
6344 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6345
6346 if (TSK == TSK_ExplicitInstantiationDeclaration)
6347 // Don't go any further if this is just an explicit instantiation
6348 // declaration.
6349 return;
6350
6351 // Add a context note to explain how we got to any diagnostics produced below.
6352 struct MarkingClassDllexported {
6353 Sema &S;
6354 MarkingClassDllexported(Sema &S, CXXRecordDecl *Class,
6355 SourceLocation AttrLoc)
6356 : S(S) {
6357 Sema::CodeSynthesisContext Ctx;
6358 Ctx.Kind = Sema::CodeSynthesisContext::MarkingClassDllexported;
6359 Ctx.PointOfInstantiation = AttrLoc;
6360 Ctx.Entity = Class;
6361 S.pushCodeSynthesisContext(Ctx);
6362 }
6363 ~MarkingClassDllexported() {
6364 S.popCodeSynthesisContext();
6365 }
6366 } MarkingDllexportedContext(S, Class, ClassAttr->getLocation());
6367
6368 if (S.Context.getTargetInfo().getTriple().isOSCygMing())
6369 S.MarkVTableUsed(Loc: Class->getLocation(), Class, DefinitionRequired: true);
6370
6371 for (Decl *Member : Class->decls()) {
6372 // Skip members that were not marked exported.
6373 if (!Member->hasAttr<DLLExportAttr>())
6374 continue;
6375
6376 // Defined static variables that are members of an exported base
6377 // class must be marked export too.
6378 auto *VD = dyn_cast<VarDecl>(Val: Member);
6379 if (VD && VD->getStorageClass() == SC_Static &&
6380 TSK == TSK_ImplicitInstantiation)
6381 S.MarkVariableReferenced(Loc: VD->getLocation(), Var: VD);
6382
6383 auto *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6384 if (!MD)
6385 continue;
6386
6387 if (MD->isUserProvided()) {
6388 // Instantiate non-default class member functions ...
6389
6390 // .. except for certain kinds of template specializations.
6391 if (TSK == TSK_ImplicitInstantiation && !ClassAttr->isInherited())
6392 continue;
6393
6394 // If this is an MS ABI dllexport default constructor, instantiate any
6395 // default arguments.
6396 if (S.Context.getTargetInfo().getCXXABI().isMicrosoft()) {
6397 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6398 if (CD && CD->isDefaultConstructor() && TSK == TSK_Undeclared) {
6399 S.BuildCtorClosureDefaultArgs(
6400 Loc: CD->getAttr<DLLExportAttr>()->getLocation(), Ctor: CD);
6401 }
6402 }
6403
6404 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6405
6406 // The function will be passed to the consumer when its definition is
6407 // encountered.
6408 } else if (MD->isExplicitlyDefaulted()) {
6409 // Synthesize and instantiate explicitly defaulted methods.
6410 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6411
6412 if (TSK != TSK_ExplicitInstantiationDefinition) {
6413 // Except for explicit instantiation defs, we will not see the
6414 // definition again later, so pass it to the consumer now.
6415 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6416 }
6417 } else if (!MD->isTrivial() ||
6418 MD->isCopyAssignmentOperator() ||
6419 MD->isMoveAssignmentOperator()) {
6420 // Synthesize and instantiate non-trivial implicit methods, and the copy
6421 // and move assignment operators. The latter are exported even if they
6422 // are trivial, because the address of an operator can be taken and
6423 // should compare equal across libraries.
6424 S.MarkFunctionReferenced(Loc: Class->getLocation(), Func: MD);
6425
6426 // There is no later point when we will see the definition of this
6427 // function, so pass it to the consumer now.
6428 S.Consumer.HandleTopLevelDecl(D: DeclGroupRef(MD));
6429 }
6430 }
6431}
6432
6433static void checkForMultipleExportedDefaultConstructors(Sema &S,
6434 CXXRecordDecl *Class) {
6435 // Only the MS ABI has default constructor closures, so we don't need to do
6436 // this semantic checking anywhere else.
6437 if (!S.Context.getTargetInfo().getCXXABI().isMicrosoft())
6438 return;
6439
6440 if (Class->isInvalidDecl())
6441 return;
6442
6443 CXXConstructorDecl *LastExportedDefaultCtor = nullptr;
6444 for (Decl *Member : Class->decls()) {
6445 // Nested classes finish delayed default argument parsing with the outermost
6446 // class, so check each nested definition here.
6447 if (auto *NestedClass = dyn_cast<CXXRecordDecl>(Val: Member)) {
6448 if (NestedClass->isThisDeclarationADefinition())
6449 checkForMultipleExportedDefaultConstructors(S, Class: NestedClass);
6450 continue;
6451 }
6452
6453 // Look for exported default constructors.
6454 auto *CD = dyn_cast<CXXConstructorDecl>(Val: Member);
6455 if (!CD || !CD->isDefaultConstructor())
6456 continue;
6457 auto *Attr = CD->getAttr<DLLExportAttr>();
6458 if (!Attr)
6459 continue;
6460
6461 // If the class is non-dependent, mark the default arguments as ODR-used so
6462 // that we can properly codegen the constructor closure.
6463 if (!Class->isDependentContext()) {
6464 S.BuildCtorClosureDefaultArgs(Loc: Attr->getLocation(), Ctor: CD);
6465 S.DiscardCleanupsInEvaluationContext();
6466 }
6467
6468 if (LastExportedDefaultCtor) {
6469 S.Diag(Loc: LastExportedDefaultCtor->getLocation(),
6470 DiagID: diag::err_attribute_dll_ambiguous_default_ctor)
6471 << Class;
6472 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_entity_declared_at)
6473 << CD->getDeclName();
6474 return;
6475 }
6476 LastExportedDefaultCtor = CD;
6477 }
6478}
6479
6480static void checkCUDADeviceBuiltinSurfaceClassTemplate(Sema &S,
6481 CXXRecordDecl *Class) {
6482 bool ErrorReported = false;
6483 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6484 ClassTemplateDecl *TD) {
6485 if (ErrorReported)
6486 return;
6487 S.Diag(Loc: TD->getLocation(),
6488 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6489 << /*surface*/ 0 << TD;
6490 ErrorReported = true;
6491 };
6492
6493 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6494 if (!TD) {
6495 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6496 if (!SD) {
6497 S.Diag(Loc: Class->getLocation(),
6498 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6499 << /*surface*/ 0 << Class;
6500 S.Diag(Loc: Class->getLocation(),
6501 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6502 << Class;
6503 return;
6504 }
6505 TD = SD->getSpecializedTemplate();
6506 }
6507
6508 TemplateParameterList *Params = TD->getTemplateParameters();
6509 unsigned N = Params->size();
6510
6511 if (N != 2) {
6512 reportIllegalClassTemplate(S, TD);
6513 S.Diag(Loc: TD->getLocation(),
6514 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6515 << TD << 2;
6516 }
6517 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6518 reportIllegalClassTemplate(S, TD);
6519 S.Diag(Loc: TD->getLocation(),
6520 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6521 << TD << /*1st*/ 0 << /*type*/ 0;
6522 }
6523 if (N > 1) {
6524 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6525 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6526 reportIllegalClassTemplate(S, TD);
6527 S.Diag(Loc: TD->getLocation(),
6528 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6529 << TD << /*2nd*/ 1 << /*integer*/ 1;
6530 }
6531 }
6532}
6533
6534static void checkCUDADeviceBuiltinTextureClassTemplate(Sema &S,
6535 CXXRecordDecl *Class) {
6536 bool ErrorReported = false;
6537 auto reportIllegalClassTemplate = [&ErrorReported](Sema &S,
6538 ClassTemplateDecl *TD) {
6539 if (ErrorReported)
6540 return;
6541 S.Diag(Loc: TD->getLocation(),
6542 DiagID: diag::err_cuda_device_builtin_surftex_cls_template)
6543 << /*texture*/ 1 << TD;
6544 ErrorReported = true;
6545 };
6546
6547 ClassTemplateDecl *TD = Class->getDescribedClassTemplate();
6548 if (!TD) {
6549 auto *SD = dyn_cast<ClassTemplateSpecializationDecl>(Val: Class);
6550 if (!SD) {
6551 S.Diag(Loc: Class->getLocation(),
6552 DiagID: diag::err_cuda_device_builtin_surftex_ref_decl)
6553 << /*texture*/ 1 << Class;
6554 S.Diag(Loc: Class->getLocation(),
6555 DiagID: diag::note_cuda_device_builtin_surftex_should_be_template_class)
6556 << Class;
6557 return;
6558 }
6559 TD = SD->getSpecializedTemplate();
6560 }
6561
6562 TemplateParameterList *Params = TD->getTemplateParameters();
6563 unsigned N = Params->size();
6564
6565 if (N != 3) {
6566 reportIllegalClassTemplate(S, TD);
6567 S.Diag(Loc: TD->getLocation(),
6568 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_n_args)
6569 << TD << 3;
6570 }
6571 if (N > 0 && !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
6572 reportIllegalClassTemplate(S, TD);
6573 S.Diag(Loc: TD->getLocation(),
6574 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6575 << TD << /*1st*/ 0 << /*type*/ 0;
6576 }
6577 if (N > 1) {
6578 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 1));
6579 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6580 reportIllegalClassTemplate(S, TD);
6581 S.Diag(Loc: TD->getLocation(),
6582 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6583 << TD << /*2nd*/ 1 << /*integer*/ 1;
6584 }
6585 }
6586 if (N > 2) {
6587 auto *NTTP = dyn_cast<NonTypeTemplateParmDecl>(Val: Params->getParam(Idx: 2));
6588 if (!NTTP || !NTTP->getType()->isIntegralOrEnumerationType()) {
6589 reportIllegalClassTemplate(S, TD);
6590 S.Diag(Loc: TD->getLocation(),
6591 DiagID: diag::note_cuda_device_builtin_surftex_cls_should_have_match_arg)
6592 << TD << /*3rd*/ 2 << /*integer*/ 1;
6593 }
6594 }
6595}
6596
6597void Sema::checkClassLevelCodeSegAttribute(CXXRecordDecl *Class) {
6598 // Mark any compiler-generated routines with the implicit code_seg attribute.
6599 for (auto *Method : Class->methods()) {
6600 if (Method->isUserProvided())
6601 continue;
6602 if (Attr *A = getImplicitCodeSegOrSectionAttrForFunction(FD: Method, /*IsDefinition=*/true))
6603 Method->addAttr(A);
6604 }
6605}
6606
6607void Sema::checkClassLevelDLLAttribute(CXXRecordDecl *Class) {
6608 Attr *ClassAttr = getDLLAttr(D: Class);
6609
6610 // MSVC inherits DLL attributes to partial class template specializations.
6611 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() && !ClassAttr) {
6612 if (auto *Spec = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: Class)) {
6613 if (Attr *TemplateAttr =
6614 getDLLAttr(D: Spec->getSpecializedTemplate()->getTemplatedDecl())) {
6615 auto *A = cast<InheritableAttr>(Val: TemplateAttr->clone(C&: getASTContext()));
6616 A->setInherited(true);
6617 ClassAttr = A;
6618 }
6619 }
6620 }
6621
6622 if (!ClassAttr)
6623 return;
6624
6625 // MSVC allows imported or exported template classes that have UniqueExternal
6626 // linkage. This occurs when the template class has been instantiated with
6627 // a template parameter which itself has internal linkage.
6628 // We drop the attribute to avoid exporting or importing any members.
6629 if ((Context.getTargetInfo().getCXXABI().isMicrosoft() ||
6630 Context.getTargetInfo().getTriple().isPS()) &&
6631 (!Class->isExternallyVisible() && Class->hasExternalFormalLinkage())) {
6632 Class->dropAttrs<DLLExportAttr, DLLImportAttr>();
6633 return;
6634 }
6635
6636 if (!Class->isExternallyVisible()) {
6637 Diag(Loc: Class->getLocation(), DiagID: diag::err_attribute_dll_not_extern)
6638 << Class << ClassAttr;
6639 return;
6640 }
6641
6642 if (Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6643 !ClassAttr->isInherited()) {
6644 // Diagnose dll attributes on members of class with dll attribute.
6645 for (Decl *Member : Class->decls()) {
6646 if (!isa<VarDecl>(Val: Member) && !isa<CXXMethodDecl>(Val: Member))
6647 continue;
6648 InheritableAttr *MemberAttr = getDLLAttr(D: Member);
6649 if (!MemberAttr || MemberAttr->isInherited() || Member->isInvalidDecl())
6650 continue;
6651
6652 Diag(Loc: MemberAttr->getLocation(),
6653 DiagID: diag::err_attribute_dll_member_of_dll_class)
6654 << MemberAttr << ClassAttr;
6655 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_previous_attribute);
6656 Member->setInvalidDecl();
6657 }
6658 }
6659
6660 if (Class->getDescribedClassTemplate())
6661 // Don't inherit dll attribute until the template is instantiated.
6662 return;
6663
6664 // The class is either imported or exported.
6665 const bool ClassExported = ClassAttr->getKind() == attr::DLLExport;
6666
6667 // Check if this was a dllimport attribute propagated from a derived class to
6668 // a base class template specialization. We don't apply these attributes to
6669 // static data members.
6670 const bool PropagatedImport =
6671 !ClassExported &&
6672 cast<DLLImportAttr>(Val: ClassAttr)->wasPropagatedToBaseTemplate();
6673
6674 TemplateSpecializationKind TSK = Class->getTemplateSpecializationKind();
6675
6676 // Ignore explicit dllexport on explicit class template instantiation
6677 // declarations, except in MinGW mode.
6678 if (ClassExported && !ClassAttr->isInherited() &&
6679 TSK == TSK_ExplicitInstantiationDeclaration &&
6680 !Context.getTargetInfo().getTriple().isOSCygMing()) {
6681 if (auto *DEA = Class->getAttr<DLLExportAttr>()) {
6682 Class->addAttr(A: DLLExportOnDeclAttr::Create(Ctx&: Context, Range: DEA->getLoc()));
6683 Class->dropAttr<DLLExportAttr>();
6684 }
6685 return;
6686 }
6687
6688 // Force declaration of implicit members so they can inherit the attribute.
6689 ForceDeclarationOfImplicitMembers(Class);
6690
6691 // Inherited constructors are created lazily; force their creation now so the
6692 // loop below can propagate the DLL attribute to them.
6693 if (ClassExported && getLangOpts().DllExportInlines) {
6694 SmallVector<ConstructorUsingShadowDecl *, 4> Shadows;
6695 for (Decl *D : Class->decls())
6696 if (auto *S = dyn_cast<ConstructorUsingShadowDecl>(Val: D))
6697 Shadows.push_back(Elt: S);
6698 for (ConstructorUsingShadowDecl *S : Shadows) {
6699 CXXConstructorDecl *BC = dyn_cast<CXXConstructorDecl>(Val: S->getTargetDecl());
6700 if (!BC || BC->isDeleted())
6701 continue;
6702 // Skip constructors whose requires clause is not satisfied.
6703 // Normally overload resolution filters these, but we are bypassing
6704 // it to eagerly create inherited constructors for dllexport.
6705 if (BC->getTrailingRequiresClause()) {
6706 ConstraintSatisfaction Satisfaction;
6707 if (CheckFunctionConstraints(FD: BC, Satisfaction) ||
6708 !Satisfaction.IsSatisfied)
6709 continue;
6710 }
6711 findInheritingConstructor(Loc: Class->getLocation(), BaseCtor: BC, DerivedShadow: S);
6712 }
6713 }
6714
6715 // FIXME: MSVC's docs say all bases must be exportable, but this doesn't
6716 // seem to be true in practice?
6717
6718 for (Decl *Member : Class->decls()) {
6719 if (Member->hasAttr<ExcludeFromExplicitInstantiationAttr>())
6720 continue;
6721
6722 VarDecl *VD = dyn_cast<VarDecl>(Val: Member);
6723 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: Member);
6724
6725 // Only methods and static fields inherit the attributes.
6726 if (!VD && !MD)
6727 continue;
6728
6729 if (MD) {
6730 // Don't process deleted methods.
6731 if (MD->isDeleted())
6732 continue;
6733
6734 if (ClassExported && getLangOpts().DllExportInlines) {
6735 CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6736 if (CD && CD->getInheritedConstructor()) {
6737 // Inherited constructors already had their base constructor's
6738 // constraints checked before creation via
6739 // findInheritingConstructor, so only ABI-compatibility checks
6740 // are needed here.
6741 //
6742 // Don't export inherited constructors whose parameters prevent
6743 // ABI-compatible forwarding. When canEmitDelegateCallArgs (in
6744 // CodeGen) returns false, Clang inlines the constructor body
6745 // instead of emitting a forwarding thunk, producing code that
6746 // is not ABI-compatible with MSVC. Suppress the export and warn
6747 // so the user gets a linker error rather than a silent runtime
6748 // mismatch.
6749 if (CD->isVariadic()) {
6750 Diag(Loc: CD->getLocation(),
6751 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6752 << /*variadic=*/0;
6753 continue;
6754 }
6755 if (Context.getTargetInfo()
6756 .getCXXABI()
6757 .areArgsDestroyedLeftToRightInCallee()) {
6758 bool HasCalleeCleanupParam = false;
6759 for (const ParmVarDecl *P : CD->parameters())
6760 if (P->needsDestruction(Ctx: Context)) {
6761 HasCalleeCleanupParam = true;
6762 break;
6763 }
6764 if (HasCalleeCleanupParam) {
6765 Diag(Loc: CD->getLocation(),
6766 DiagID: diag::warn_dllexport_inherited_ctor_unsupported)
6767 << /*callee-cleanup=*/1;
6768 continue;
6769 }
6770 }
6771 } else if (MD->getTrailingRequiresClause()) {
6772 // Don't export methods whose requires clause is not satisfied.
6773 // For class template specializations, member constraints may
6774 // depend on template arguments and an unsatisfied constraint
6775 // means the member should not be available in this
6776 // specialization.
6777 ConstraintSatisfaction Satisfaction;
6778 if (CheckFunctionConstraints(FD: MD, Satisfaction) ||
6779 !Satisfaction.IsSatisfied)
6780 continue;
6781 }
6782 }
6783
6784 if (MD->isInlined()) {
6785 // MinGW does not import or export inline methods. But do it for
6786 // template instantiations and inherited constructors (which are
6787 // marked inline but must be exported to match MSVC behavior).
6788 if (!Context.getTargetInfo().shouldDLLImportComdatSymbols() &&
6789 TSK != TSK_ExplicitInstantiationDeclaration &&
6790 TSK != TSK_ExplicitInstantiationDefinition) {
6791 if (auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
6792 !CD || !CD->getInheritedConstructor())
6793 continue;
6794 }
6795
6796 // MSVC versions before 2015 don't export the move assignment operators
6797 // and move constructor, so don't attempt to import/export them if
6798 // we have a definition.
6799 auto *Ctor = dyn_cast<CXXConstructorDecl>(Val: MD);
6800 if ((MD->isMoveAssignmentOperator() ||
6801 (Ctor && Ctor->isMoveConstructor())) &&
6802 getLangOpts().isCompatibleWithMSVC() &&
6803 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015))
6804 continue;
6805
6806 // MSVC2015 doesn't export trivial defaulted x-tor but copy assign
6807 // operator is exported anyway.
6808 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
6809 (Ctor || isa<CXXDestructorDecl>(Val: MD)) && MD->isTrivial())
6810 continue;
6811 }
6812 }
6813
6814 // Don't apply dllimport attributes to static data members of class template
6815 // instantiations when the attribute is propagated from a derived class.
6816 if (VD && PropagatedImport)
6817 continue;
6818
6819 if (!cast<NamedDecl>(Val: Member)->isExternallyVisible())
6820 continue;
6821
6822 if (!getDLLAttr(D: Member)) {
6823 InheritableAttr *NewAttr = nullptr;
6824
6825 // Do not export/import inline function when -fno-dllexport-inlines is
6826 // passed. But add attribute for later local static var check.
6827 if (!getLangOpts().DllExportInlines && MD && MD->isInlined() &&
6828 TSK != TSK_ExplicitInstantiationDeclaration &&
6829 TSK != TSK_ExplicitInstantiationDefinition) {
6830 if (ClassExported) {
6831 NewAttr = ::new (getASTContext())
6832 DLLExportStaticLocalAttr(getASTContext(), *ClassAttr);
6833 } else {
6834 NewAttr = ::new (getASTContext())
6835 DLLImportStaticLocalAttr(getASTContext(), *ClassAttr);
6836 }
6837 } else {
6838 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6839 }
6840
6841 NewAttr->setInherited(true);
6842 Member->addAttr(A: NewAttr);
6843
6844 if (MD) {
6845 // Propagate DLLAttr to friend re-declarations of MD that have already
6846 // been constructed.
6847 for (FunctionDecl *FD = MD->getMostRecentDecl(); FD;
6848 FD = FD->getPreviousDecl()) {
6849 if (FD->getFriendObjectKind() == Decl::FOK_None)
6850 continue;
6851 assert(!getDLLAttr(FD) &&
6852 "friend re-decl should not already have a DLLAttr");
6853 NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6854 NewAttr->setInherited(true);
6855 FD->addAttr(A: NewAttr);
6856 }
6857 }
6858 }
6859 }
6860
6861 if (ClassExported)
6862 DelayedDllExportClasses.push_back(Elt: Class);
6863}
6864
6865void Sema::propagateDLLAttrToBaseClassTemplate(
6866 CXXRecordDecl *Class, Attr *ClassAttr,
6867 ClassTemplateSpecializationDecl *BaseTemplateSpec, SourceLocation BaseLoc) {
6868 if (getDLLAttr(
6869 D: BaseTemplateSpec->getSpecializedTemplate()->getTemplatedDecl())) {
6870 // If the base class template has a DLL attribute, don't try to change it.
6871 return;
6872 }
6873
6874 auto TSK = BaseTemplateSpec->getSpecializationKind();
6875 if (!getDLLAttr(D: BaseTemplateSpec) &&
6876 (TSK == TSK_Undeclared || TSK == TSK_ExplicitInstantiationDeclaration ||
6877 TSK == TSK_ImplicitInstantiation)) {
6878 // The template hasn't been instantiated yet (or it has, but only as an
6879 // explicit instantiation declaration or implicit instantiation, which means
6880 // we haven't codegenned any members yet), so propagate the attribute.
6881 auto *NewAttr = cast<InheritableAttr>(Val: ClassAttr->clone(C&: getASTContext()));
6882 NewAttr->setInherited(true);
6883 BaseTemplateSpec->addAttr(A: NewAttr);
6884
6885 // If this was an import, mark that we propagated it from a derived class to
6886 // a base class template specialization.
6887 if (auto *ImportAttr = dyn_cast<DLLImportAttr>(Val: NewAttr))
6888 ImportAttr->setPropagatedToBaseTemplate();
6889
6890 // If the template is already instantiated, checkDLLAttributeRedeclaration()
6891 // needs to be run again to work see the new attribute. Otherwise this will
6892 // get run whenever the template is instantiated.
6893 if (TSK != TSK_Undeclared)
6894 checkClassLevelDLLAttribute(Class: BaseTemplateSpec);
6895
6896 return;
6897 }
6898
6899 if (getDLLAttr(D: BaseTemplateSpec)) {
6900 // The template has already been specialized or instantiated with an
6901 // attribute, explicitly or through propagation. We should not try to change
6902 // it.
6903 return;
6904 }
6905
6906 // The template was previously instantiated or explicitly specialized without
6907 // a dll attribute, It's too late for us to add an attribute, so warn that
6908 // this is unsupported.
6909 Diag(Loc: BaseLoc, DiagID: diag::warn_attribute_dll_instantiated_base_class)
6910 << BaseTemplateSpec->isExplicitSpecialization();
6911 Diag(Loc: ClassAttr->getLocation(), DiagID: diag::note_attribute);
6912 if (BaseTemplateSpec->isExplicitSpecialization()) {
6913 Diag(Loc: BaseTemplateSpec->getLocation(),
6914 DiagID: diag::note_template_class_explicit_specialization_was_here)
6915 << BaseTemplateSpec;
6916 } else {
6917 Diag(Loc: BaseTemplateSpec->getPointOfInstantiation(),
6918 DiagID: diag::note_template_class_instantiation_was_here)
6919 << BaseTemplateSpec;
6920 }
6921}
6922
6923namespace {
6924/// RAII object to restore the floating-point (FP) features active at the time
6925/// a defaulted function was declared. This ensures that the synthesized body
6926/// of the function respects the FP pragmas (e.g., #pragma STDC FENV_ACCESS)
6927/// that were in effect when the function was explicitly defaulted.
6928struct DefaultedFunctionFPFeaturesRAII {
6929 Sema::FPFeaturesStateRAII SavedFPFeatures;
6930 DefaultedFunctionFPFeaturesRAII(Sema &S, FunctionDecl *FD)
6931 : SavedFPFeatures(S) {
6932 auto *Info = FD->getDefaultedOrDeletedInfo();
6933 FPOptionsOverride FPO = Info ? Info->getFPFeatures() : FPOptionsOverride();
6934 S.CurFPFeatures = FPO.applyOverrides(LO: S.LangOpts);
6935 S.FpPragmaStack.CurrentValue = FPO;
6936 }
6937
6938 ~DefaultedFunctionFPFeaturesRAII() = default;
6939};
6940} // namespace
6941
6942static void DefineDefaultedFunction(Sema &S, FunctionDecl *FD,
6943 SourceLocation DefaultLoc) {
6944 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
6945 if (DFK.isComparison())
6946 return S.DefineDefaultedComparison(Loc: DefaultLoc, FD, DCK: DFK.asComparison());
6947
6948 switch (DFK.asSpecialMember()) {
6949 case CXXSpecialMemberKind::DefaultConstructor:
6950 S.DefineImplicitDefaultConstructor(CurrentLocation: DefaultLoc,
6951 Constructor: cast<CXXConstructorDecl>(Val: FD));
6952 break;
6953 case CXXSpecialMemberKind::CopyConstructor:
6954 S.DefineImplicitCopyConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6955 break;
6956 case CXXSpecialMemberKind::CopyAssignment:
6957 S.DefineImplicitCopyAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6958 break;
6959 case CXXSpecialMemberKind::Destructor:
6960 S.DefineImplicitDestructor(CurrentLocation: DefaultLoc, Destructor: cast<CXXDestructorDecl>(Val: FD));
6961 break;
6962 case CXXSpecialMemberKind::MoveConstructor:
6963 S.DefineImplicitMoveConstructor(CurrentLocation: DefaultLoc, Constructor: cast<CXXConstructorDecl>(Val: FD));
6964 break;
6965 case CXXSpecialMemberKind::MoveAssignment:
6966 S.DefineImplicitMoveAssignment(CurrentLocation: DefaultLoc, MethodDecl: cast<CXXMethodDecl>(Val: FD));
6967 break;
6968 case CXXSpecialMemberKind::Invalid:
6969 llvm_unreachable("Invalid special member.");
6970 }
6971}
6972
6973/// Determine whether a type is permitted to be passed or returned in
6974/// registers, per C++ [class.temporary]p3.
6975static bool canPassInRegisters(Sema &S, CXXRecordDecl *D,
6976 TargetInfo::CallingConvKind CCK) {
6977 if (D->isDependentType() || D->isInvalidDecl())
6978 return false;
6979
6980 // Clang <= 4 used the pre-C++11 rule, which ignores move operations.
6981 // The PS4 platform ABI follows the behavior of Clang 3.2.
6982 if (CCK == TargetInfo::CCK_ClangABI4OrPS4)
6983 return !D->hasNonTrivialDestructorForCall() &&
6984 !D->hasNonTrivialCopyConstructorForCall();
6985
6986 if (CCK == TargetInfo::CCK_MicrosoftWin64) {
6987 bool CopyCtorIsTrivial = false, CopyCtorIsTrivialForCall = false;
6988 bool DtorIsTrivialForCall = false;
6989
6990 // If a class has at least one eligible, trivial copy constructor, it
6991 // is passed according to the C ABI. Otherwise, it is passed indirectly.
6992 //
6993 // Note: This permits classes with non-trivial copy or move ctors to be
6994 // passed in registers, so long as they *also* have a trivial copy ctor,
6995 // which is non-conforming.
6996 if (D->needsImplicitCopyConstructor()) {
6997 if (!D->defaultedCopyConstructorIsDeleted()) {
6998 if (D->hasTrivialCopyConstructor())
6999 CopyCtorIsTrivial = true;
7000 if (D->hasTrivialCopyConstructorForCall())
7001 CopyCtorIsTrivialForCall = true;
7002 }
7003 } else {
7004 for (const CXXConstructorDecl *CD : D->ctors()) {
7005 if (CD->isCopyConstructor() && !CD->isDeleted() &&
7006 !CD->isIneligibleOrNotSelected()) {
7007 if (CD->isTrivial())
7008 CopyCtorIsTrivial = true;
7009 if (CD->isTrivialForCall())
7010 CopyCtorIsTrivialForCall = true;
7011 }
7012 }
7013 }
7014
7015 if (D->needsImplicitDestructor()) {
7016 if (!D->defaultedDestructorIsDeleted() &&
7017 D->hasTrivialDestructorForCall())
7018 DtorIsTrivialForCall = true;
7019 } else if (const auto *DD = D->getDestructor()) {
7020 if (!DD->isDeleted() && DD->isTrivialForCall())
7021 DtorIsTrivialForCall = true;
7022 }
7023
7024 // If the copy ctor and dtor are both trivial-for-calls, pass direct.
7025 if (CopyCtorIsTrivialForCall && DtorIsTrivialForCall)
7026 return true;
7027
7028 // If a class has a destructor, we'd really like to pass it indirectly
7029 // because it allows us to elide copies. Unfortunately, MSVC makes that
7030 // impossible for small types, which it will pass in a single register or
7031 // stack slot. Most objects with dtors are large-ish, so handle that early.
7032 // We can't call out all large objects as being indirect because there are
7033 // multiple x64 calling conventions and the C++ ABI code shouldn't dictate
7034 // how we pass large POD types.
7035
7036 // Note: This permits small classes with nontrivial destructors to be
7037 // passed in registers, which is non-conforming.
7038 bool isAArch64 = S.Context.getTargetInfo().getTriple().isAArch64();
7039 uint64_t TypeSize = isAArch64 ? 128 : 64;
7040
7041 if (CopyCtorIsTrivial && S.getASTContext().getTypeSize(
7042 T: S.Context.getCanonicalTagType(TD: D)) <= TypeSize)
7043 return true;
7044 return false;
7045 }
7046
7047 // Per C++ [class.temporary]p3, the relevant condition is:
7048 // each copy constructor, move constructor, and destructor of X is
7049 // either trivial or deleted, and X has at least one non-deleted copy
7050 // or move constructor
7051 bool HasNonDeletedCopyOrMove = false;
7052
7053 if (D->needsImplicitCopyConstructor() &&
7054 !D->defaultedCopyConstructorIsDeleted()) {
7055 if (!D->hasTrivialCopyConstructorForCall())
7056 return false;
7057 HasNonDeletedCopyOrMove = true;
7058 }
7059
7060 if (S.getLangOpts().CPlusPlus11 && D->needsImplicitMoveConstructor() &&
7061 !D->defaultedMoveConstructorIsDeleted()) {
7062 if (!D->hasTrivialMoveConstructorForCall())
7063 return false;
7064 HasNonDeletedCopyOrMove = true;
7065 }
7066
7067 if (D->needsImplicitDestructor() && !D->defaultedDestructorIsDeleted() &&
7068 !D->hasTrivialDestructorForCall())
7069 return false;
7070
7071 for (const CXXMethodDecl *MD : D->methods()) {
7072 if (MD->isDeleted() || MD->isIneligibleOrNotSelected())
7073 continue;
7074
7075 auto *CD = dyn_cast<CXXConstructorDecl>(Val: MD);
7076 if (CD && CD->isCopyOrMoveConstructor())
7077 HasNonDeletedCopyOrMove = true;
7078 else if (!isa<CXXDestructorDecl>(Val: MD))
7079 continue;
7080
7081 if (!MD->isTrivialForCall())
7082 return false;
7083 }
7084
7085 return HasNonDeletedCopyOrMove;
7086}
7087
7088/// Report an error regarding overriding, along with any relevant
7089/// overridden methods.
7090///
7091/// \param DiagID the primary error to report.
7092/// \param MD the overriding method.
7093static bool
7094ReportOverrides(Sema &S, unsigned DiagID, const CXXMethodDecl *MD,
7095 llvm::function_ref<bool(const CXXMethodDecl *)> Report) {
7096 bool IssuedDiagnostic = false;
7097 for (const CXXMethodDecl *O : MD->overridden_methods()) {
7098 if (Report(O)) {
7099 if (!IssuedDiagnostic) {
7100 S.Diag(Loc: MD->getLocation(), DiagID) << MD->getDeclName();
7101 IssuedDiagnostic = true;
7102 }
7103 S.Diag(Loc: O->getLocation(), DiagID: diag::note_overridden_virtual_function);
7104 }
7105 }
7106 return IssuedDiagnostic;
7107}
7108
7109void Sema::CheckCompletedCXXClass(Scope *S, CXXRecordDecl *Record) {
7110 if (!Record)
7111 return;
7112
7113 if (Record->isAbstract() && !Record->isInvalidDecl()) {
7114 AbstractUsageInfo Info(*this, Record);
7115 CheckAbstractClassUsage(Info, RD: Record);
7116 }
7117
7118 // If this is not an aggregate type and has no user-declared constructor,
7119 // complain about any non-static data members of reference or const scalar
7120 // type, since they will never get initializers.
7121 if (!Record->isInvalidDecl() && !Record->isDependentType() &&
7122 !Record->isAggregate() && !Record->hasUserDeclaredConstructor() &&
7123 !Record->isLambda()) {
7124 bool Complained = false;
7125 for (const auto *F : Record->fields()) {
7126 if (F->hasInClassInitializer() || F->isUnnamedBitField())
7127 continue;
7128
7129 if (F->getType()->isReferenceType() ||
7130 (F->getType().isConstQualified() && F->getType()->isScalarType())) {
7131 if (!Complained) {
7132 Diag(Loc: Record->getLocation(), DiagID: diag::warn_no_constructor_for_refconst)
7133 << Record->getTagKind() << Record;
7134 Complained = true;
7135 }
7136
7137 Diag(Loc: F->getLocation(), DiagID: diag::note_refconst_member_not_initialized)
7138 << F->getType()->isReferenceType()
7139 << F->getDeclName();
7140 }
7141 }
7142 }
7143
7144 if (Record->getIdentifier()) {
7145 // C++ [class.mem]p13:
7146 // If T is the name of a class, then each of the following shall have a
7147 // name different from T:
7148 // - every member of every anonymous union that is a member of class T.
7149 //
7150 // C++ [class.mem]p14:
7151 // In addition, if class T has a user-declared constructor (12.1), every
7152 // non-static data member of class T shall have a name different from T.
7153 for (const NamedDecl *Element : Record->lookup(Name: Record->getDeclName())) {
7154 const NamedDecl *D = Element->getUnderlyingDecl();
7155 // Invalid IndirectFieldDecls have already been diagnosed with
7156 // err_anonymous_record_member_redecl in
7157 // SemaDecl.cpp:CheckAnonMemberRedeclaration.
7158 if (((isa<FieldDecl>(Val: D) || isa<UnresolvedUsingValueDecl>(Val: D)) &&
7159 Record->hasUserDeclaredConstructor()) ||
7160 (isa<IndirectFieldDecl>(Val: D) && !D->isInvalidDecl())) {
7161 Diag(Loc: Element->getLocation(), DiagID: diag::err_member_name_of_class)
7162 << D->getDeclName();
7163 break;
7164 }
7165 }
7166 }
7167
7168 // Warn if the class has virtual methods but non-virtual public destructor.
7169 if (Record->isPolymorphic() && !Record->isDependentType()) {
7170 CXXDestructorDecl *dtor = Record->getDestructor();
7171 if ((!dtor || (!dtor->isVirtual() && dtor->getAccess() == AS_public)) &&
7172 !Record->hasAttr<FinalAttr>())
7173 Diag(Loc: dtor ? dtor->getLocation() : Record->getLocation(),
7174 DiagID: diag::warn_non_virtual_dtor)
7175 << Context.getCanonicalTagType(TD: Record);
7176 }
7177
7178 if (Record->isAbstract()) {
7179 if (FinalAttr *FA = Record->getAttr<FinalAttr>()) {
7180 Diag(Loc: Record->getLocation(), DiagID: diag::warn_abstract_final_class)
7181 << FA->isSpelledAsSealed();
7182 DiagnoseAbstractType(RD: Record);
7183 }
7184 }
7185
7186 // Warn if the class has a final destructor but is not itself marked final.
7187 if (!Record->hasAttr<FinalAttr>()) {
7188 if (const CXXDestructorDecl *dtor = Record->getDestructor()) {
7189 if (const FinalAttr *FA = dtor->getAttr<FinalAttr>()) {
7190 Diag(Loc: FA->getLocation(), DiagID: diag::warn_final_dtor_non_final_class)
7191 << FA->isSpelledAsSealed()
7192 << FixItHint::CreateInsertion(
7193 InsertionLoc: getLocForEndOfToken(Loc: Record->getLocation()),
7194 Code: (FA->isSpelledAsSealed() ? " sealed" : " final"));
7195 Diag(Loc: Record->getLocation(),
7196 DiagID: diag::note_final_dtor_non_final_class_silence)
7197 << Context.getCanonicalTagType(TD: Record) << FA->isSpelledAsSealed();
7198 }
7199 }
7200 }
7201
7202 // See if trivial_abi has to be dropped.
7203 if (Record->hasAttr<TrivialABIAttr>())
7204 checkIllFormedTrivialABIStruct(RD&: *Record);
7205
7206 // Set HasTrivialSpecialMemberForCall if the record has attribute
7207 // "trivial_abi".
7208 bool HasTrivialABI = Record->hasAttr<TrivialABIAttr>();
7209
7210 if (HasTrivialABI)
7211 Record->setHasTrivialSpecialMemberForCall();
7212
7213 // Explicitly-defaulted secondary comparison functions (!=, <, <=, >, >=).
7214 // We check these last because they can depend on the properties of the
7215 // primary comparison functions (==, <=>).
7216 llvm::SmallVector<FunctionDecl*, 5> DefaultedSecondaryComparisons;
7217
7218 // Perform checks that can't be done until we know all the properties of a
7219 // member function (whether it's defaulted, deleted, virtual, overriding,
7220 // ...).
7221 auto CheckCompletedMemberFunction = [&](CXXMethodDecl *MD) {
7222 // A static function cannot override anything.
7223 if (MD->getStorageClass() == SC_Static) {
7224 if (ReportOverrides(S&: *this, DiagID: diag::err_static_overrides_virtual, MD,
7225 Report: [](const CXXMethodDecl *) { return true; }))
7226 return;
7227 }
7228
7229 // A deleted function cannot override a non-deleted function and vice
7230 // versa.
7231 if (ReportOverrides(S&: *this,
7232 DiagID: MD->isDeleted() ? diag::err_deleted_override
7233 : diag::err_non_deleted_override,
7234 MD, Report: [&](const CXXMethodDecl *V) {
7235 return MD->isDeleted() != V->isDeleted();
7236 })) {
7237 if (MD->isDefaulted() && MD->isDeleted())
7238 // Explain why this defaulted function was deleted.
7239 DiagnoseDeletedDefaultedFunction(FD: MD);
7240 return;
7241 }
7242
7243 // A consteval function cannot override a non-consteval function and vice
7244 // versa.
7245 if (ReportOverrides(S&: *this,
7246 DiagID: MD->isConsteval() ? diag::err_consteval_override
7247 : diag::err_non_consteval_override,
7248 MD, Report: [&](const CXXMethodDecl *V) {
7249 return MD->isConsteval() != V->isConsteval();
7250 })) {
7251 if (MD->isDefaulted() && MD->isDeleted())
7252 // Explain why this defaulted function was deleted.
7253 DiagnoseDeletedDefaultedFunction(FD: MD);
7254 return;
7255 }
7256 };
7257
7258 auto CheckForDefaultedFunction = [&](FunctionDecl *FD) -> bool {
7259 if (!FD || FD->isInvalidDecl() || !FD->isExplicitlyDefaulted())
7260 return false;
7261
7262 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
7263 if (DFK.asComparison() == DefaultedComparisonKind::NotEqual ||
7264 DFK.asComparison() == DefaultedComparisonKind::Relational) {
7265 DefaultedSecondaryComparisons.push_back(Elt: FD);
7266 return true;
7267 }
7268
7269 CheckExplicitlyDefaultedFunction(S, MD: FD);
7270 return false;
7271 };
7272
7273 if (!Record->isInvalidDecl() &&
7274 Record->hasAttr<VTablePointerAuthenticationAttr>())
7275 checkIncorrectVTablePointerAuthenticationAttribute(RD&: *Record);
7276
7277 auto CompleteMemberFunction = [&](CXXMethodDecl *M) {
7278 // Check whether the explicitly-defaulted members are valid.
7279 bool Incomplete = CheckForDefaultedFunction(M);
7280
7281 // Skip the rest of the checks for a member of a dependent class.
7282 if (Record->isDependentType())
7283 return;
7284
7285 // For an explicitly defaulted or deleted special member, we defer
7286 // determining triviality until the class is complete. That time is now!
7287 CXXSpecialMemberKind CSM = M->getSpecialMemberKind();
7288 if (!M->isImplicit() && !M->isUserProvided()) {
7289 if (CSM != CXXSpecialMemberKind::Invalid) {
7290 M->setTrivial(SpecialMemberIsTrivial(MD: M, CSM));
7291 // Inform the class that we've finished declaring this member.
7292 Record->finishedDefaultedOrDeletedMember(MD: M);
7293 M->setTrivialForCall(
7294 HasTrivialABI ||
7295 SpecialMemberIsTrivial(MD: M, CSM,
7296 TAH: TrivialABIHandling::ConsiderTrivialABI));
7297 Record->setTrivialForCallFlags(M);
7298 }
7299 }
7300
7301 // Set triviality for the purpose of calls if this is a user-provided
7302 // copy/move constructor or destructor.
7303 if ((CSM == CXXSpecialMemberKind::CopyConstructor ||
7304 CSM == CXXSpecialMemberKind::MoveConstructor ||
7305 CSM == CXXSpecialMemberKind::Destructor) &&
7306 M->isUserProvided()) {
7307 M->setTrivialForCall(HasTrivialABI);
7308 Record->setTrivialForCallFlags(M);
7309 }
7310
7311 if (!M->isInvalidDecl() && M->isExplicitlyDefaulted() &&
7312 M->hasAttr<DLLExportAttr>()) {
7313 if (getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015) &&
7314 M->isTrivial() &&
7315 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7316 CSM == CXXSpecialMemberKind::CopyConstructor ||
7317 CSM == CXXSpecialMemberKind::Destructor))
7318 M->dropAttr<DLLExportAttr>();
7319
7320 if (M->hasAttr<DLLExportAttr>()) {
7321 // Define after any fields with in-class initializers have been parsed.
7322 DelayedDllExportMemberFunctions.push_back(Elt: M);
7323 }
7324 }
7325
7326 bool EffectivelyConstexprDestructor = true;
7327 // Avoid triggering vtable instantiation due to a dtor that is not
7328 // "effectively constexpr" for better compatibility.
7329 // See https://github.com/llvm/llvm-project/issues/102293 for more info.
7330 if (isa<CXXDestructorDecl>(Val: M)) {
7331 llvm::SmallDenseSet<QualType> Visited;
7332 auto Check = [&Visited](QualType T, auto &&Check) -> bool {
7333 if (!Visited.insert(V: T->getCanonicalTypeUnqualified()).second)
7334 return false;
7335 const CXXRecordDecl *RD =
7336 T->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
7337 if (!RD || !RD->isCompleteDefinition())
7338 return true;
7339
7340 if (!RD->hasConstexprDestructor())
7341 return false;
7342
7343 for (const CXXBaseSpecifier &B : RD->bases())
7344 if (!Check(B.getType(), Check))
7345 return false;
7346 for (const FieldDecl *FD : RD->fields())
7347 if (!Check(FD->getType(), Check))
7348 return false;
7349 return true;
7350 };
7351 EffectivelyConstexprDestructor =
7352 Check(Context.getCanonicalTagType(TD: Record), Check);
7353 }
7354
7355 // Define defaulted constexpr virtual functions that override a base class
7356 // function right away.
7357 // FIXME: We can defer doing this until the vtable is marked as used.
7358 if (CSM != CXXSpecialMemberKind::Invalid && !M->isDeleted() &&
7359 M->isDefaulted() && M->isConstexpr() && M->size_overridden_methods() &&
7360 EffectivelyConstexprDestructor)
7361 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
7362
7363 if (!Incomplete)
7364 CheckCompletedMemberFunction(M);
7365 };
7366
7367 // Check the destructor before any other member function. We need to
7368 // determine whether it's trivial in order to determine whether the claas
7369 // type is a literal type, which is a prerequisite for determining whether
7370 // other special member functions are valid and whether they're implicitly
7371 // 'constexpr'.
7372 if (CXXDestructorDecl *Dtor = Record->getDestructor())
7373 CompleteMemberFunction(Dtor);
7374
7375 bool HasMethodWithOverrideControl = false,
7376 HasOverridingMethodWithoutOverrideControl = false;
7377 for (auto *D : Record->decls()) {
7378 if (auto *M = dyn_cast<CXXMethodDecl>(Val: D)) {
7379 // FIXME: We could do this check for dependent types with non-dependent
7380 // bases.
7381 if (!Record->isDependentType()) {
7382 // See if a method overloads virtual methods in a base
7383 // class without overriding any.
7384 if (!M->isStatic())
7385 DiagnoseHiddenVirtualMethods(MD: M);
7386
7387 if (M->hasAttr<OverrideAttr>()) {
7388 HasMethodWithOverrideControl = true;
7389 } else if (M->size_overridden_methods() > 0) {
7390 HasOverridingMethodWithoutOverrideControl = true;
7391 } else {
7392 // Warn on newly-declared virtual methods in `final` classes
7393 if (M->isVirtualAsWritten() && Record->isEffectivelyFinal()) {
7394 Diag(Loc: M->getLocation(), DiagID: diag::warn_unnecessary_virtual_specifier)
7395 << M;
7396 }
7397 }
7398 }
7399
7400 if (!isa<CXXDestructorDecl>(Val: M))
7401 CompleteMemberFunction(M);
7402 } else if (auto *F = dyn_cast<FriendDecl>(Val: D)) {
7403 CheckForDefaultedFunction(
7404 dyn_cast_or_null<FunctionDecl>(Val: F->getFriendDecl()));
7405 }
7406 }
7407
7408 if (HasOverridingMethodWithoutOverrideControl) {
7409 bool HasInconsistentOverrideControl = HasMethodWithOverrideControl;
7410 for (auto *M : Record->methods())
7411 DiagnoseAbsenceOfOverrideControl(D: M, Inconsistent: HasInconsistentOverrideControl);
7412 }
7413
7414 // Check the defaulted secondary comparisons after any other member functions.
7415 for (FunctionDecl *FD : DefaultedSecondaryComparisons) {
7416 CheckExplicitlyDefaultedFunction(S, MD: FD);
7417
7418 // If this is a member function, we deferred checking it until now.
7419 if (auto *MD = dyn_cast<CXXMethodDecl>(Val: FD))
7420 CheckCompletedMemberFunction(MD);
7421 }
7422
7423 // {ms,gcc}_struct is a request to change ABI rules to either follow
7424 // Microsoft or Itanium C++ ABI. However, even if these attributes are
7425 // present, we do not layout classes following foreign ABI rules, but
7426 // instead enter a special "compatibility mode", which only changes
7427 // alignments of fundamental types and layout of bit fields.
7428 // Check whether this class uses any C++ features that are implemented
7429 // completely differently in the requested ABI, and if so, emit a
7430 // diagnostic. That diagnostic defaults to an error, but we allow
7431 // projects to map it down to a warning (or ignore it). It's a fairly
7432 // common practice among users of the ms_struct pragma to
7433 // mass-annotate headers, sweeping up a bunch of types that the
7434 // project doesn't really rely on MSVC-compatible layout for. We must
7435 // therefore support "ms_struct except for C++ stuff" as a secondary
7436 // ABI.
7437 // Don't emit this diagnostic if the feature was enabled as a
7438 // language option (as opposed to via a pragma or attribute), as
7439 // the option -mms-bitfields otherwise essentially makes it impossible
7440 // to build C++ code, unless this diagnostic is turned off.
7441 if (Context.getLangOpts().getLayoutCompatibility() ==
7442 LangOptions::LayoutCompatibilityKind::Default &&
7443 Record->isMsStruct(C: Context) != Context.defaultsToMsStruct() &&
7444 (Record->isPolymorphic() || Record->getNumBases())) {
7445 Diag(Loc: Record->getLocation(), DiagID: diag::warn_cxx_ms_struct);
7446 }
7447
7448 checkClassLevelDLLAttribute(Class: Record);
7449 checkClassLevelCodeSegAttribute(Class: Record);
7450
7451 bool ClangABICompat4 =
7452 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver4);
7453 TargetInfo::CallingConvKind CCK =
7454 Context.getTargetInfo().getCallingConvKind(ClangABICompat4);
7455 bool CanPass = canPassInRegisters(S&: *this, D: Record, CCK);
7456
7457 // Do not change ArgPassingRestrictions if it has already been set to
7458 // RecordArgPassingKind::CanNeverPassInRegs.
7459 if (Record->getArgPassingRestrictions() !=
7460 RecordArgPassingKind::CanNeverPassInRegs)
7461 Record->setArgPassingRestrictions(
7462 CanPass ? RecordArgPassingKind::CanPassInRegs
7463 : RecordArgPassingKind::CannotPassInRegs);
7464
7465 // If canPassInRegisters returns true despite the record having a non-trivial
7466 // destructor, the record is destructed in the callee. This happens only when
7467 // the record or one of its subobjects has a field annotated with trivial_abi
7468 // or a field qualified with ObjC __strong/__weak.
7469 if (Context.getTargetInfo().getCXXABI().areArgsDestroyedLeftToRightInCallee())
7470 Record->setParamDestroyedInCallee(true);
7471 else if (Record->hasNonTrivialDestructor())
7472 Record->setParamDestroyedInCallee(CanPass);
7473
7474 if (getLangOpts().ForceEmitVTables) {
7475 // If we want to emit all the vtables, we need to mark it as used. This
7476 // is especially required for cases like vtable assumption loads.
7477 MarkVTableUsed(Loc: Record->getInnerLocStart(), Class: Record);
7478 }
7479
7480 if (getLangOpts().CUDA) {
7481 if (Record->hasAttr<CUDADeviceBuiltinSurfaceTypeAttr>())
7482 checkCUDADeviceBuiltinSurfaceClassTemplate(S&: *this, Class: Record);
7483 else if (Record->hasAttr<CUDADeviceBuiltinTextureTypeAttr>())
7484 checkCUDADeviceBuiltinTextureClassTemplate(S&: *this, Class: Record);
7485 }
7486
7487 llvm::SmallDenseMap<OverloadedOperatorKind,
7488 llvm::SmallVector<const FunctionDecl *, 2>, 4>
7489 TypeAwareDecls{{OO_New, {}},
7490 {OO_Array_New, {}},
7491 {OO_Delete, {}},
7492 {OO_Array_New, {}}};
7493 for (auto *D : Record->decls()) {
7494 const FunctionDecl *FnDecl = D->getAsFunction();
7495 if (!FnDecl || !FnDecl->isTypeAwareOperatorNewOrDelete())
7496 continue;
7497 assert(FnDecl->getDeclName().isAnyOperatorNewOrDelete());
7498 TypeAwareDecls[FnDecl->getOverloadedOperator()].push_back(Elt: FnDecl);
7499 }
7500 auto CheckMismatchedTypeAwareAllocators =
7501 [this, &TypeAwareDecls, Record](OverloadedOperatorKind NewKind,
7502 OverloadedOperatorKind DeleteKind) {
7503 auto &NewDecls = TypeAwareDecls[NewKind];
7504 auto &DeleteDecls = TypeAwareDecls[DeleteKind];
7505 if (NewDecls.empty() == DeleteDecls.empty())
7506 return;
7507 DeclarationName FoundOperator =
7508 Context.DeclarationNames.getCXXOperatorName(
7509 Op: NewDecls.empty() ? DeleteKind : NewKind);
7510 DeclarationName MissingOperator =
7511 Context.DeclarationNames.getCXXOperatorName(
7512 Op: NewDecls.empty() ? NewKind : DeleteKind);
7513 Diag(Loc: Record->getLocation(),
7514 DiagID: diag::err_type_aware_allocator_missing_matching_operator)
7515 << FoundOperator << Context.getCanonicalTagType(TD: Record)
7516 << MissingOperator;
7517 for (auto MD : NewDecls)
7518 Diag(Loc: MD->getLocation(),
7519 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7520 << MD;
7521 for (auto MD : DeleteDecls)
7522 Diag(Loc: MD->getLocation(),
7523 DiagID: diag::note_unmatched_type_aware_allocator_declared)
7524 << MD;
7525 };
7526 CheckMismatchedTypeAwareAllocators(OO_New, OO_Delete);
7527 CheckMismatchedTypeAwareAllocators(OO_Array_New, OO_Array_Delete);
7528}
7529
7530/// Look up the special member function that would be called by a special
7531/// member function for a subobject of class type.
7532///
7533/// \param Class The class type of the subobject.
7534/// \param CSM The kind of special member function.
7535/// \param FieldQuals If the subobject is a field, its cv-qualifiers.
7536/// \param ConstRHS True if this is a copy operation with a const object
7537/// on its RHS, that is, if the argument to the outer special member
7538/// function is 'const' and this is not a field marked 'mutable'.
7539static Sema::SpecialMemberOverloadResult
7540lookupCallFromSpecialMember(Sema &S, CXXRecordDecl *Class,
7541 CXXSpecialMemberKind CSM, unsigned FieldQuals,
7542 bool ConstRHS) {
7543 unsigned LHSQuals = 0;
7544 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7545 CSM == CXXSpecialMemberKind::MoveAssignment)
7546 LHSQuals = FieldQuals;
7547
7548 unsigned RHSQuals = FieldQuals;
7549 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7550 CSM == CXXSpecialMemberKind::Destructor)
7551 RHSQuals = 0;
7552 else if (ConstRHS)
7553 RHSQuals |= Qualifiers::Const;
7554
7555 return S.LookupSpecialMember(D: Class, SM: CSM,
7556 ConstArg: RHSQuals & Qualifiers::Const,
7557 VolatileArg: RHSQuals & Qualifiers::Volatile,
7558 RValueThis: false,
7559 ConstThis: LHSQuals & Qualifiers::Const,
7560 VolatileThis: LHSQuals & Qualifiers::Volatile);
7561}
7562
7563class Sema::InheritedConstructorInfo {
7564 Sema &S;
7565 SourceLocation UseLoc;
7566
7567 /// A mapping from the base classes through which the constructor was
7568 /// inherited to the using shadow declaration in that base class (or a null
7569 /// pointer if the constructor was declared in that base class).
7570 llvm::DenseMap<CXXRecordDecl *, ConstructorUsingShadowDecl *>
7571 InheritedFromBases;
7572
7573public:
7574 InheritedConstructorInfo(Sema &S, SourceLocation UseLoc,
7575 ConstructorUsingShadowDecl *Shadow)
7576 : S(S), UseLoc(UseLoc) {
7577 bool DiagnosedMultipleConstructedBases = false;
7578 CXXRecordDecl *ConstructedBase = nullptr;
7579 BaseUsingDecl *ConstructedBaseIntroducer = nullptr;
7580
7581 // Find the set of such base class subobjects and check that there's a
7582 // unique constructed subobject.
7583 for (auto *D : Shadow->redecls()) {
7584 auto *DShadow = cast<ConstructorUsingShadowDecl>(Val: D);
7585 auto *DNominatedBase = DShadow->getNominatedBaseClass();
7586 auto *DConstructedBase = DShadow->getConstructedBaseClass();
7587
7588 InheritedFromBases.insert(
7589 KV: std::make_pair(x: DNominatedBase->getCanonicalDecl(),
7590 y: DShadow->getNominatedBaseClassShadowDecl()));
7591 if (DShadow->constructsVirtualBase())
7592 InheritedFromBases.insert(
7593 KV: std::make_pair(x: DConstructedBase->getCanonicalDecl(),
7594 y: DShadow->getConstructedBaseClassShadowDecl()));
7595 else
7596 assert(DNominatedBase == DConstructedBase);
7597
7598 // [class.inhctor.init]p2:
7599 // If the constructor was inherited from multiple base class subobjects
7600 // of type B, the program is ill-formed.
7601 if (!ConstructedBase) {
7602 ConstructedBase = DConstructedBase;
7603 ConstructedBaseIntroducer = D->getIntroducer();
7604 } else if (ConstructedBase != DConstructedBase &&
7605 !Shadow->isInvalidDecl()) {
7606 if (!DiagnosedMultipleConstructedBases) {
7607 S.Diag(Loc: UseLoc, DiagID: diag::err_ambiguous_inherited_constructor)
7608 << Shadow->getTargetDecl();
7609 S.Diag(Loc: ConstructedBaseIntroducer->getLocation(),
7610 DiagID: diag::note_ambiguous_inherited_constructor_using)
7611 << ConstructedBase;
7612 DiagnosedMultipleConstructedBases = true;
7613 }
7614 S.Diag(Loc: D->getIntroducer()->getLocation(),
7615 DiagID: diag::note_ambiguous_inherited_constructor_using)
7616 << DConstructedBase;
7617 }
7618 }
7619
7620 if (DiagnosedMultipleConstructedBases)
7621 Shadow->setInvalidDecl();
7622 }
7623
7624 /// Find the constructor to use for inherited construction of a base class,
7625 /// and whether that base class constructor inherits the constructor from a
7626 /// virtual base class (in which case it won't actually invoke it).
7627 std::pair<CXXConstructorDecl *, bool>
7628 findConstructorForBase(CXXRecordDecl *Base, CXXConstructorDecl *Ctor) const {
7629 auto It = InheritedFromBases.find(Val: Base->getCanonicalDecl());
7630 if (It == InheritedFromBases.end())
7631 return std::make_pair(x: nullptr, y: false);
7632
7633 // This is an intermediary class.
7634 if (It->second)
7635 return std::make_pair(
7636 x: S.findInheritingConstructor(Loc: UseLoc, BaseCtor: Ctor, DerivedShadow: It->second),
7637 y: It->second->constructsVirtualBase());
7638
7639 // This is the base class from which the constructor was inherited.
7640 return std::make_pair(x&: Ctor, y: false);
7641 }
7642};
7643
7644/// Is the special member function which would be selected to perform the
7645/// specified operation on the specified class type a constexpr constructor?
7646static bool specialMemberIsConstexpr(
7647 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, unsigned Quals,
7648 bool ConstRHS, CXXConstructorDecl *InheritedCtor = nullptr,
7649 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7650 // Suppress duplicate constraint checking here, in case a constraint check
7651 // caused us to decide to do this. Any truely recursive checks will get
7652 // caught during these checks anyway.
7653 Sema::SatisfactionStackResetRAII SSRAII{S};
7654
7655 // If we're inheriting a constructor, see if we need to call it for this base
7656 // class.
7657 if (InheritedCtor) {
7658 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
7659 auto BaseCtor =
7660 Inherited->findConstructorForBase(Base: ClassDecl, Ctor: InheritedCtor).first;
7661 if (BaseCtor)
7662 return BaseCtor->isConstexpr();
7663 }
7664
7665 if (CSM == CXXSpecialMemberKind::DefaultConstructor)
7666 return ClassDecl->hasConstexprDefaultConstructor();
7667 if (CSM == CXXSpecialMemberKind::Destructor)
7668 return ClassDecl->hasConstexprDestructor();
7669
7670 Sema::SpecialMemberOverloadResult SMOR =
7671 lookupCallFromSpecialMember(S, Class: ClassDecl, CSM, FieldQuals: Quals, ConstRHS);
7672 if (!SMOR.getMethod())
7673 // A constructor we wouldn't select can't be "involved in initializing"
7674 // anything.
7675 return true;
7676 return SMOR.getMethod()->isConstexpr();
7677}
7678
7679/// Determine whether the specified special member function would be constexpr
7680/// if it were implicitly defined.
7681static bool defaultedSpecialMemberIsConstexpr(
7682 Sema &S, CXXRecordDecl *ClassDecl, CXXSpecialMemberKind CSM, bool ConstArg,
7683 CXXConstructorDecl *InheritedCtor = nullptr,
7684 Sema::InheritedConstructorInfo *Inherited = nullptr) {
7685 if (!S.getLangOpts().CPlusPlus11)
7686 return false;
7687
7688 // C++11 [dcl.constexpr]p4:
7689 // In the definition of a constexpr constructor [...]
7690 bool Ctor = true;
7691 switch (CSM) {
7692 case CXXSpecialMemberKind::DefaultConstructor:
7693 if (Inherited)
7694 break;
7695 // Since default constructor lookup is essentially trivial (and cannot
7696 // involve, for instance, template instantiation), we compute whether a
7697 // defaulted default constructor is constexpr directly within CXXRecordDecl.
7698 //
7699 // This is important for performance; we need to know whether the default
7700 // constructor is constexpr to determine whether the type is a literal type.
7701 return ClassDecl->defaultedDefaultConstructorIsConstexpr();
7702
7703 case CXXSpecialMemberKind::CopyConstructor:
7704 case CXXSpecialMemberKind::MoveConstructor:
7705 // For copy or move constructors, we need to perform overload resolution.
7706 break;
7707
7708 case CXXSpecialMemberKind::CopyAssignment:
7709 case CXXSpecialMemberKind::MoveAssignment:
7710 if (!S.getLangOpts().CPlusPlus14)
7711 return false;
7712 // In C++1y, we need to perform overload resolution.
7713 Ctor = false;
7714 break;
7715
7716 case CXXSpecialMemberKind::Destructor:
7717 return ClassDecl->defaultedDestructorIsConstexpr();
7718
7719 case CXXSpecialMemberKind::Invalid:
7720 return false;
7721 }
7722
7723 // -- if the class is a non-empty union, or for each non-empty anonymous
7724 // union member of a non-union class, exactly one non-static data member
7725 // shall be initialized; [DR1359]
7726 //
7727 // If we squint, this is guaranteed, since exactly one non-static data member
7728 // will be initialized (if the constructor isn't deleted), we just don't know
7729 // which one.
7730 if (Ctor && ClassDecl->isUnion())
7731 return CSM == CXXSpecialMemberKind::DefaultConstructor
7732 ? ClassDecl->hasInClassInitializer() ||
7733 !ClassDecl->hasVariantMembers()
7734 : true;
7735
7736 // -- the class shall not have any virtual base classes;
7737 if (!S.getLangOpts().CPlusPlus26 && Ctor && ClassDecl->getNumVBases())
7738 return false;
7739
7740 // C++1y [class.copy]p26:
7741 // -- [the class] is a literal type, and
7742 if (!S.getLangOpts().CPlusPlus23 && !Ctor && !ClassDecl->isLiteral())
7743 return false;
7744
7745 // -- every constructor involved in initializing [...] base class
7746 // sub-objects shall be a constexpr constructor;
7747 // -- the assignment operator selected to copy/move each direct base
7748 // class is a constexpr function, and
7749 if (!S.getLangOpts().CPlusPlus23) {
7750 for (const auto &B : ClassDecl->bases()) {
7751 auto *BaseClassDecl = B.getType()->getAsCXXRecordDecl();
7752 if (!BaseClassDecl)
7753 continue;
7754 if (!specialMemberIsConstexpr(S, ClassDecl: BaseClassDecl, CSM, Quals: 0, ConstRHS: ConstArg,
7755 InheritedCtor, Inherited))
7756 return false;
7757 }
7758 }
7759
7760 // -- every constructor involved in initializing non-static data members
7761 // [...] shall be a constexpr constructor;
7762 // -- every non-static data member and base class sub-object shall be
7763 // initialized
7764 // -- for each non-static data member of X that is of class type (or array
7765 // thereof), the assignment operator selected to copy/move that member is
7766 // a constexpr function
7767 if (!S.getLangOpts().CPlusPlus23) {
7768 for (const auto *F : ClassDecl->fields()) {
7769 if (F->isInvalidDecl())
7770 continue;
7771 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
7772 F->hasInClassInitializer())
7773 continue;
7774 QualType BaseType = S.Context.getBaseElementType(QT: F->getType());
7775 if (const RecordType *RecordTy = BaseType->getAsCanonical<RecordType>()) {
7776 auto *FieldRecDecl =
7777 cast<CXXRecordDecl>(Val: RecordTy->getDecl())->getDefinitionOrSelf();
7778 if (!specialMemberIsConstexpr(S, ClassDecl: FieldRecDecl, CSM,
7779 Quals: BaseType.getCVRQualifiers(),
7780 ConstRHS: ConstArg && !F->isMutable()))
7781 return false;
7782 } else if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
7783 return false;
7784 }
7785 }
7786 }
7787
7788 // All OK, it's constexpr!
7789 return true;
7790}
7791
7792namespace {
7793/// RAII object to register a defaulted function as having its exception
7794/// specification computed.
7795struct ComputingExceptionSpec {
7796 Sema &S;
7797
7798 ComputingExceptionSpec(Sema &S, FunctionDecl *FD, SourceLocation Loc)
7799 : S(S) {
7800 Sema::CodeSynthesisContext Ctx;
7801 Ctx.Kind = Sema::CodeSynthesisContext::ExceptionSpecEvaluation;
7802 Ctx.PointOfInstantiation = Loc;
7803 Ctx.Entity = FD;
7804 S.pushCodeSynthesisContext(Ctx);
7805 }
7806 ~ComputingExceptionSpec() {
7807 S.popCodeSynthesisContext();
7808 }
7809};
7810}
7811
7812static Sema::ImplicitExceptionSpecification
7813ComputeDefaultedSpecialMemberExceptionSpec(Sema &S, SourceLocation Loc,
7814 CXXMethodDecl *MD,
7815 CXXSpecialMemberKind CSM,
7816 Sema::InheritedConstructorInfo *ICI);
7817
7818static Sema::ImplicitExceptionSpecification
7819ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
7820 FunctionDecl *FD,
7821 DefaultedComparisonKind DCK);
7822
7823static Sema::ImplicitExceptionSpecification
7824computeImplicitExceptionSpec(Sema &S, SourceLocation Loc, FunctionDecl *FD) {
7825 auto DFK = FD->getDefaultedFunctionKind();
7826 if (DFK.isSpecialMember())
7827 return ComputeDefaultedSpecialMemberExceptionSpec(
7828 S, Loc, MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(), ICI: nullptr);
7829 if (DFK.isComparison())
7830 return ComputeDefaultedComparisonExceptionSpec(S, Loc, FD,
7831 DCK: DFK.asComparison());
7832
7833 auto *CD = cast<CXXConstructorDecl>(Val: FD);
7834 assert(CD->getInheritedConstructor() &&
7835 "only defaulted functions and inherited constructors have implicit "
7836 "exception specs");
7837 Sema::InheritedConstructorInfo ICI(
7838 S, Loc, CD->getInheritedConstructor().getShadowDecl());
7839 return ComputeDefaultedSpecialMemberExceptionSpec(
7840 S, Loc, MD: CD, CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI);
7841}
7842
7843static FunctionProtoType::ExtProtoInfo getImplicitMethodEPI(Sema &S,
7844 CXXMethodDecl *MD) {
7845 FunctionProtoType::ExtProtoInfo EPI;
7846
7847 // Build an exception specification pointing back at this member.
7848 EPI.ExceptionSpec.Type = EST_Unevaluated;
7849 EPI.ExceptionSpec.SourceDecl = MD;
7850
7851 // Set the calling convention to the default for C++ instance methods.
7852 EPI.ExtInfo = EPI.ExtInfo.withCallingConv(
7853 cc: S.Context.getDefaultCallingConvention(/*IsVariadic=*/false,
7854 /*IsCXXMethod=*/true));
7855 return EPI;
7856}
7857
7858void Sema::EvaluateImplicitExceptionSpec(SourceLocation Loc, FunctionDecl *FD) {
7859 const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
7860 if (FPT->getExceptionSpecType() != EST_Unevaluated)
7861 return;
7862
7863 // Evaluate the exception specification.
7864 auto IES = computeImplicitExceptionSpec(S&: *this, Loc, FD);
7865 auto ESI = IES.getExceptionSpec();
7866
7867 // Update the type of the special member to use it.
7868 UpdateExceptionSpec(FD, ESI);
7869}
7870
7871void Sema::CheckExplicitlyDefaultedFunction(Scope *S, FunctionDecl *FD) {
7872 assert(FD->isExplicitlyDefaulted() && "not explicitly-defaulted");
7873
7874 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
7875 if (!DefKind) {
7876 assert(FD->getDeclContext()->isDependentContext());
7877 return;
7878 }
7879
7880 if (DefKind.isComparison()) {
7881 auto PT = FD->getParamDecl(i: 0)->getType();
7882 if (const CXXRecordDecl *RD =
7883 PT.getNonReferenceType()->getAsCXXRecordDecl()) {
7884 for (FieldDecl *Field : RD->fields()) {
7885 UnusedPrivateFields.remove(X: Field);
7886 }
7887 }
7888 }
7889
7890 if (DefKind.isSpecialMember()
7891 ? CheckExplicitlyDefaultedSpecialMember(MD: cast<CXXMethodDecl>(Val: FD),
7892 CSM: DefKind.asSpecialMember(),
7893 DefaultLoc: FD->getDefaultLoc())
7894 : CheckExplicitlyDefaultedComparison(S, MD: FD, DCK: DefKind.asComparison()))
7895 FD->setInvalidDecl();
7896}
7897
7898bool Sema::CheckExplicitlyDefaultedSpecialMember(CXXMethodDecl *MD,
7899 CXXSpecialMemberKind CSM,
7900 SourceLocation DefaultLoc) {
7901 CXXRecordDecl *RD = MD->getParent();
7902
7903 assert(MD->isExplicitlyDefaulted() && CSM != CXXSpecialMemberKind::Invalid &&
7904 "not an explicitly-defaulted special member");
7905
7906 // Defer all checking for special members of a dependent type.
7907 if (RD->isDependentType())
7908 return false;
7909
7910 // Whether this was the first-declared instance of the constructor.
7911 // This affects whether we implicitly add an exception spec and constexpr.
7912 bool First = MD == MD->getCanonicalDecl();
7913
7914 bool HadError = false;
7915
7916 // C++11 [dcl.fct.def.default]p1:
7917 // A function that is explicitly defaulted shall
7918 // -- be a special member function [...] (checked elsewhere),
7919 // -- have the same type (except for ref-qualifiers, and except that a
7920 // copy operation can take a non-const reference) as an implicit
7921 // declaration, and
7922 // -- not have default arguments.
7923 // C++2a changes the second bullet to instead delete the function if it's
7924 // defaulted on its first declaration, unless it's "an assignment operator,
7925 // and its return type differs or its parameter type is not a reference".
7926 bool DeleteOnTypeMismatch = getLangOpts().CPlusPlus20 && First;
7927 bool ShouldDeleteForTypeMismatch = false;
7928 unsigned ExpectedParams = 1;
7929 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
7930 CSM == CXXSpecialMemberKind::Destructor)
7931 ExpectedParams = 0;
7932 if (MD->getNumExplicitParams() != ExpectedParams) {
7933 // This checks for default arguments: a copy or move constructor with a
7934 // default argument is classified as a default constructor, and assignment
7935 // operations and destructors can't have default arguments.
7936 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_params)
7937 << CSM << MD->getSourceRange();
7938 HadError = true;
7939 } else if (MD->isVariadic()) {
7940 if (DeleteOnTypeMismatch)
7941 ShouldDeleteForTypeMismatch = true;
7942 else {
7943 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_variadic)
7944 << CSM << MD->getSourceRange();
7945 HadError = true;
7946 }
7947 }
7948
7949 const FunctionProtoType *Type = MD->getType()->castAs<FunctionProtoType>();
7950
7951 bool CanHaveConstParam = false;
7952 if (CSM == CXXSpecialMemberKind::CopyConstructor)
7953 CanHaveConstParam = RD->implicitCopyConstructorHasConstParam();
7954 else if (CSM == CXXSpecialMemberKind::CopyAssignment)
7955 CanHaveConstParam = RD->implicitCopyAssignmentHasConstParam();
7956
7957 QualType ReturnType = Context.VoidTy;
7958 if (CSM == CXXSpecialMemberKind::CopyAssignment ||
7959 CSM == CXXSpecialMemberKind::MoveAssignment) {
7960 // Check for return type matching.
7961 ReturnType = Type->getReturnType();
7962 QualType ThisType = MD->getFunctionObjectParameterType();
7963
7964 QualType DeclType =
7965 Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
7966 /*Qualifier=*/std::nullopt, TD: RD, /*OwnsTag=*/false);
7967 DeclType = Context.getAddrSpaceQualType(
7968 T: DeclType, AddressSpace: ThisType.getQualifiers().getAddressSpace());
7969 QualType ExpectedReturnType = Context.getLValueReferenceType(T: DeclType);
7970
7971 if (!Context.hasSameType(T1: ReturnType, T2: ExpectedReturnType)) {
7972 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_return_type)
7973 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7974 << ExpectedReturnType;
7975 HadError = true;
7976 }
7977
7978 // A defaulted special member cannot have cv-qualifiers.
7979 if (ThisType.isConstQualified() || ThisType.isVolatileQualified()) {
7980 if (DeleteOnTypeMismatch)
7981 ShouldDeleteForTypeMismatch = true;
7982 else {
7983 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_special_member_quals)
7984 << (CSM == CXXSpecialMemberKind::MoveAssignment)
7985 << getLangOpts().CPlusPlus14;
7986 HadError = true;
7987 }
7988 }
7989 // [C++23][dcl.fct.def.default]/p2.2
7990 // if F2 has an implicit object parameter of type “reference to C”,
7991 // F1 may be an explicit object member function whose explicit object
7992 // parameter is of (possibly different) type “reference to C”,
7993 // in which case the type of F1 would differ from the type of F2
7994 // in that the type of F1 has an additional parameter;
7995 QualType ExplicitObjectParameter = MD->isExplicitObjectMemberFunction()
7996 ? MD->getParamDecl(i: 0)->getType()
7997 : QualType();
7998 if (!ExplicitObjectParameter.isNull() &&
7999 (!ExplicitObjectParameter->isReferenceType() ||
8000 !Context.hasSameType(T1: ExplicitObjectParameter.getNonReferenceType(),
8001 T2: Context.getCanonicalTagType(TD: RD)))) {
8002 if (DeleteOnTypeMismatch)
8003 ShouldDeleteForTypeMismatch = true;
8004 else {
8005 Diag(Loc: MD->getLocation(),
8006 DiagID: diag::err_defaulted_special_member_explicit_object_mismatch)
8007 << (CSM == CXXSpecialMemberKind::MoveAssignment) << RD
8008 << MD->getSourceRange();
8009 HadError = true;
8010 }
8011 }
8012 }
8013
8014 // Check for parameter type matching.
8015 QualType ArgType =
8016 ExpectedParams
8017 ? Type->getParamType(i: MD->isExplicitObjectMemberFunction() ? 1 : 0)
8018 : QualType();
8019 bool HasConstParam = false;
8020 if (ExpectedParams && ArgType->isReferenceType()) {
8021 // Argument must be reference to possibly-const T.
8022 QualType ReferentType = ArgType->getPointeeType();
8023 HasConstParam = ReferentType.isConstQualified();
8024
8025 if (ReferentType.isVolatileQualified()) {
8026 if (DeleteOnTypeMismatch)
8027 ShouldDeleteForTypeMismatch = true;
8028 else {
8029 Diag(Loc: MD->getLocation(),
8030 DiagID: diag::err_defaulted_special_member_volatile_param)
8031 << CSM;
8032 HadError = true;
8033 }
8034 }
8035
8036 if (HasConstParam && !CanHaveConstParam) {
8037 if (DeleteOnTypeMismatch)
8038 ShouldDeleteForTypeMismatch = true;
8039 else if (CSM == CXXSpecialMemberKind::CopyConstructor ||
8040 CSM == CXXSpecialMemberKind::CopyAssignment) {
8041 Diag(Loc: MD->getLocation(),
8042 DiagID: diag::err_defaulted_special_member_copy_const_param)
8043 << (CSM == CXXSpecialMemberKind::CopyAssignment);
8044 // FIXME: Explain why this special member can't be const.
8045 HadError = true;
8046 } else {
8047 Diag(Loc: MD->getLocation(),
8048 DiagID: diag::err_defaulted_special_member_move_const_param)
8049 << (CSM == CXXSpecialMemberKind::MoveAssignment);
8050 HadError = true;
8051 }
8052 }
8053 } else if (ExpectedParams) {
8054 // A copy assignment operator can take its argument by value, but a
8055 // defaulted one cannot.
8056 assert(CSM == CXXSpecialMemberKind::CopyAssignment &&
8057 "unexpected non-ref argument");
8058 Diag(Loc: MD->getLocation(), DiagID: diag::err_defaulted_copy_assign_not_ref);
8059 HadError = true;
8060 }
8061
8062 // C++11 [dcl.fct.def.default]p2:
8063 // An explicitly-defaulted function may be declared constexpr only if it
8064 // would have been implicitly declared as constexpr,
8065 // Do not apply this rule to members of class templates, since core issue 1358
8066 // makes such functions always instantiate to constexpr functions. For
8067 // functions which cannot be constexpr (for non-constructors in C++11 and for
8068 // destructors in C++14 and C++17), this is checked elsewhere.
8069 //
8070 // FIXME: This should not apply if the member is deleted.
8071 bool Constexpr = defaultedSpecialMemberIsConstexpr(S&: *this, ClassDecl: RD, CSM,
8072 ConstArg: HasConstParam);
8073
8074 // C++14 [dcl.constexpr]p6 (CWG DR647/CWG DR1358):
8075 // If the instantiated template specialization of a constexpr function
8076 // template or member function of a class template would fail to satisfy
8077 // the requirements for a constexpr function or constexpr constructor, that
8078 // specialization is still a constexpr function or constexpr constructor,
8079 // even though a call to such a function cannot appear in a constant
8080 // expression.
8081 if (MD->isTemplateInstantiation() && MD->isConstexpr())
8082 Constexpr = true;
8083
8084 if ((getLangOpts().CPlusPlus20 ||
8085 (getLangOpts().CPlusPlus14 ? !isa<CXXDestructorDecl>(Val: MD)
8086 : isa<CXXConstructorDecl>(Val: MD))) &&
8087 MD->isConstexpr() && !Constexpr &&
8088 MD->getTemplatedKind() == FunctionDecl::TK_NonTemplate) {
8089 if (!MD->isConsteval() && RD->getNumVBases()) {
8090 Diag(Loc: MD->getBeginLoc(),
8091 DiagID: diag::err_incorrect_defaulted_constexpr_with_vb)
8092 << CSM;
8093 for (const auto &I : RD->vbases())
8094 Diag(Loc: I.getBeginLoc(), DiagID: diag::note_constexpr_virtual_base_here);
8095 } else {
8096 Diag(Loc: MD->getBeginLoc(), DiagID: diag::err_incorrect_defaulted_constexpr)
8097 << CSM << MD->isConsteval();
8098 }
8099 HadError = true;
8100 // FIXME: Explain why the special member can't be constexpr.
8101 }
8102 if (First) {
8103 // C++2a [dcl.fct.def.default]p3:
8104 // If a function is explicitly defaulted on its first declaration, it is
8105 // implicitly considered to be constexpr if the implicit declaration
8106 // would be.
8107 MD->setConstexprKind(Constexpr ? (MD->isConsteval()
8108 ? ConstexprSpecKind::Consteval
8109 : ConstexprSpecKind::Constexpr)
8110 : ConstexprSpecKind::Unspecified);
8111
8112 if (!Type->hasExceptionSpec()) {
8113 // C++2a [except.spec]p3:
8114 // If a declaration of a function does not have a noexcept-specifier
8115 // [and] is defaulted on its first declaration, [...] the exception
8116 // specification is as specified below
8117 FunctionProtoType::ExtProtoInfo EPI = Type->getExtProtoInfo();
8118 EPI.ExceptionSpec.Type = EST_Unevaluated;
8119 EPI.ExceptionSpec.SourceDecl = MD;
8120 MD->setType(
8121 Context.getFunctionType(ResultTy: ReturnType, Args: Type->getParamTypes(), EPI));
8122 }
8123 }
8124
8125 if (ShouldDeleteForTypeMismatch || ShouldDeleteSpecialMember(MD, CSM)) {
8126 if (First) {
8127 SetDeclDeleted(dcl: MD, DelLoc: MD->getLocation());
8128 if (!inTemplateInstantiation() && !HadError) {
8129 Diag(Loc: MD->getLocation(), DiagID: diag::warn_defaulted_method_deleted) << CSM;
8130 if (ShouldDeleteForTypeMismatch) {
8131 Diag(Loc: MD->getLocation(), DiagID: diag::note_deleted_type_mismatch) << CSM;
8132 } else if (ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr,
8133 /*Diagnose*/ true) &&
8134 DefaultLoc.isValid()) {
8135 Diag(Loc: DefaultLoc, DiagID: diag::note_replace_equals_default_to_delete)
8136 << FixItHint::CreateReplacement(RemoveRange: DefaultLoc, Code: "delete");
8137 }
8138 }
8139 if (ShouldDeleteForTypeMismatch && !HadError) {
8140 Diag(Loc: MD->getLocation(),
8141 DiagID: diag::warn_cxx17_compat_defaulted_method_type_mismatch)
8142 << CSM;
8143 }
8144 } else {
8145 // C++11 [dcl.fct.def.default]p4:
8146 // [For a] user-provided explicitly-defaulted function [...] if such a
8147 // function is implicitly defined as deleted, the program is ill-formed.
8148 Diag(Loc: MD->getLocation(), DiagID: diag::err_out_of_line_default_deletes) << CSM;
8149 assert(!ShouldDeleteForTypeMismatch && "deleted non-first decl");
8150 ShouldDeleteSpecialMember(MD, CSM, ICI: nullptr, /*Diagnose*/true);
8151 HadError = true;
8152 }
8153 }
8154
8155 return HadError;
8156}
8157
8158namespace {
8159/// Helper class for building and checking a defaulted comparison.
8160///
8161/// Defaulted functions are built in two phases:
8162///
8163/// * First, the set of operations that the function will perform are
8164/// identified, and some of them are checked. If any of the checked
8165/// operations is invalid in certain ways, the comparison function is
8166/// defined as deleted and no body is built.
8167/// * Then, if the function is not defined as deleted, the body is built.
8168///
8169/// This is accomplished by performing two visitation steps over the eventual
8170/// body of the function.
8171template<typename Derived, typename ResultList, typename Result,
8172 typename Subobject>
8173class DefaultedComparisonVisitor {
8174public:
8175 DefaultedComparisonVisitor(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8176 DefaultedComparisonKind DCK)
8177 : S(S), RD(RD), FD(FD), DCK(DCK) {
8178 if (auto *Info = FD->getDefaultedOrDeletedInfo()) {
8179 // FIXME: Change CreateOverloadedBinOp to take an ArrayRef instead of an
8180 // UnresolvedSet to avoid this copy.
8181 Fns.assign(I: Info->getUnqualifiedLookups().begin(),
8182 E: Info->getUnqualifiedLookups().end());
8183 }
8184 }
8185
8186 ResultList visit() {
8187 // The type of an lvalue naming a parameter of this function.
8188 QualType ParamLvalType =
8189 FD->getParamDecl(i: 0)->getType().getNonReferenceType();
8190
8191 ResultList Results;
8192
8193 switch (DCK) {
8194 case DefaultedComparisonKind::None:
8195 llvm_unreachable("not a defaulted comparison");
8196
8197 case DefaultedComparisonKind::Equal:
8198 case DefaultedComparisonKind::ThreeWay:
8199 getDerived().visitSubobjects(Results, RD, ParamLvalType.getQualifiers());
8200 return Results;
8201
8202 case DefaultedComparisonKind::NotEqual:
8203 case DefaultedComparisonKind::Relational:
8204 Results.add(getDerived().visitExpandedSubobject(
8205 ParamLvalType, getDerived().getCompleteObject()));
8206 return Results;
8207 }
8208 llvm_unreachable("");
8209 }
8210
8211protected:
8212 Derived &getDerived() { return static_cast<Derived&>(*this); }
8213
8214 /// Visit the expanded list of subobjects of the given type, as specified in
8215 /// C++2a [class.compare.default].
8216 ///
8217 /// \return \c true if the ResultList object said we're done, \c false if not.
8218 bool visitSubobjects(ResultList &Results, CXXRecordDecl *Record,
8219 Qualifiers Quals) {
8220 // C++2a [class.compare.default]p4:
8221 // The direct base class subobjects of C
8222 for (CXXBaseSpecifier &Base : Record->bases())
8223 if (Results.add(getDerived().visitSubobject(
8224 S.Context.getQualifiedType(T: Base.getType(), Qs: Quals),
8225 getDerived().getBase(&Base))))
8226 return true;
8227
8228 // followed by the non-static data members of C
8229 for (FieldDecl *Field : Record->fields()) {
8230 // C++23 [class.bit]p2:
8231 // Unnamed bit-fields are not members ...
8232 if (Field->isUnnamedBitField())
8233 continue;
8234 if (Field->isInvalidDecl())
8235 continue;
8236 // Recursively expand anonymous structs.
8237 if (Field->isAnonymousStructOrUnion()) {
8238 if (visitSubobjects(Results, Record: Field->getType()->getAsCXXRecordDecl(),
8239 Quals))
8240 return true;
8241 continue;
8242 }
8243
8244 // Figure out the type of an lvalue denoting this field.
8245 Qualifiers FieldQuals = Quals;
8246 if (Field->isMutable())
8247 FieldQuals.removeConst();
8248 QualType FieldType =
8249 S.Context.getQualifiedType(T: Field->getType(), Qs: FieldQuals);
8250
8251 if (Results.add(getDerived().visitSubobject(
8252 FieldType, getDerived().getField(Field))))
8253 return true;
8254 }
8255
8256 // form a list of subobjects.
8257 return false;
8258 }
8259
8260 Result visitSubobject(QualType Type, Subobject Subobj) {
8261 // In that list, any subobject of array type is recursively expanded
8262 const ArrayType *AT = S.Context.getAsArrayType(T: Type);
8263 if (auto *CAT = dyn_cast_or_null<ConstantArrayType>(Val: AT))
8264 return getDerived().visitSubobjectArray(CAT->getElementType(),
8265 CAT->getSize(), Subobj);
8266 return getDerived().visitExpandedSubobject(Type, Subobj);
8267 }
8268
8269 Result visitSubobjectArray(QualType Type, const llvm::APInt &Size,
8270 Subobject Subobj) {
8271 return getDerived().visitSubobject(Type, Subobj);
8272 }
8273
8274protected:
8275 Sema &S;
8276 CXXRecordDecl *RD;
8277 FunctionDecl *FD;
8278 DefaultedComparisonKind DCK;
8279 UnresolvedSet<16> Fns;
8280};
8281
8282/// Information about a defaulted comparison, as determined by
8283/// DefaultedComparisonAnalyzer.
8284struct DefaultedComparisonInfo {
8285 bool Deleted = false;
8286 bool Constexpr = true;
8287 ComparisonCategoryType Category = ComparisonCategoryType::StrongOrdering;
8288
8289 static DefaultedComparisonInfo deleted() {
8290 DefaultedComparisonInfo Deleted;
8291 Deleted.Deleted = true;
8292 return Deleted;
8293 }
8294
8295 bool add(const DefaultedComparisonInfo &R) {
8296 Deleted |= R.Deleted;
8297 Constexpr &= R.Constexpr;
8298 Category = commonComparisonType(A: Category, B: R.Category);
8299 return Deleted;
8300 }
8301};
8302
8303/// An element in the expanded list of subobjects of a defaulted comparison, as
8304/// specified in C++2a [class.compare.default]p4.
8305struct DefaultedComparisonSubobject {
8306 enum { CompleteObject, Member, Base } Kind;
8307 NamedDecl *Decl;
8308 SourceLocation Loc;
8309};
8310
8311/// A visitor over the notional body of a defaulted comparison that determines
8312/// whether that body would be deleted or constexpr.
8313class DefaultedComparisonAnalyzer
8314 : public DefaultedComparisonVisitor<DefaultedComparisonAnalyzer,
8315 DefaultedComparisonInfo,
8316 DefaultedComparisonInfo,
8317 DefaultedComparisonSubobject> {
8318public:
8319 enum DiagnosticKind { NoDiagnostics, ExplainDeleted, ExplainConstexpr };
8320
8321private:
8322 DiagnosticKind Diagnose;
8323
8324public:
8325 using Base = DefaultedComparisonVisitor;
8326 using Result = DefaultedComparisonInfo;
8327 using Subobject = DefaultedComparisonSubobject;
8328
8329 friend Base;
8330
8331 DefaultedComparisonAnalyzer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8332 DefaultedComparisonKind DCK,
8333 DiagnosticKind Diagnose = NoDiagnostics)
8334 : Base(S, RD, FD, DCK), Diagnose(Diagnose) {}
8335
8336 Result visit() {
8337 if ((DCK == DefaultedComparisonKind::Equal ||
8338 DCK == DefaultedComparisonKind::ThreeWay) &&
8339 RD->hasVariantMembers()) {
8340 // C++2a [class.compare.default]p2 [P2002R0]:
8341 // A defaulted comparison operator function for class C is defined as
8342 // deleted if [...] C has variant members.
8343 if (Diagnose == ExplainDeleted) {
8344 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_defaulted_comparison_union)
8345 << FD << RD->isUnion() << RD;
8346 }
8347 return Result::deleted();
8348 }
8349
8350 return Base::visit();
8351 }
8352
8353private:
8354 Subobject getCompleteObject() {
8355 return Subobject{.Kind: Subobject::CompleteObject, .Decl: RD, .Loc: FD->getLocation()};
8356 }
8357
8358 Subobject getBase(CXXBaseSpecifier *Base) {
8359 return Subobject{.Kind: Subobject::Base, .Decl: Base->getType()->getAsCXXRecordDecl(),
8360 .Loc: Base->getBaseTypeLoc()};
8361 }
8362
8363 Subobject getField(FieldDecl *Field) {
8364 return Subobject{.Kind: Subobject::Member, .Decl: Field, .Loc: Field->getLocation()};
8365 }
8366
8367 Result visitExpandedSubobject(QualType Type, Subobject Subobj) {
8368 // C++2a [class.compare.default]p2 [P2002R0]:
8369 // A defaulted <=> or == operator function for class C is defined as
8370 // deleted if any non-static data member of C is of reference type
8371 if (Type->isReferenceType()) {
8372 if (Diagnose == ExplainDeleted) {
8373 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_reference_member)
8374 << FD << RD;
8375 }
8376 return Result::deleted();
8377 }
8378
8379 // [...] Let xi be an lvalue denoting the ith element [...]
8380 OpaqueValueExpr Xi(FD->getLocation(), Type, VK_LValue);
8381 Expr *Args[] = {&Xi, &Xi};
8382
8383 // All operators start by trying to apply that same operator recursively.
8384 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8385 assert(OO != OO_None && "not an overloaded operator!");
8386 return visitBinaryOperator(OO, Args, Subobj);
8387 }
8388
8389 Result
8390 visitBinaryOperator(OverloadedOperatorKind OO, ArrayRef<Expr *> Args,
8391 Subobject Subobj,
8392 OverloadCandidateSet *SpaceshipCandidates = nullptr) {
8393 // Note that there is no need to consider rewritten candidates here if
8394 // we've already found there is no viable 'operator<=>' candidate (and are
8395 // considering synthesizing a '<=>' from '==' and '<').
8396 OverloadCandidateSet CandidateSet(
8397 FD->getLocation(), OverloadCandidateSet::CSK_Operator,
8398 OverloadCandidateSet::OperatorRewriteInfo(
8399 OO, FD->getLocation(),
8400 /*AllowRewrittenCandidates=*/!SpaceshipCandidates));
8401
8402 /// C++2a [class.compare.default]p1 [P2002R0]:
8403 /// [...] the defaulted function itself is never a candidate for overload
8404 /// resolution [...]
8405 CandidateSet.exclude(F: FD);
8406
8407 if (Args[0]->getType()->isOverloadableType())
8408 S.LookupOverloadedBinOp(CandidateSet, Op: OO, Fns, Args);
8409 else
8410 // FIXME: We determine whether this is a valid expression by checking to
8411 // see if there's a viable builtin operator candidate for it. That isn't
8412 // really what the rules ask us to do, but should give the right results.
8413 S.AddBuiltinOperatorCandidates(Op: OO, OpLoc: FD->getLocation(), Args, CandidateSet);
8414
8415 Result R;
8416
8417 OverloadCandidateSet::iterator Best;
8418 switch (CandidateSet.BestViableFunction(S, Loc: FD->getLocation(), Best)) {
8419 case OR_Success: {
8420 // C++2a [class.compare.secondary]p2 [P2002R0]:
8421 // The operator function [...] is defined as deleted if [...] the
8422 // candidate selected by overload resolution is not a rewritten
8423 // candidate.
8424 if ((DCK == DefaultedComparisonKind::NotEqual ||
8425 DCK == DefaultedComparisonKind::Relational) &&
8426 !Best->RewriteKind) {
8427 if (Diagnose == ExplainDeleted) {
8428 if (Best->Function) {
8429 S.Diag(Loc: Best->Function->getLocation(),
8430 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8431 << FD;
8432 } else {
8433 assert(Best->Conversions.size() == 2 &&
8434 Best->Conversions[0].isUserDefined() &&
8435 "non-user-defined conversion from class to built-in "
8436 "comparison");
8437 S.Diag(Loc: Best->Conversions[0]
8438 .UserDefined.FoundConversionFunction.getDecl()
8439 ->getLocation(),
8440 DiagID: diag::note_defaulted_comparison_not_rewritten_conversion)
8441 << FD;
8442 }
8443 }
8444 return Result::deleted();
8445 }
8446
8447 // Throughout C++2a [class.compare]: if overload resolution does not
8448 // result in a usable function, the candidate function is defined as
8449 // deleted. This requires that we selected an accessible function.
8450 //
8451 // Note that this only considers the access of the function when named
8452 // within the type of the subobject, and not the access path for any
8453 // derived-to-base conversion.
8454 CXXRecordDecl *ArgClass = Args[0]->getType()->getAsCXXRecordDecl();
8455 if (ArgClass && Best->FoundDecl.getDecl() &&
8456 Best->FoundDecl.getDecl()->isCXXClassMember()) {
8457 QualType ObjectType = Subobj.Kind == Subobject::Member
8458 ? Args[0]->getType()
8459 : S.Context.getCanonicalTagType(TD: RD);
8460 if (!S.isMemberAccessibleForDeletion(
8461 NamingClass: ArgClass, Found: Best->FoundDecl, ObjectType, Loc: Subobj.Loc,
8462 Diag: Diagnose == ExplainDeleted
8463 ? S.PDiag(DiagID: diag::note_defaulted_comparison_inaccessible)
8464 << FD << Subobj.Kind << Subobj.Decl
8465 : S.PDiag()))
8466 return Result::deleted();
8467 }
8468
8469 bool NeedsDeducing =
8470 OO == OO_Spaceship && FD->getReturnType()->isUndeducedAutoType();
8471
8472 if (FunctionDecl *BestFD = Best->Function) {
8473 // C++2a [class.compare.default]p3 [P2002R0]:
8474 // A defaulted comparison function is constexpr-compatible if
8475 // [...] no overlod resolution performed [...] results in a
8476 // non-constexpr function.
8477 assert(!BestFD->isDeleted() && "wrong overload resolution result");
8478 // If it's not constexpr, explain why not.
8479 if (Diagnose == ExplainConstexpr && !BestFD->isConstexpr()) {
8480 if (Subobj.Kind != Subobject::CompleteObject)
8481 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_not_constexpr)
8482 << Subobj.Kind << Subobj.Decl;
8483 S.Diag(Loc: BestFD->getLocation(),
8484 DiagID: diag::note_defaulted_comparison_not_constexpr_here);
8485 // Bail out after explaining; we don't want any more notes.
8486 return Result::deleted();
8487 }
8488 R.Constexpr &= BestFD->isConstexpr();
8489
8490 if (NeedsDeducing) {
8491 // If any callee has an undeduced return type, deduce it now.
8492 // FIXME: It's not clear how a failure here should be handled. For
8493 // now, we produce an eager diagnostic, because that is forward
8494 // compatible with most (all?) other reasonable options.
8495 if (BestFD->getReturnType()->isUndeducedType() &&
8496 S.DeduceReturnType(FD: BestFD, Loc: FD->getLocation(),
8497 /*Diagnose=*/false)) {
8498 // Don't produce a duplicate error when asked to explain why the
8499 // comparison is deleted: we diagnosed that when initially checking
8500 // the defaulted operator.
8501 if (Diagnose == NoDiagnostics) {
8502 S.Diag(
8503 Loc: FD->getLocation(),
8504 DiagID: diag::err_defaulted_comparison_cannot_deduce_undeduced_auto)
8505 << Subobj.Kind << Subobj.Decl;
8506 S.Diag(
8507 Loc: Subobj.Loc,
8508 DiagID: diag::note_defaulted_comparison_cannot_deduce_undeduced_auto)
8509 << Subobj.Kind << Subobj.Decl;
8510 S.Diag(Loc: BestFD->getLocation(),
8511 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8512 << Subobj.Kind << Subobj.Decl;
8513 }
8514 return Result::deleted();
8515 }
8516 auto *Info = S.Context.CompCategories.lookupInfoForType(
8517 Ty: BestFD->getCallResultType());
8518 if (!Info) {
8519 if (Diagnose == ExplainDeleted) {
8520 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_cannot_deduce)
8521 << Subobj.Kind << Subobj.Decl
8522 << BestFD->getCallResultType().withoutLocalFastQualifiers();
8523 S.Diag(Loc: BestFD->getLocation(),
8524 DiagID: diag::note_defaulted_comparison_cannot_deduce_callee)
8525 << Subobj.Kind << Subobj.Decl;
8526 }
8527 return Result::deleted();
8528 }
8529 R.Category = Info->Kind;
8530 }
8531 } else {
8532 QualType T = Best->BuiltinParamTypes[0];
8533 assert(T == Best->BuiltinParamTypes[1] &&
8534 "builtin comparison for different types?");
8535 assert(Best->BuiltinParamTypes[2].isNull() &&
8536 "invalid builtin comparison");
8537
8538 // FIXME: If the type we deduced is a vector type, we mark the
8539 // comparison as deleted because we don't yet support this.
8540 if (isa<VectorType>(Val: T)) {
8541 if (Diagnose == ExplainDeleted) {
8542 S.Diag(Loc: FD->getLocation(),
8543 DiagID: diag::note_defaulted_comparison_vector_types)
8544 << FD;
8545 S.Diag(Loc: Subobj.Decl->getLocation(), DiagID: diag::note_declared_at);
8546 }
8547 return Result::deleted();
8548 }
8549
8550 if (NeedsDeducing) {
8551 std::optional<ComparisonCategoryType> Cat =
8552 getComparisonCategoryForBuiltinCmp(T);
8553 assert(Cat && "no category for builtin comparison?");
8554 R.Category = *Cat;
8555 }
8556 }
8557
8558 // Note that we might be rewriting to a different operator. That call is
8559 // not considered until we come to actually build the comparison function.
8560 break;
8561 }
8562
8563 case OR_Ambiguous:
8564 if (Diagnose == ExplainDeleted) {
8565 unsigned Kind = 0;
8566 if (FD->getOverloadedOperator() == OO_Spaceship && OO != OO_Spaceship)
8567 Kind = OO == OO_EqualEqual ? 1 : 2;
8568 CandidateSet.NoteCandidates(
8569 PA: PartialDiagnosticAt(
8570 Subobj.Loc, S.PDiag(DiagID: diag::note_defaulted_comparison_ambiguous)
8571 << FD << Kind << Subobj.Kind << Subobj.Decl),
8572 S, OCD: OCD_AmbiguousCandidates, Args);
8573 }
8574 R = Result::deleted();
8575 break;
8576
8577 case OR_Deleted:
8578 if (Diagnose == ExplainDeleted) {
8579 if ((DCK == DefaultedComparisonKind::NotEqual ||
8580 DCK == DefaultedComparisonKind::Relational) &&
8581 !Best->RewriteKind) {
8582 S.Diag(Loc: Best->Function->getLocation(),
8583 DiagID: diag::note_defaulted_comparison_not_rewritten_callee)
8584 << FD;
8585 } else {
8586 S.Diag(Loc: Subobj.Loc,
8587 DiagID: diag::note_defaulted_comparison_calls_deleted)
8588 << FD << Subobj.Kind << Subobj.Decl;
8589 S.NoteDeletedFunction(FD: Best->Function);
8590 }
8591 }
8592 R = Result::deleted();
8593 break;
8594
8595 case OR_No_Viable_Function:
8596 // If there's no usable candidate, we're done unless we can rewrite a
8597 // '<=>' in terms of '==' and '<'.
8598 if (OO == OO_Spaceship &&
8599 S.Context.CompCategories.lookupInfoForType(Ty: FD->getReturnType())) {
8600 // For any kind of comparison category return type, we need a usable
8601 // '==' and a usable '<'.
8602 if (!R.add(R: visitBinaryOperator(OO: OO_EqualEqual, Args, Subobj,
8603 SpaceshipCandidates: &CandidateSet)))
8604 R.add(R: visitBinaryOperator(OO: OO_Less, Args, Subobj, SpaceshipCandidates: &CandidateSet));
8605 break;
8606 }
8607
8608 if (Diagnose == ExplainDeleted) {
8609 S.Diag(Loc: Subobj.Loc, DiagID: diag::note_defaulted_comparison_no_viable_function)
8610 << FD << (OO == OO_EqualEqual || OO == OO_ExclaimEqual)
8611 << Subobj.Kind << Subobj.Decl;
8612
8613 // For a three-way comparison, list both the candidates for the
8614 // original operator and the candidates for the synthesized operator.
8615 if (SpaceshipCandidates) {
8616 SpaceshipCandidates->NoteCandidates(
8617 S, Args,
8618 Cands: SpaceshipCandidates->CompleteCandidates(S, OCD: OCD_AllCandidates,
8619 Args, OpLoc: FD->getLocation()));
8620 S.Diag(Loc: Subobj.Loc,
8621 DiagID: diag::note_defaulted_comparison_no_viable_function_synthesized)
8622 << (OO == OO_EqualEqual ? 0 : 1);
8623 }
8624
8625 CandidateSet.NoteCandidates(
8626 S, Args,
8627 Cands: CandidateSet.CompleteCandidates(S, OCD: OCD_AllCandidates, Args,
8628 OpLoc: FD->getLocation()));
8629 }
8630 R = Result::deleted();
8631 break;
8632 }
8633
8634 return R;
8635 }
8636};
8637
8638/// A list of statements.
8639struct StmtListResult {
8640 bool IsInvalid = false;
8641 llvm::SmallVector<Stmt*, 16> Stmts;
8642
8643 bool add(const StmtResult &S) {
8644 IsInvalid |= S.isInvalid();
8645 if (IsInvalid)
8646 return true;
8647 Stmts.push_back(Elt: S.get());
8648 return false;
8649 }
8650};
8651
8652/// A visitor over the notional body of a defaulted comparison that synthesizes
8653/// the actual body.
8654class DefaultedComparisonSynthesizer
8655 : public DefaultedComparisonVisitor<DefaultedComparisonSynthesizer,
8656 StmtListResult, StmtResult,
8657 std::pair<ExprResult, ExprResult>> {
8658 SourceLocation Loc;
8659 unsigned ArrayDepth = 0;
8660
8661public:
8662 using Base = DefaultedComparisonVisitor;
8663 using ExprPair = std::pair<ExprResult, ExprResult>;
8664
8665 friend Base;
8666
8667 DefaultedComparisonSynthesizer(Sema &S, CXXRecordDecl *RD, FunctionDecl *FD,
8668 DefaultedComparisonKind DCK,
8669 SourceLocation BodyLoc)
8670 : Base(S, RD, FD, DCK), Loc(BodyLoc) {}
8671
8672 /// Build a suitable function body for this defaulted comparison operator.
8673 StmtResult build() {
8674 Sema::CompoundScopeRAII CompoundScope(S);
8675
8676 StmtListResult Stmts = visit();
8677 if (Stmts.IsInvalid)
8678 return StmtError();
8679
8680 ExprResult RetVal;
8681 switch (DCK) {
8682 case DefaultedComparisonKind::None:
8683 llvm_unreachable("not a defaulted comparison");
8684
8685 case DefaultedComparisonKind::Equal: {
8686 // C++2a [class.eq]p3:
8687 // [...] compar[e] the corresponding elements [...] until the first
8688 // index i where xi == yi yields [...] false. If no such index exists,
8689 // V is true. Otherwise, V is false.
8690 //
8691 // Join the comparisons with '&&'s and return the result. Use a right
8692 // fold (traversing the conditions right-to-left), because that
8693 // short-circuits more naturally.
8694 auto OldStmts = std::move(Stmts.Stmts);
8695 Stmts.Stmts.clear();
8696 ExprResult CmpSoFar;
8697 // Finish a particular comparison chain.
8698 auto FinishCmp = [&] {
8699 if (Expr *Prior = CmpSoFar.get()) {
8700 // Convert the last expression to 'return ...;'
8701 if (RetVal.isUnset() && Stmts.Stmts.empty())
8702 RetVal = CmpSoFar;
8703 // Convert any prior comparison to 'if (!(...)) return false;'
8704 else if (Stmts.add(S: buildIfNotCondReturnFalse(Cond: Prior)))
8705 return true;
8706 CmpSoFar = ExprResult();
8707 }
8708 return false;
8709 };
8710 for (Stmt *EAsStmt : llvm::reverse(C&: OldStmts)) {
8711 Expr *E = dyn_cast<Expr>(Val: EAsStmt);
8712 if (!E) {
8713 // Found an array comparison.
8714 if (FinishCmp() || Stmts.add(S: EAsStmt))
8715 return StmtError();
8716 continue;
8717 }
8718
8719 if (CmpSoFar.isUnset()) {
8720 CmpSoFar = E;
8721 continue;
8722 }
8723 CmpSoFar = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_LAnd, LHSExpr: E, RHSExpr: CmpSoFar.get());
8724 if (CmpSoFar.isInvalid())
8725 return StmtError();
8726 }
8727 if (FinishCmp())
8728 return StmtError();
8729 std::reverse(first: Stmts.Stmts.begin(), last: Stmts.Stmts.end());
8730 // If no such index exists, V is true.
8731 if (RetVal.isUnset())
8732 RetVal = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_true);
8733 break;
8734 }
8735
8736 case DefaultedComparisonKind::ThreeWay: {
8737 // Per C++2a [class.spaceship]p3, as a fallback add:
8738 // return static_cast<R>(std::strong_ordering::equal);
8739 QualType StrongOrdering = S.CheckComparisonCategoryType(
8740 Kind: ComparisonCategoryType::StrongOrdering, Loc,
8741 Usage: Sema::ComparisonCategoryUsage::DefaultedOperator);
8742 if (StrongOrdering.isNull())
8743 return StmtError();
8744 VarDecl *EqualVD = S.Context.CompCategories.getInfoForType(Ty: StrongOrdering)
8745 .getValueInfo(ValueKind: ComparisonCategoryResult::Equal)
8746 ->VD;
8747 RetVal = getDecl(VD: EqualVD);
8748 if (RetVal.isInvalid())
8749 return StmtError();
8750 RetVal = buildStaticCastToR(E: RetVal.get());
8751 break;
8752 }
8753
8754 case DefaultedComparisonKind::NotEqual:
8755 case DefaultedComparisonKind::Relational:
8756 RetVal = cast<Expr>(Val: Stmts.Stmts.pop_back_val());
8757 break;
8758 }
8759
8760 // Build the final return statement.
8761 if (RetVal.isInvalid())
8762 return StmtError();
8763 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: RetVal.get());
8764 if (ReturnStmt.isInvalid())
8765 return StmtError();
8766 Stmts.Stmts.push_back(Elt: ReturnStmt.get());
8767
8768 return S.ActOnCompoundStmt(L: Loc, R: Loc, Elts: Stmts.Stmts, /*IsStmtExpr=*/isStmtExpr: false);
8769 }
8770
8771private:
8772 ExprResult getDecl(ValueDecl *VD) {
8773 return S.BuildDeclarationNameExpr(
8774 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(VD->getDeclName(), Loc), D: VD);
8775 }
8776
8777 ExprResult getParam(unsigned I) {
8778 ParmVarDecl *PD = FD->getParamDecl(i: I);
8779 return getDecl(VD: PD);
8780 }
8781
8782 ExprPair getCompleteObject() {
8783 unsigned Param = 0;
8784 ExprResult LHS;
8785 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FD);
8786 MD && MD->isImplicitObjectMemberFunction()) {
8787 // LHS is '*this'.
8788 LHS = S.ActOnCXXThis(Loc);
8789 if (!LHS.isInvalid())
8790 LHS = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: LHS.get());
8791 } else {
8792 LHS = getParam(I: Param++);
8793 }
8794 ExprResult RHS = getParam(I: Param++);
8795 assert(Param == FD->getNumParams());
8796 return {LHS, RHS};
8797 }
8798
8799 ExprPair getBase(CXXBaseSpecifier *Base) {
8800 ExprPair Obj = getCompleteObject();
8801 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8802 return {ExprError(), ExprError()};
8803 CXXCastPath Path = {Base};
8804 const auto CastToBase = [&](Expr *E) {
8805 QualType ToType = S.Context.getQualifiedType(
8806 T: Base->getType(), Qs: E->getType().getQualifiers());
8807 return S.ImpCastExprToType(E, Type: ToType, CK: CK_DerivedToBase, VK: VK_LValue, BasePath: &Path);
8808 };
8809 return {CastToBase(Obj.first.get()), CastToBase(Obj.second.get())};
8810 }
8811
8812 ExprPair getField(FieldDecl *Field) {
8813 ExprPair Obj = getCompleteObject();
8814 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8815 return {ExprError(), ExprError()};
8816
8817 DeclAccessPair Found = DeclAccessPair::make(D: Field, AS: Field->getAccess());
8818 DeclarationNameInfo NameInfo(Field->getDeclName(), Loc);
8819 return {S.BuildFieldReferenceExpr(BaseExpr: Obj.first.get(), /*IsArrow=*/false, OpLoc: Loc,
8820 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo),
8821 S.BuildFieldReferenceExpr(BaseExpr: Obj.second.get(), /*IsArrow=*/false, OpLoc: Loc,
8822 SS: CXXScopeSpec(), Field, FoundDecl: Found, MemberNameInfo: NameInfo)};
8823 }
8824
8825 // FIXME: When expanding a subobject, register a note in the code synthesis
8826 // stack to say which subobject we're comparing.
8827
8828 StmtResult buildIfNotCondReturnFalse(ExprResult Cond) {
8829 if (Cond.isInvalid())
8830 return StmtError();
8831
8832 ExprResult NotCond = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_LNot, InputExpr: Cond.get());
8833 if (NotCond.isInvalid())
8834 return StmtError();
8835
8836 ExprResult False = S.ActOnCXXBoolLiteral(OpLoc: Loc, Kind: tok::kw_false);
8837 assert(!False.isInvalid() && "should never fail");
8838 StmtResult ReturnFalse = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: False.get());
8839 if (ReturnFalse.isInvalid())
8840 return StmtError();
8841
8842 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt: nullptr,
8843 Cond: S.ActOnCondition(S: nullptr, Loc, SubExpr: NotCond.get(),
8844 CK: Sema::ConditionKind::Boolean),
8845 RParenLoc: Loc, ThenVal: ReturnFalse.get(), ElseLoc: SourceLocation(), ElseVal: nullptr);
8846 }
8847
8848 StmtResult visitSubobjectArray(QualType Type, llvm::APInt Size,
8849 ExprPair Subobj) {
8850 QualType SizeType = S.Context.getSizeType();
8851 Size = Size.zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
8852
8853 // Build 'size_t i$n = 0'.
8854 IdentifierInfo *IterationVarName = nullptr;
8855 {
8856 SmallString<8> Str;
8857 llvm::raw_svector_ostream OS(Str);
8858 OS << "i" << ArrayDepth;
8859 IterationVarName = &S.Context.Idents.get(Name: OS.str());
8860 }
8861 VarDecl *IterationVar = VarDecl::Create(
8862 C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: IterationVarName, T: SizeType,
8863 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc), S: SC_None);
8864 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
8865 IterationVar->setInit(
8866 IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
8867 Stmt *Init = new (S.Context) DeclStmt(DeclGroupRef(IterationVar), Loc, Loc);
8868
8869 auto IterRef = [&] {
8870 ExprResult Ref = S.BuildDeclarationNameExpr(
8871 SS: CXXScopeSpec(), NameInfo: DeclarationNameInfo(IterationVarName, Loc),
8872 D: IterationVar);
8873 assert(!Ref.isInvalid() && "can't reference our own variable?");
8874 return Ref.get();
8875 };
8876
8877 // Build 'i$n != Size'.
8878 ExprResult Cond = S.CreateBuiltinBinOp(
8879 OpLoc: Loc, Opc: BO_NE, LHSExpr: IterRef(),
8880 RHSExpr: IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc));
8881 assert(!Cond.isInvalid() && "should never fail");
8882
8883 // Build '++i$n'.
8884 ExprResult Inc = S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_PreInc, InputExpr: IterRef());
8885 assert(!Inc.isInvalid() && "should never fail");
8886
8887 // Build 'a[i$n]' and 'b[i$n]'.
8888 auto Index = [&](ExprResult E) {
8889 if (E.isInvalid())
8890 return ExprError();
8891 return S.CreateBuiltinArraySubscriptExpr(Base: E.get(), LLoc: Loc, Idx: IterRef(), RLoc: Loc);
8892 };
8893 Subobj.first = Index(Subobj.first);
8894 Subobj.second = Index(Subobj.second);
8895
8896 // Compare the array elements.
8897 ++ArrayDepth;
8898 StmtResult Substmt = visitSubobject(Type, Subobj);
8899 --ArrayDepth;
8900
8901 if (Substmt.isInvalid())
8902 return StmtError();
8903
8904 // For the inner level of an 'operator==', build 'if (!cmp) return false;'.
8905 // For outer levels or for an 'operator<=>' we already have a suitable
8906 // statement that returns as necessary.
8907 if (Expr *ElemCmp = dyn_cast<Expr>(Val: Substmt.get())) {
8908 assert(DCK == DefaultedComparisonKind::Equal &&
8909 "should have non-expression statement");
8910 Substmt = buildIfNotCondReturnFalse(Cond: ElemCmp);
8911 if (Substmt.isInvalid())
8912 return StmtError();
8913 }
8914
8915 // Build 'for (...) ...'
8916 return S.ActOnForStmt(ForLoc: Loc, LParenLoc: Loc, First: Init,
8917 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Cond.get(),
8918 CK: Sema::ConditionKind::Boolean),
8919 Third: S.MakeFullDiscardedValueExpr(Arg: Inc.get()), RParenLoc: Loc,
8920 Body: Substmt.get());
8921 }
8922
8923 StmtResult visitExpandedSubobject(QualType Type, ExprPair Obj) {
8924 if (Obj.first.isInvalid() || Obj.second.isInvalid())
8925 return StmtError();
8926
8927 OverloadedOperatorKind OO = FD->getOverloadedOperator();
8928 BinaryOperatorKind Opc = BinaryOperator::getOverloadedOpcode(OO);
8929 ExprResult Op;
8930 if (Type->isOverloadableType())
8931 Op = S.CreateOverloadedBinOp(OpLoc: Loc, Opc, Fns, LHS: Obj.first.get(),
8932 RHS: Obj.second.get(), /*PerformADL=*/RequiresADL: true,
8933 /*AllowRewrittenCandidates=*/true, DefaultedFn: FD);
8934 else
8935 Op = S.CreateBuiltinBinOp(OpLoc: Loc, Opc, LHSExpr: Obj.first.get(), RHSExpr: Obj.second.get());
8936 if (Op.isInvalid())
8937 return StmtError();
8938
8939 switch (DCK) {
8940 case DefaultedComparisonKind::None:
8941 llvm_unreachable("not a defaulted comparison");
8942
8943 case DefaultedComparisonKind::Equal:
8944 // Per C++2a [class.eq]p2, each comparison is individually contextually
8945 // converted to bool.
8946 Op = S.PerformContextuallyConvertToBool(From: Op.get());
8947 if (Op.isInvalid())
8948 return StmtError();
8949 return Op.get();
8950
8951 case DefaultedComparisonKind::ThreeWay: {
8952 // Per C++2a [class.spaceship]p3, form:
8953 // if (R cmp = static_cast<R>(op); cmp != 0)
8954 // return cmp;
8955 QualType R = FD->getReturnType();
8956 Op = buildStaticCastToR(E: Op.get());
8957 if (Op.isInvalid())
8958 return StmtError();
8959
8960 // R cmp = ...;
8961 IdentifierInfo *Name = &S.Context.Idents.get(Name: "cmp");
8962 VarDecl *VD =
8963 VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc, Id: Name, T: R,
8964 TInfo: S.Context.getTrivialTypeSourceInfo(T: R, Loc), S: SC_None);
8965 S.AddInitializerToDecl(dcl: VD, init: Op.get(), /*DirectInit=*/false);
8966 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(VD), Loc, Loc);
8967
8968 // cmp != 0
8969 ExprResult VDRef = getDecl(VD);
8970 if (VDRef.isInvalid())
8971 return StmtError();
8972 llvm::APInt ZeroVal(S.Context.getIntWidth(T: S.Context.IntTy), 0);
8973 Expr *Zero =
8974 IntegerLiteral::Create(C: S.Context, V: ZeroVal, type: S.Context.IntTy, l: Loc);
8975 ExprResult Comp;
8976 if (VDRef.get()->getType()->isOverloadableType())
8977 Comp = S.CreateOverloadedBinOp(OpLoc: Loc, Opc: BO_NE, Fns, LHS: VDRef.get(), RHS: Zero, RequiresADL: true,
8978 AllowRewrittenCandidates: true, DefaultedFn: FD);
8979 else
8980 Comp = S.CreateBuiltinBinOp(OpLoc: Loc, Opc: BO_NE, LHSExpr: VDRef.get(), RHSExpr: Zero);
8981 if (Comp.isInvalid())
8982 return StmtError();
8983 Sema::ConditionResult Cond = S.ActOnCondition(
8984 S: nullptr, Loc, SubExpr: Comp.get(), CK: Sema::ConditionKind::Boolean);
8985 if (Cond.isInvalid())
8986 return StmtError();
8987
8988 // return cmp;
8989 VDRef = getDecl(VD);
8990 if (VDRef.isInvalid())
8991 return StmtError();
8992 StmtResult ReturnStmt = S.BuildReturnStmt(ReturnLoc: Loc, RetValExp: VDRef.get());
8993 if (ReturnStmt.isInvalid())
8994 return StmtError();
8995
8996 // if (...)
8997 return S.ActOnIfStmt(IfLoc: Loc, StatementKind: IfStatementKind::Ordinary, LParenLoc: Loc, InitStmt, Cond,
8998 RParenLoc: Loc, ThenVal: ReturnStmt.get(),
8999 /*ElseLoc=*/SourceLocation(), /*Else=*/ElseVal: nullptr);
9000 }
9001
9002 case DefaultedComparisonKind::NotEqual:
9003 case DefaultedComparisonKind::Relational:
9004 // C++2a [class.compare.secondary]p2:
9005 // Otherwise, the operator function yields x @ y.
9006 return Op.get();
9007 }
9008 llvm_unreachable("");
9009 }
9010
9011 /// Build "static_cast<R>(E)".
9012 ExprResult buildStaticCastToR(Expr *E) {
9013 QualType R = FD->getReturnType();
9014 assert(!R->isUndeducedType() && "type should have been deduced already");
9015
9016 // Don't bother forming a no-op cast in the common case.
9017 if (E->isPRValue() && S.Context.hasSameType(T1: E->getType(), T2: R))
9018 return E;
9019 return S.BuildCXXNamedCast(OpLoc: Loc, Kind: tok::kw_static_cast,
9020 Ty: S.Context.getTrivialTypeSourceInfo(T: R, Loc), E,
9021 AngleBrackets: SourceRange(Loc, Loc), Parens: SourceRange(Loc, Loc));
9022 }
9023};
9024}
9025
9026/// Perform the unqualified lookups that might be needed to form a defaulted
9027/// comparison function for the given operator.
9028static void lookupOperatorsForDefaultedComparison(Sema &Self, Scope *S,
9029 UnresolvedSetImpl &Operators,
9030 OverloadedOperatorKind Op) {
9031 auto Lookup = [&](OverloadedOperatorKind OO) {
9032 Self.LookupOverloadedOperatorName(Op: OO, S, Functions&: Operators);
9033 };
9034
9035 // Every defaulted operator looks up itself.
9036 Lookup(Op);
9037 // ... and the rewritten form of itself, if any.
9038 if (OverloadedOperatorKind ExtraOp = getRewrittenOverloadedOperator(Kind: Op))
9039 Lookup(ExtraOp);
9040
9041 // For 'operator<=>', we also form a 'cmp != 0' expression, and might
9042 // synthesize a three-way comparison from '<' and '=='. In a dependent
9043 // context, we also need to look up '==' in case we implicitly declare a
9044 // defaulted 'operator=='.
9045 if (Op == OO_Spaceship) {
9046 Lookup(OO_ExclaimEqual);
9047 Lookup(OO_Less);
9048 Lookup(OO_EqualEqual);
9049 }
9050}
9051
9052bool Sema::CheckExplicitlyDefaultedComparison(Scope *S, FunctionDecl *FD,
9053 DefaultedComparisonKind DCK) {
9054 assert(DCK != DefaultedComparisonKind::None && "not a defaulted comparison");
9055
9056 // Perform any unqualified lookups we're going to need to default this
9057 // function.
9058 if (S) {
9059 UnresolvedSet<32> Operators;
9060 lookupOperatorsForDefaultedComparison(Self&: *this, S, Operators,
9061 Op: FD->getOverloadedOperator());
9062 FD->setDefaultedOrDeletedInfo(
9063 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
9064 Context, Lookups: Operators.pairs(), FPFeatures: CurFPFeatureOverrides()));
9065 }
9066
9067 // C++2a [class.compare.default]p1:
9068 // A defaulted comparison operator function for some class C shall be a
9069 // non-template function declared in the member-specification of C that is
9070 // -- a non-static const non-volatile member of C having one parameter of
9071 // type const C& and either no ref-qualifier or the ref-qualifier &, or
9072 // -- a friend of C having two parameters of type const C& or two
9073 // parameters of type C.
9074
9075 CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext());
9076 bool IsMethod = isa<CXXMethodDecl>(Val: FD);
9077 if (IsMethod) {
9078 auto *MD = cast<CXXMethodDecl>(Val: FD);
9079 assert(!MD->isStatic() && "comparison function cannot be a static member");
9080
9081 if (MD->getRefQualifier() == RQ_RValue) {
9082 Diag(Loc: MD->getLocation(), DiagID: diag::err_ref_qualifier_comparison_operator);
9083
9084 // Remove the ref qualifier to recover.
9085 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9086 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9087 EPI.RefQualifier = RQ_None;
9088 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9089 Args: FPT->getParamTypes(), EPI));
9090 }
9091
9092 // If we're out-of-class, this is the class we're comparing.
9093 if (!RD)
9094 RD = MD->getParent();
9095 QualType T = MD->getFunctionObjectParameterReferenceType();
9096 if (!T.getNonReferenceType().isConstQualified() &&
9097 (MD->isImplicitObjectMemberFunction() || T->isLValueReferenceType())) {
9098 SourceLocation Loc, InsertLoc;
9099 if (MD->isExplicitObjectMemberFunction()) {
9100 Loc = MD->getParamDecl(i: 0)->getBeginLoc();
9101 InsertLoc = getLocForEndOfToken(
9102 Loc: MD->getParamDecl(i: 0)->getExplicitObjectParamThisLoc());
9103 } else {
9104 Loc = MD->getLocation();
9105 if (FunctionTypeLoc Loc = MD->getFunctionTypeLoc())
9106 InsertLoc = getLocForEndOfToken(Loc: Loc.getRParenLoc());
9107 }
9108 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9109 // corresponding defaulted 'operator<=>' already.
9110 if (!MD->isImplicit()) {
9111 Diag(Loc, DiagID: diag::err_defaulted_comparison_non_const)
9112 << (int)DCK << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " const");
9113 }
9114
9115 // Add the 'const' to the type to recover.
9116 if (MD->isExplicitObjectMemberFunction()) {
9117 assert(T->isLValueReferenceType());
9118 MD->getParamDecl(i: 0)->setType(Context.getLValueReferenceType(
9119 T: T.getNonReferenceType().withConst()));
9120 } else {
9121 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9122 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9123 EPI.TypeQuals.addConst();
9124 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9125 Args: FPT->getParamTypes(), EPI));
9126 }
9127 }
9128
9129 if (MD->isVolatile()) {
9130 Diag(Loc: MD->getLocation(), DiagID: diag::err_volatile_comparison_operator);
9131
9132 // Remove the 'volatile' from the type to recover.
9133 const auto *FPT = MD->getType()->castAs<FunctionProtoType>();
9134 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9135 EPI.TypeQuals.removeVolatile();
9136 MD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9137 Args: FPT->getParamTypes(), EPI));
9138 }
9139 }
9140
9141 if ((FD->getNumParams() -
9142 (unsigned)FD->hasCXXExplicitFunctionObjectParameter()) !=
9143 (IsMethod ? 1 : 2)) {
9144 // Let's not worry about using a variadic template pack here -- who would do
9145 // such a thing?
9146 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_num_args)
9147 << int(IsMethod) << int(DCK);
9148 return true;
9149 }
9150
9151 const ParmVarDecl *KnownParm = nullptr;
9152 for (const ParmVarDecl *Param : FD->parameters()) {
9153 QualType ParmTy = Param->getType();
9154 if (!KnownParm) {
9155 auto CTy = ParmTy;
9156 // Is it `T const &`?
9157 bool Ok = !IsMethod || FD->hasCXXExplicitFunctionObjectParameter();
9158 QualType ExpectedTy;
9159 if (RD)
9160 ExpectedTy = Context.getCanonicalTagType(TD: RD);
9161 if (auto *Ref = CTy->getAs<LValueReferenceType>()) {
9162 CTy = Ref->getPointeeType();
9163 if (RD)
9164 ExpectedTy.addConst();
9165 Ok = true;
9166 }
9167
9168 // Is T a class?
9169 if (RD) {
9170 Ok &= RD->isDependentType() || Context.hasSameType(T1: CTy, T2: ExpectedTy);
9171 } else {
9172 RD = CTy->getAsCXXRecordDecl();
9173 Ok &= RD != nullptr;
9174 }
9175
9176 if (Ok) {
9177 KnownParm = Param;
9178 } else {
9179 // Don't diagnose an implicit 'operator=='; we will have diagnosed the
9180 // corresponding defaulted 'operator<=>' already.
9181 if (!FD->isImplicit()) {
9182 if (RD) {
9183 CanQualType PlainTy = Context.getCanonicalTagType(TD: RD);
9184 QualType RefTy =
9185 Context.getLValueReferenceType(T: PlainTy.withConst());
9186 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param)
9187 << int(DCK) << ParmTy << RefTy << int(!IsMethod) << PlainTy
9188 << Param->getSourceRange();
9189 } else {
9190 assert(!IsMethod && "should know expected type for method");
9191 Diag(Loc: FD->getLocation(),
9192 DiagID: diag::err_defaulted_comparison_param_unknown)
9193 << int(DCK) << ParmTy << Param->getSourceRange();
9194 }
9195 }
9196 return true;
9197 }
9198 } else if (!Context.hasSameType(T1: KnownParm->getType(), T2: ParmTy)) {
9199 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_param_mismatch)
9200 << int(DCK) << KnownParm->getType() << KnownParm->getSourceRange()
9201 << ParmTy << Param->getSourceRange();
9202 return true;
9203 }
9204 }
9205
9206 assert(RD && "must have determined class");
9207 if (IsMethod) {
9208 } else if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9209 // In-class, must be a friend decl.
9210 assert(FD->getFriendObjectKind() && "expected a friend declaration");
9211 } else {
9212 // Out of class, require the defaulted comparison to be a friend (of a
9213 // complete type, per CWG2547).
9214 if (RequireCompleteType(Loc: FD->getLocation(), T: Context.getCanonicalTagType(TD: RD),
9215 DiagID: diag::err_defaulted_comparison_not_friend, Args: int(DCK),
9216 Args: int(1)))
9217 return true;
9218
9219 if (llvm::none_of(Range: RD->friends(), P: [&](const FriendDecl *F) {
9220 return declaresSameEntity(D1: F->getFriendDecl(), D2: FD);
9221 })) {
9222 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_not_friend)
9223 << int(DCK) << int(0) << RD;
9224 Diag(Loc: RD->getCanonicalDecl()->getLocation(), DiagID: diag::note_declared_at);
9225 return true;
9226 }
9227 }
9228
9229 // C++2a [class.eq]p1, [class.rel]p1:
9230 // A [defaulted comparison other than <=>] shall have a declared return
9231 // type bool.
9232 if (DCK != DefaultedComparisonKind::ThreeWay &&
9233 !FD->getDeclaredReturnType()->isDependentType() &&
9234 !Context.hasSameType(T1: FD->getDeclaredReturnType(), T2: Context.BoolTy)) {
9235 Diag(Loc: FD->getLocation(), DiagID: diag::err_defaulted_comparison_return_type_not_bool)
9236 << (int)DCK << FD->getDeclaredReturnType() << Context.BoolTy
9237 << FD->getReturnTypeSourceRange();
9238 return true;
9239 }
9240 // C++2a [class.spaceship]p2 [P2002R0]:
9241 // Let R be the declared return type [...]. If R is auto, [...]. Otherwise,
9242 // R shall not contain a placeholder type.
9243 if (QualType RT = FD->getDeclaredReturnType();
9244 DCK == DefaultedComparisonKind::ThreeWay &&
9245 RT->getContainedDeducedType() &&
9246 (!Context.hasSameType(T1: RT, T2: Context.getAutoDeductType()) ||
9247 RT->getContainedAutoType()->isConstrained())) {
9248 Diag(Loc: FD->getLocation(),
9249 DiagID: diag::err_defaulted_comparison_deduced_return_type_not_auto)
9250 << (int)DCK << FD->getDeclaredReturnType() << Context.AutoDeductTy
9251 << FD->getReturnTypeSourceRange();
9252 return true;
9253 }
9254
9255 // For a defaulted function in a dependent class, defer all remaining checks
9256 // until instantiation.
9257 if (RD->isDependentType())
9258 return false;
9259
9260 // Determine whether the function should be defined as deleted.
9261 DefaultedComparisonInfo Info =
9262 DefaultedComparisonAnalyzer(*this, RD, FD, DCK).visit();
9263
9264 bool First = FD == FD->getCanonicalDecl();
9265
9266 if (!First) {
9267 if (Info.Deleted) {
9268 // C++11 [dcl.fct.def.default]p4:
9269 // [For a] user-provided explicitly-defaulted function [...] if such a
9270 // function is implicitly defined as deleted, the program is ill-formed.
9271 //
9272 // This is really just a consequence of the general rule that you can
9273 // only delete a function on its first declaration.
9274 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_deletes)
9275 << FD->isImplicit() << (int)DCK;
9276 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9277 DefaultedComparisonAnalyzer::ExplainDeleted)
9278 .visit();
9279 return true;
9280 }
9281 if (isa<CXXRecordDecl>(Val: FD->getLexicalDeclContext())) {
9282 // C++20 [class.compare.default]p1:
9283 // [...] A definition of a comparison operator as defaulted that appears
9284 // in a class shall be the first declaration of that function.
9285 Diag(Loc: FD->getLocation(), DiagID: diag::err_non_first_default_compare_in_class)
9286 << (int)DCK;
9287 Diag(Loc: FD->getCanonicalDecl()->getLocation(),
9288 DiagID: diag::note_previous_declaration);
9289 return true;
9290 }
9291 }
9292
9293 // If we want to delete the function, then do so; there's nothing else to
9294 // check in that case.
9295 if (Info.Deleted) {
9296 SetDeclDeleted(dcl: FD, DelLoc: FD->getLocation());
9297 if (!inTemplateInstantiation() && !FD->isImplicit()) {
9298 Diag(Loc: FD->getLocation(), DiagID: diag::warn_defaulted_comparison_deleted)
9299 << (int)DCK;
9300 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9301 DefaultedComparisonAnalyzer::ExplainDeleted)
9302 .visit();
9303 if (FD->getDefaultLoc().isValid())
9304 Diag(Loc: FD->getDefaultLoc(), DiagID: diag::note_replace_equals_default_to_delete)
9305 << FixItHint::CreateReplacement(RemoveRange: FD->getDefaultLoc(), Code: "delete");
9306 }
9307 return false;
9308 }
9309
9310 // C++2a [class.spaceship]p2:
9311 // The return type is deduced as the common comparison type of R0, R1, ...
9312 if (DCK == DefaultedComparisonKind::ThreeWay &&
9313 FD->getDeclaredReturnType()->isUndeducedAutoType()) {
9314 SourceLocation RetLoc = FD->getReturnTypeSourceRange().getBegin();
9315 if (RetLoc.isInvalid())
9316 RetLoc = FD->getBeginLoc();
9317 // FIXME: Should we really care whether we have the complete type and the
9318 // 'enumerator' constants here? A forward declaration seems sufficient.
9319 QualType Cat = CheckComparisonCategoryType(
9320 Kind: Info.Category, Loc: RetLoc, Usage: ComparisonCategoryUsage::DefaultedOperator);
9321 if (Cat.isNull())
9322 return true;
9323 Context.adjustDeducedFunctionResultType(
9324 FD, ResultType: SubstAutoType(TypeWithAuto: FD->getDeclaredReturnType(), Replacement: Cat));
9325 }
9326
9327 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9328 // An explicitly-defaulted function that is not defined as deleted may be
9329 // declared constexpr or consteval only if it is constexpr-compatible.
9330 // C++2a [class.compare.default]p3 [P2002R0]:
9331 // A defaulted comparison function is constexpr-compatible if it satisfies
9332 // the requirements for a constexpr function [...]
9333 // The only relevant requirements are that the parameter and return types are
9334 // literal types. The remaining conditions are checked by the analyzer.
9335 //
9336 // We support P2448R2 in language modes earlier than C++23 as an extension.
9337 // The concept of constexpr-compatible was removed.
9338 // C++23 [dcl.fct.def.default]p3 [P2448R2]
9339 // A function explicitly defaulted on its first declaration is implicitly
9340 // inline, and is implicitly constexpr if it is constexpr-suitable.
9341 // C++23 [dcl.constexpr]p3
9342 // A function is constexpr-suitable if
9343 // - it is not a coroutine, and
9344 // - if the function is a constructor or destructor, its class does not
9345 // have any virtual base classes.
9346 if (FD->isConstexpr()) {
9347 if (!getLangOpts().CPlusPlus23 &&
9348 CheckConstexprReturnType(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9349 CheckConstexprParameterTypes(SemaRef&: *this, FD, Kind: CheckConstexprKind::Diagnose) &&
9350 !Info.Constexpr) {
9351 Diag(Loc: FD->getBeginLoc(), DiagID: diag::err_defaulted_comparison_constexpr_mismatch)
9352 << FD->isImplicit() << (int)DCK << FD->isConsteval();
9353 DefaultedComparisonAnalyzer(*this, RD, FD, DCK,
9354 DefaultedComparisonAnalyzer::ExplainConstexpr)
9355 .visit();
9356 }
9357 }
9358
9359 // C++2a [dcl.fct.def.default]p3 [P2002R0]:
9360 // If a constexpr-compatible function is explicitly defaulted on its first
9361 // declaration, it is implicitly considered to be constexpr.
9362 // FIXME: Only applying this to the first declaration seems problematic, as
9363 // simple reorderings can affect the meaning of the program.
9364 if (First && !FD->isConstexpr() && Info.Constexpr)
9365 FD->setConstexprKind(ConstexprSpecKind::Constexpr);
9366
9367 // C++2a [except.spec]p3:
9368 // If a declaration of a function does not have a noexcept-specifier
9369 // [and] is defaulted on its first declaration, [...] the exception
9370 // specification is as specified below
9371 if (FD->getExceptionSpecType() == EST_None) {
9372 auto *FPT = FD->getType()->castAs<FunctionProtoType>();
9373 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
9374 EPI.ExceptionSpec.Type = EST_Unevaluated;
9375 EPI.ExceptionSpec.SourceDecl = FD;
9376 FD->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
9377 Args: FPT->getParamTypes(), EPI));
9378 }
9379
9380 return false;
9381}
9382
9383void Sema::DeclareImplicitEqualityComparison(CXXRecordDecl *RD,
9384 FunctionDecl *Spaceship) {
9385 Sema::CodeSynthesisContext Ctx;
9386 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringImplicitEqualityComparison;
9387 Ctx.PointOfInstantiation = Spaceship->getEndLoc();
9388 Ctx.Entity = Spaceship;
9389 pushCodeSynthesisContext(Ctx);
9390
9391 if (FunctionDecl *EqualEqual = SubstSpaceshipAsEqualEqual(RD, Spaceship))
9392 EqualEqual->setImplicit();
9393
9394 popCodeSynthesisContext();
9395}
9396
9397void Sema::DefineDefaultedComparison(SourceLocation UseLoc, FunctionDecl *FD,
9398 DefaultedComparisonKind DCK) {
9399 assert(FD->isDefaulted() && !FD->isDeleted() &&
9400 !FD->doesThisDeclarationHaveABody());
9401 if (FD->willHaveBody() || FD->isInvalidDecl())
9402 return;
9403
9404 SynthesizedFunctionScope Scope(*this, FD);
9405
9406 // Add a context note for diagnostics produced after this point.
9407 Scope.addContextNote(UseLoc);
9408
9409 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, FD);
9410
9411 {
9412 // Build and set up the function body.
9413 // The first parameter has type maybe-ref-to maybe-const T, use that to get
9414 // the type of the class being compared.
9415 auto PT = FD->getParamDecl(i: 0)->getType();
9416 CXXRecordDecl *RD = PT.getNonReferenceType()->getAsCXXRecordDecl();
9417 SourceLocation BodyLoc =
9418 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9419 StmtResult Body =
9420 DefaultedComparisonSynthesizer(*this, RD, FD, DCK, BodyLoc).build();
9421 if (Body.isInvalid()) {
9422 FD->setInvalidDecl();
9423 return;
9424 }
9425 FD->setBody(Body.get());
9426 FD->markUsed(C&: Context);
9427 }
9428
9429 // The exception specification is needed because we are defining the
9430 // function. Note that this will reuse the body we just built.
9431 ResolveExceptionSpec(Loc: UseLoc, FPT: FD->getType()->castAs<FunctionProtoType>());
9432
9433 if (ASTMutationListener *L = getASTMutationListener())
9434 L->CompletedImplicitDefinition(D: FD);
9435}
9436
9437static Sema::ImplicitExceptionSpecification
9438ComputeDefaultedComparisonExceptionSpec(Sema &S, SourceLocation Loc,
9439 FunctionDecl *FD,
9440 DefaultedComparisonKind DCK) {
9441 ComputingExceptionSpec CES(S, FD, Loc);
9442 Sema::ImplicitExceptionSpecification ExceptSpec(S);
9443
9444 if (FD->isInvalidDecl())
9445 return ExceptSpec;
9446
9447 // The common case is that we just defined the comparison function. In that
9448 // case, just look at whether the body can throw.
9449 if (Stmt *FunctionBody = FD->getBody()) {
9450 ExceptSpec.CalledStmt(S: FunctionBody);
9451 } else {
9452 // Otherwise, build a body so we can check it. This should ideally only
9453 // happen when we're not actually marking the function referenced. (This is
9454 // only really important for efficiency: we don't want to build and throw
9455 // away bodies for comparison functions more than we strictly need to.)
9456
9457 // Pretend to synthesize the function body in an unevaluated context.
9458 // Note that we can't actually just go ahead and define the function here:
9459 // we are not permitted to mark its callees as referenced.
9460 Sema::SynthesizedFunctionScope Scope(S, FD);
9461 EnterExpressionEvaluationContext Context(
9462 S, Sema::ExpressionEvaluationContext::Unevaluated);
9463
9464 CXXRecordDecl *RD =
9465 cast<CXXRecordDecl>(Val: FD->getFriendObjectKind() == Decl::FOK_None
9466 ? FD->getDeclContext()
9467 : FD->getLexicalDeclContext());
9468 SourceLocation BodyLoc =
9469 FD->getEndLoc().isValid() ? FD->getEndLoc() : FD->getLocation();
9470 StmtResult Body =
9471 DefaultedComparisonSynthesizer(S, RD, FD, DCK, BodyLoc).build();
9472 if (!Body.isInvalid())
9473 ExceptSpec.CalledStmt(S: Body.get());
9474
9475 // FIXME: Can we hold onto this body and just transform it to potentially
9476 // evaluated when we're asked to define the function rather than rebuilding
9477 // it? Either that, or we should only build the bits of the body that we
9478 // need (the expressions, not the statements).
9479 }
9480
9481 return ExceptSpec;
9482}
9483
9484void Sema::CheckDelayedMemberExceptionSpecs() {
9485 decltype(DelayedOverridingExceptionSpecChecks) Overriding;
9486 decltype(DelayedEquivalentExceptionSpecChecks) Equivalent;
9487
9488 std::swap(LHS&: Overriding, RHS&: DelayedOverridingExceptionSpecChecks);
9489 std::swap(LHS&: Equivalent, RHS&: DelayedEquivalentExceptionSpecChecks);
9490
9491 // Perform any deferred checking of exception specifications for virtual
9492 // destructors.
9493 for (auto &Check : Overriding)
9494 CheckOverridingFunctionExceptionSpec(New: Check.first, Old: Check.second);
9495
9496 // Perform any deferred checking of exception specifications for befriended
9497 // special members.
9498 for (auto &Check : Equivalent)
9499 CheckEquivalentExceptionSpec(Old: Check.second, New: Check.first);
9500}
9501
9502namespace {
9503/// CRTP base class for visiting operations performed by a special member
9504/// function (or inherited constructor).
9505template<typename Derived>
9506struct SpecialMemberVisitor {
9507 Sema &S;
9508 CXXMethodDecl *MD;
9509 CXXSpecialMemberKind CSM;
9510 Sema::InheritedConstructorInfo *ICI;
9511
9512 // Properties of the special member, computed for convenience.
9513 bool IsConstructor = false, IsAssignment = false, ConstArg = false;
9514
9515 SpecialMemberVisitor(Sema &S, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
9516 Sema::InheritedConstructorInfo *ICI)
9517 : S(S), MD(MD), CSM(CSM), ICI(ICI) {
9518 switch (CSM) {
9519 case CXXSpecialMemberKind::DefaultConstructor:
9520 case CXXSpecialMemberKind::CopyConstructor:
9521 case CXXSpecialMemberKind::MoveConstructor:
9522 IsConstructor = true;
9523 break;
9524 case CXXSpecialMemberKind::CopyAssignment:
9525 case CXXSpecialMemberKind::MoveAssignment:
9526 IsAssignment = true;
9527 break;
9528 case CXXSpecialMemberKind::Destructor:
9529 break;
9530 case CXXSpecialMemberKind::Invalid:
9531 llvm_unreachable("invalid special member kind");
9532 }
9533
9534 if (MD->getNumExplicitParams()) {
9535 if (const ReferenceType *RT =
9536 MD->getNonObjectParameter(I: 0)->getType()->getAs<ReferenceType>())
9537 ConstArg = RT->getPointeeType().isConstQualified();
9538 }
9539 }
9540
9541 Derived &getDerived() { return static_cast<Derived&>(*this); }
9542
9543 /// Is this a "move" special member?
9544 bool isMove() const {
9545 return CSM == CXXSpecialMemberKind::MoveConstructor ||
9546 CSM == CXXSpecialMemberKind::MoveAssignment;
9547 }
9548
9549 /// Look up the corresponding special member in the given class.
9550 Sema::SpecialMemberOverloadResult lookupIn(CXXRecordDecl *Class,
9551 unsigned Quals, bool IsMutable) {
9552 return lookupCallFromSpecialMember(S, Class, CSM, FieldQuals: Quals,
9553 ConstRHS: ConstArg && !IsMutable);
9554 }
9555
9556 /// Look up the constructor for the specified base class to see if it's
9557 /// overridden due to this being an inherited constructor.
9558 Sema::SpecialMemberOverloadResult lookupInheritedCtor(CXXRecordDecl *Class) {
9559 if (!ICI)
9560 return {};
9561 assert(CSM == CXXSpecialMemberKind::DefaultConstructor);
9562 auto *BaseCtor =
9563 cast<CXXConstructorDecl>(Val: MD)->getInheritedConstructor().getConstructor();
9564 if (auto *MD = ICI->findConstructorForBase(Base: Class, Ctor: BaseCtor).first)
9565 return MD;
9566 return {};
9567 }
9568
9569 /// A base or member subobject.
9570 typedef llvm::PointerUnion<CXXBaseSpecifier*, FieldDecl*> Subobject;
9571
9572 /// Get the location to use for a subobject in diagnostics.
9573 static SourceLocation getSubobjectLoc(Subobject Subobj) {
9574 // FIXME: For an indirect virtual base, the direct base leading to
9575 // the indirect virtual base would be a more useful choice.
9576 if (auto *B = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj))
9577 return B->getBaseTypeLoc();
9578 else
9579 return cast<FieldDecl *>(Val&: Subobj)->getLocation();
9580 }
9581
9582 enum BasesToVisit {
9583 /// Visit all non-virtual (direct) bases.
9584 VisitNonVirtualBases,
9585 /// Visit all direct bases, virtual or not.
9586 VisitDirectBases,
9587 /// Visit all non-virtual bases, and all virtual bases if the class
9588 /// is not abstract.
9589 VisitPotentiallyConstructedBases,
9590 /// Visit all direct or virtual bases.
9591 VisitAllBases
9592 };
9593
9594 // Visit the bases and members of the class.
9595 bool visit(BasesToVisit Bases) {
9596 CXXRecordDecl *RD = MD->getParent();
9597
9598 if (Bases == VisitPotentiallyConstructedBases)
9599 Bases = RD->isAbstract() ? VisitNonVirtualBases : VisitAllBases;
9600
9601 for (auto &B : RD->bases())
9602 if ((Bases == VisitDirectBases || !B.isVirtual()) &&
9603 getDerived().visitBase(&B))
9604 return true;
9605
9606 if (Bases == VisitAllBases)
9607 for (auto &B : RD->vbases())
9608 if (getDerived().visitBase(&B))
9609 return true;
9610
9611 for (auto *F : RD->fields())
9612 if (!F->isInvalidDecl() && !F->isUnnamedBitField() &&
9613 getDerived().visitField(F))
9614 return true;
9615
9616 return false;
9617 }
9618};
9619}
9620
9621namespace {
9622struct SpecialMemberDeletionInfo
9623 : SpecialMemberVisitor<SpecialMemberDeletionInfo> {
9624 bool Diagnose;
9625
9626 SourceLocation Loc;
9627
9628 bool AllFieldsAreConst;
9629
9630 SpecialMemberDeletionInfo(Sema &S, CXXMethodDecl *MD,
9631 CXXSpecialMemberKind CSM,
9632 Sema::InheritedConstructorInfo *ICI, bool Diagnose)
9633 : SpecialMemberVisitor(S, MD, CSM, ICI), Diagnose(Diagnose),
9634 Loc(MD->getLocation()), AllFieldsAreConst(true) {}
9635
9636 bool inUnion() const { return MD->getParent()->isUnion(); }
9637
9638 CXXSpecialMemberKind getEffectiveCSM() {
9639 return ICI ? CXXSpecialMemberKind::Invalid : CSM;
9640 }
9641
9642 bool shouldDeleteForVariantObjCPtrMember(FieldDecl *FD, QualType FieldType);
9643
9644 bool shouldDeleteForVariantPtrAuthMember(const FieldDecl *FD);
9645
9646 bool visitBase(CXXBaseSpecifier *Base) { return shouldDeleteForBase(Base); }
9647 bool visitField(FieldDecl *Field) { return shouldDeleteForField(FD: Field); }
9648
9649 bool shouldDeleteForBase(CXXBaseSpecifier *Base);
9650 bool shouldDeleteForField(FieldDecl *FD);
9651 bool shouldDeleteForAllConstMembers();
9652
9653 bool shouldDeleteForClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
9654 unsigned Quals);
9655 bool shouldDeleteForSubobjectCall(Subobject Subobj,
9656 Sema::SpecialMemberOverloadResult SMOR,
9657 bool IsDtorCallInCtor);
9658
9659 bool isAccessible(Subobject Subobj, CXXMethodDecl *D);
9660};
9661}
9662
9663/// Is the given special member inaccessible when used on the given
9664/// sub-object.
9665bool SpecialMemberDeletionInfo::isAccessible(Subobject Subobj,
9666 CXXMethodDecl *target) {
9667 /// If we're operating on a base class, the object type is the
9668 /// type of this special member.
9669 CanQualType objectTy;
9670 AccessSpecifier access = target->getAccess();
9671 if (CXXBaseSpecifier *base = dyn_cast<CXXBaseSpecifier *>(Val&: Subobj)) {
9672 objectTy = S.Context.getCanonicalTagType(TD: MD->getParent());
9673 access = CXXRecordDecl::MergeAccess(PathAccess: base->getAccessSpecifier(), DeclAccess: access);
9674
9675 // If we're operating on a field, the object type is the type of the field.
9676 } else {
9677 objectTy = S.Context.getCanonicalTagType(TD: target->getParent());
9678 }
9679
9680 return S.isMemberAccessibleForDeletion(
9681 NamingClass: target->getParent(), Found: DeclAccessPair::make(D: target, AS: access), ObjectType: objectTy);
9682}
9683
9684/// Check whether we should delete a special member due to the implicit
9685/// definition containing a call to a special member of a subobject.
9686bool SpecialMemberDeletionInfo::shouldDeleteForSubobjectCall(
9687 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR,
9688 bool IsDtorCallInCtor) {
9689 CXXMethodDecl *Decl = SMOR.getMethod();
9690 FieldDecl *Field = dyn_cast<FieldDecl *>(Val&: Subobj);
9691
9692 enum {
9693 NotSet = -1,
9694 NoDecl,
9695 DeletedDecl,
9696 MultipleDecl,
9697 InaccessibleDecl,
9698 NonTrivialDecl
9699 } DiagKind = NotSet;
9700
9701 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::NoMemberOrDeleted) {
9702 if (CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9703 Field->getParent()->isUnion()) {
9704 // [class.default.ctor]p2:
9705 // A defaulted default constructor for class X is defined as deleted if
9706 // - X is a union that has a variant member with a non-trivial default
9707 // constructor and no variant member of X has a default member
9708 // initializer
9709 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9710 if (RD->hasInClassInitializer())
9711 return false;
9712 }
9713 DiagKind = !Decl ? NoDecl : DeletedDecl;
9714 } else if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
9715 DiagKind = MultipleDecl;
9716 else if (!isAccessible(Subobj, target: Decl))
9717 DiagKind = InaccessibleDecl;
9718 else if (!IsDtorCallInCtor && Field && Field->getParent()->isUnion() &&
9719 !Decl->isTrivial()) {
9720 // A member of a union must have a trivial corresponding special member.
9721 // As a weird special case, a destructor call from a union's constructor
9722 // must be accessible and non-deleted, but need not be trivial. Such a
9723 // destructor is never actually called, but is semantically checked as
9724 // if it were.
9725 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9726 // [class.default.ctor]p2:
9727 // A defaulted default constructor for class X is defined as deleted if
9728 // - X is a union that has a variant member with a non-trivial default
9729 // constructor and no variant member of X has a default member
9730 // initializer
9731 const auto *RD = cast<CXXRecordDecl>(Val: Field->getParent());
9732 if (!RD->hasInClassInitializer())
9733 DiagKind = NonTrivialDecl;
9734 } else {
9735 DiagKind = NonTrivialDecl;
9736 }
9737 }
9738
9739 if (DiagKind == NotSet)
9740 return false;
9741
9742 if (Diagnose) {
9743 if (Field) {
9744 S.Diag(Loc: Field->getLocation(),
9745 DiagID: diag::note_deleted_special_member_class_subobject)
9746 << getEffectiveCSM() << MD->getParent() << /*IsField*/ true << Field
9747 << DiagKind << IsDtorCallInCtor << /*IsObjCPtr*/ false;
9748 } else {
9749 CXXBaseSpecifier *Base = cast<CXXBaseSpecifier *>(Val&: Subobj);
9750 S.Diag(Loc: Base->getBeginLoc(),
9751 DiagID: diag::note_deleted_special_member_class_subobject)
9752 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9753 << Base->getType() << DiagKind << IsDtorCallInCtor
9754 << /*IsObjCPtr*/ false;
9755 }
9756
9757 if (DiagKind == DeletedDecl)
9758 S.NoteDeletedFunction(FD: Decl);
9759 // FIXME: Explain inaccessibility if DiagKind == InaccessibleDecl.
9760 }
9761
9762 return true;
9763}
9764
9765/// Check whether we should delete a special member function due to having a
9766/// direct or virtual base class or non-static data member of class type M.
9767bool SpecialMemberDeletionInfo::shouldDeleteForClassSubobject(
9768 CXXRecordDecl *Class, Subobject Subobj, unsigned Quals) {
9769 FieldDecl *Field = dyn_cast<FieldDecl *>(Val&: Subobj);
9770 bool IsMutable = Field && Field->isMutable();
9771
9772 // C++11 [class.ctor]p5:
9773 // -- any direct or virtual base class, or non-static data member with no
9774 // brace-or-equal-initializer, has class type M (or array thereof) and
9775 // either M has no default constructor or overload resolution as applied
9776 // to M's default constructor results in an ambiguity or in a function
9777 // that is deleted or inaccessible
9778 // C++11 [class.copy]p11, C++11 [class.copy]p23:
9779 // -- a direct or virtual base class B that cannot be copied/moved because
9780 // overload resolution, as applied to B's corresponding special member,
9781 // results in an ambiguity or a function that is deleted or inaccessible
9782 // from the defaulted special member
9783 // C++11 [class.dtor]p5:
9784 // -- any direct or virtual base class [...] has a type with a destructor
9785 // that is deleted or inaccessible
9786 if (!(CSM == CXXSpecialMemberKind::DefaultConstructor && Field &&
9787 Field->hasInClassInitializer()) &&
9788 shouldDeleteForSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable),
9789 IsDtorCallInCtor: false))
9790 return true;
9791
9792 // C++11 [class.ctor]p5, C++11 [class.copy]p11:
9793 // -- any direct or virtual base class or non-static data member has a
9794 // type with a destructor that is deleted or inaccessible
9795 if (IsConstructor) {
9796 Sema::SpecialMemberOverloadResult SMOR =
9797 S.LookupSpecialMember(D: Class, SM: CXXSpecialMemberKind::Destructor, ConstArg: false,
9798 VolatileArg: false, RValueThis: false, ConstThis: false, VolatileThis: false);
9799 if (shouldDeleteForSubobjectCall(Subobj, SMOR, IsDtorCallInCtor: true))
9800 return true;
9801 }
9802
9803 return false;
9804}
9805
9806bool SpecialMemberDeletionInfo::shouldDeleteForVariantObjCPtrMember(
9807 FieldDecl *FD, QualType FieldType) {
9808 // The defaulted special functions are defined as deleted if this is a variant
9809 // member with a non-trivial ownership type, e.g., ObjC __strong or __weak
9810 // type under ARC.
9811 if (!FieldType.hasNonTrivialObjCLifetime())
9812 return false;
9813
9814 // Don't make the defaulted default constructor defined as deleted if the
9815 // member has an in-class initializer.
9816 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9817 FD->hasInClassInitializer())
9818 return false;
9819
9820 if (Diagnose) {
9821 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9822 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9823 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9824 << /*IsDtorCallInCtor*/ false << /*IsObjCPtr*/ true;
9825 }
9826
9827 return true;
9828}
9829
9830bool SpecialMemberDeletionInfo::shouldDeleteForVariantPtrAuthMember(
9831 const FieldDecl *FD) {
9832 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9833 // Copy/move constructors/assignment operators are deleted if the field has an
9834 // address-discriminated ptrauth qualifier.
9835 PointerAuthQualifier Q = FieldType.getPointerAuth();
9836
9837 if (!Q || !Q.isAddressDiscriminated())
9838 return false;
9839
9840 if (CSM == CXXSpecialMemberKind::DefaultConstructor ||
9841 CSM == CXXSpecialMemberKind::Destructor)
9842 return false;
9843
9844 if (Diagnose) {
9845 auto *ParentClass = cast<CXXRecordDecl>(Val: FD->getParent());
9846 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_special_member_class_subobject)
9847 << getEffectiveCSM() << ParentClass << /*IsField*/ true << FD << 4
9848 << /*IsDtorCallInCtor*/ false << 2;
9849 }
9850
9851 return true;
9852}
9853
9854/// Check whether we should delete a special member function due to the class
9855/// having a particular direct or virtual base class.
9856bool SpecialMemberDeletionInfo::shouldDeleteForBase(CXXBaseSpecifier *Base) {
9857 CXXRecordDecl *BaseClass = Base->getType()->getAsCXXRecordDecl();
9858 // If program is correct, BaseClass cannot be null, but if it is, the error
9859 // must be reported elsewhere.
9860 if (!BaseClass)
9861 return false;
9862 // If we have an inheriting constructor, check whether we're calling an
9863 // inherited constructor instead of a default constructor.
9864 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
9865 if (auto *BaseCtor = SMOR.getMethod()) {
9866 // Note that we do not check access along this path; other than that,
9867 // this is the same as shouldDeleteForSubobjectCall(Base, BaseCtor, false);
9868 // FIXME: Check that the base has a usable destructor! Sink this into
9869 // shouldDeleteForClassSubobject.
9870 if (BaseCtor->isDeleted() && Diagnose) {
9871 S.Diag(Loc: Base->getBeginLoc(),
9872 DiagID: diag::note_deleted_special_member_class_subobject)
9873 << getEffectiveCSM() << MD->getParent() << /*IsField*/ false
9874 << Base->getType() << /*Deleted*/ 1 << /*IsDtorCallInCtor*/ false
9875 << /*IsObjCPtr*/ false;
9876 S.NoteDeletedFunction(FD: BaseCtor);
9877 }
9878 return BaseCtor->isDeleted();
9879 }
9880 return shouldDeleteForClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
9881}
9882
9883/// Check whether we should delete a special member function due to the class
9884/// having a particular non-static data member.
9885bool SpecialMemberDeletionInfo::shouldDeleteForField(FieldDecl *FD) {
9886 QualType FieldType = S.Context.getBaseElementType(QT: FD->getType());
9887 CXXRecordDecl *FieldRecord = FieldType->getAsCXXRecordDecl();
9888
9889 if (inUnion() && shouldDeleteForVariantObjCPtrMember(FD, FieldType))
9890 return true;
9891
9892 if (inUnion() && shouldDeleteForVariantPtrAuthMember(FD))
9893 return true;
9894
9895 if (CSM == CXXSpecialMemberKind::DefaultConstructor) {
9896 // For a default constructor, all references must be initialized in-class
9897 // and, if a union, it must have a non-const member.
9898 if (FieldType->isReferenceType() && !FD->hasInClassInitializer()) {
9899 if (Diagnose)
9900 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9901 << !!ICI << MD->getParent() << FD << FieldType << /*Reference*/0;
9902 return true;
9903 }
9904 // C++11 [class.ctor]p5 (modified by DR2394): any non-variant non-static
9905 // data member of const-qualified type (or array thereof) with no
9906 // brace-or-equal-initializer is not const-default-constructible.
9907 if (!inUnion() && FieldType.isConstQualified() &&
9908 !FD->hasInClassInitializer() &&
9909 (!FieldRecord || !FieldRecord->allowConstDefaultInit())) {
9910 if (Diagnose)
9911 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_default_ctor_uninit_field)
9912 << !!ICI << MD->getParent() << FD << FD->getType() << /*Const*/1;
9913 return true;
9914 }
9915
9916 if (inUnion() && !FieldType.isConstQualified())
9917 AllFieldsAreConst = false;
9918 } else if (CSM == CXXSpecialMemberKind::CopyConstructor) {
9919 // For a copy constructor, data members must not be of rvalue reference
9920 // type.
9921 if (FieldType->isRValueReferenceType()) {
9922 if (Diagnose)
9923 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_copy_ctor_rvalue_reference)
9924 << MD->getParent() << FD << FieldType;
9925 return true;
9926 }
9927 } else if (IsAssignment) {
9928 // For an assignment operator, data members must not be of reference type.
9929 if (FieldType->isReferenceType()) {
9930 if (Diagnose)
9931 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9932 << isMove() << MD->getParent() << FD << FieldType << /*Reference*/0;
9933 return true;
9934 }
9935 if (!FieldRecord && FieldType.isConstQualified()) {
9936 // C++11 [class.copy]p23:
9937 // -- a non-static data member of const non-class type (or array thereof)
9938 if (Diagnose)
9939 S.Diag(Loc: FD->getLocation(), DiagID: diag::note_deleted_assign_field)
9940 << isMove() << MD->getParent() << FD << FD->getType() << /*Const*/1;
9941 return true;
9942 }
9943 }
9944
9945 if (FieldRecord) {
9946 // Some additional restrictions exist on the variant members.
9947 if (!inUnion() && FieldRecord->isUnion() &&
9948 FieldRecord->isAnonymousStructOrUnion()) {
9949 bool AllVariantFieldsAreConst = true;
9950
9951 // FIXME: Handle anonymous unions declared within anonymous unions.
9952 for (auto *UI : FieldRecord->fields()) {
9953 QualType UnionFieldType = S.Context.getBaseElementType(QT: UI->getType());
9954
9955 if (shouldDeleteForVariantObjCPtrMember(FD: &*UI, FieldType: UnionFieldType))
9956 return true;
9957
9958 if (shouldDeleteForVariantPtrAuthMember(FD: &*UI))
9959 return true;
9960
9961 if (!UnionFieldType.isConstQualified())
9962 AllVariantFieldsAreConst = false;
9963
9964 CXXRecordDecl *UnionFieldRecord = UnionFieldType->getAsCXXRecordDecl();
9965 if (UnionFieldRecord &&
9966 shouldDeleteForClassSubobject(Class: UnionFieldRecord, Subobj: UI,
9967 Quals: UnionFieldType.getCVRQualifiers()))
9968 return true;
9969 }
9970
9971 // At least one member in each anonymous union must be non-const
9972 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
9973 AllVariantFieldsAreConst && !FieldRecord->field_empty()) {
9974 if (Diagnose)
9975 S.Diag(Loc: FieldRecord->getLocation(),
9976 DiagID: diag::note_deleted_default_ctor_all_const)
9977 << !!ICI << MD->getParent() << /*anonymous union*/1;
9978 return true;
9979 }
9980
9981 // Don't check the implicit member of the anonymous union type.
9982 // This is technically non-conformant but supported, and we have a
9983 // diagnostic for this elsewhere.
9984 return false;
9985 }
9986
9987 if (shouldDeleteForClassSubobject(Class: FieldRecord, Subobj: FD,
9988 Quals: FieldType.getCVRQualifiers()))
9989 return true;
9990 }
9991
9992 return false;
9993}
9994
9995/// C++11 [class.ctor] p5:
9996/// A defaulted default constructor for a class X is defined as deleted if
9997/// X is a union and all of its variant members are of const-qualified type.
9998bool SpecialMemberDeletionInfo::shouldDeleteForAllConstMembers() {
9999 // This is a silly definition, because it gives an empty union a deleted
10000 // default constructor. Don't do that.
10001 if (CSM == CXXSpecialMemberKind::DefaultConstructor && inUnion() &&
10002 AllFieldsAreConst) {
10003 bool AnyFields = false;
10004 for (auto *F : MD->getParent()->fields())
10005 if ((AnyFields = !F->isUnnamedBitField()))
10006 break;
10007 if (!AnyFields)
10008 return false;
10009 if (Diagnose)
10010 S.Diag(Loc: MD->getParent()->getLocation(),
10011 DiagID: diag::note_deleted_default_ctor_all_const)
10012 << !!ICI << MD->getParent() << /*not anonymous union*/0;
10013 return true;
10014 }
10015 return false;
10016}
10017
10018/// Determine whether a defaulted special member function should be defined as
10019/// deleted, as specified in C++11 [class.ctor]p5, C++11 [class.copy]p11,
10020/// C++11 [class.copy]p23, and C++11 [class.dtor]p5.
10021bool Sema::ShouldDeleteSpecialMember(CXXMethodDecl *MD,
10022 CXXSpecialMemberKind CSM,
10023 InheritedConstructorInfo *ICI,
10024 bool Diagnose) {
10025 if (MD->isInvalidDecl())
10026 return false;
10027 CXXRecordDecl *RD = MD->getParent();
10028 assert(!RD->isDependentType() && "do deletion after instantiation");
10029 if (!LangOpts.CPlusPlus || (!LangOpts.CPlusPlus11 && !RD->isLambda()) ||
10030 RD->isInvalidDecl())
10031 return false;
10032
10033 // C++11 [expr.lambda.prim]p19:
10034 // The closure type associated with a lambda-expression has a
10035 // deleted (8.4.3) default constructor and a deleted copy
10036 // assignment operator.
10037 // C++2a adds back these operators if the lambda has no lambda-capture.
10038 if (RD->isLambda() && !RD->lambdaIsDefaultConstructibleAndAssignable() &&
10039 (CSM == CXXSpecialMemberKind::DefaultConstructor ||
10040 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10041 if (Diagnose)
10042 Diag(Loc: RD->getLocation(), DiagID: diag::note_lambda_decl);
10043 return true;
10044 }
10045
10046 // C++11 [class.copy]p7, p18:
10047 // If the class definition declares a move constructor or move assignment
10048 // operator, an implicitly declared copy constructor or copy assignment
10049 // operator is defined as deleted.
10050 if (MD->isImplicit() && (CSM == CXXSpecialMemberKind::CopyConstructor ||
10051 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10052 CXXMethodDecl *UserDeclaredMove = nullptr;
10053
10054 // In Microsoft mode up to MSVC 2013, a user-declared move only causes the
10055 // deletion of the corresponding copy operation, not both copy operations.
10056 // MSVC 2015 has adopted the standards conforming behavior.
10057 bool DeletesOnlyMatchingCopy =
10058 getLangOpts().MSVCCompat &&
10059 !getLangOpts().isCompatibleWithMSVC(MajorVersion: LangOptions::MSVC2015);
10060
10061 if (RD->hasUserDeclaredMoveConstructor() &&
10062 (!DeletesOnlyMatchingCopy ||
10063 CSM == CXXSpecialMemberKind::CopyConstructor)) {
10064 if (!Diagnose) return true;
10065
10066 // Find any user-declared move constructor.
10067 for (auto *I : RD->ctors()) {
10068 if (I->isMoveConstructor()) {
10069 UserDeclaredMove = I;
10070 break;
10071 }
10072 }
10073 assert(UserDeclaredMove);
10074 } else if (RD->hasUserDeclaredMoveAssignment() &&
10075 (!DeletesOnlyMatchingCopy ||
10076 CSM == CXXSpecialMemberKind::CopyAssignment)) {
10077 if (!Diagnose) return true;
10078
10079 // Find any user-declared move assignment operator.
10080 for (auto *I : RD->methods()) {
10081 if (I->isMoveAssignmentOperator()) {
10082 UserDeclaredMove = I;
10083 break;
10084 }
10085 }
10086 assert(UserDeclaredMove);
10087 }
10088
10089 if (UserDeclaredMove) {
10090 Diag(Loc: UserDeclaredMove->getLocation(),
10091 DiagID: diag::note_deleted_copy_user_declared_move)
10092 << (CSM == CXXSpecialMemberKind::CopyAssignment) << RD
10093 << UserDeclaredMove->isMoveAssignmentOperator();
10094 return true;
10095 }
10096 }
10097
10098 // Do access control from the special member function
10099 ContextRAII MethodContext(*this, MD);
10100
10101 // C++11 [class.dtor]p5:
10102 // -- for a virtual destructor, lookup of the non-array deallocation function
10103 // results in an ambiguity or in a function that is deleted or inaccessible
10104 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10105 FunctionDecl *OperatorDelete = nullptr;
10106 CanQualType DeallocType = Context.getCanonicalTagType(TD: RD);
10107 DeclarationName Name =
10108 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
10109 ImplicitDeallocationParameters IDP = {
10110 DeallocType, ShouldUseTypeAwareOperatorNewOrDelete(),
10111 AlignedAllocationMode::No, SizedDeallocationMode::No};
10112 if (FindDeallocationFunction(StartLoc: MD->getLocation(), RD: MD->getParent(), Name,
10113 Operator&: OperatorDelete, IDP,
10114 /*Diagnose=*/false)) {
10115 if (Diagnose)
10116 Diag(Loc: RD->getLocation(), DiagID: diag::note_deleted_dtor_no_operator_delete);
10117 return true;
10118 }
10119 }
10120
10121 SpecialMemberDeletionInfo SMI(*this, MD, CSM, ICI, Diagnose);
10122
10123 // Per DR1611, do not consider virtual bases of constructors of abstract
10124 // classes, since we are not going to construct them.
10125 // Per DR1658, do not consider virtual bases of destructors of abstract
10126 // classes either.
10127 // Per DR2180, for assignment operators we only assign (and thus only
10128 // consider) direct bases.
10129 if (SMI.visit(Bases: SMI.IsAssignment ? SMI.VisitDirectBases
10130 : SMI.VisitPotentiallyConstructedBases))
10131 return true;
10132
10133 if (SMI.shouldDeleteForAllConstMembers())
10134 return true;
10135
10136 if (getLangOpts().CUDA) {
10137 // We should delete the special member in CUDA mode if target inference
10138 // failed.
10139 // For inherited constructors (non-null ICI), CSM may be passed so that MD
10140 // is treated as certain special member, which may not reflect what special
10141 // member MD really is. However inferTargetForImplicitSpecialMember
10142 // expects CSM to match MD, therefore recalculate CSM.
10143 assert(ICI || CSM == MD->getSpecialMemberKind());
10144 auto RealCSM = CSM;
10145 if (ICI)
10146 RealCSM = MD->getSpecialMemberKind();
10147
10148 return CUDA().inferTargetForImplicitSpecialMember(ClassDecl: RD, CSM: RealCSM, MemberDecl: MD,
10149 ConstRHS: SMI.ConstArg, Diagnose);
10150 }
10151
10152 return false;
10153}
10154
10155void Sema::DiagnoseDeletedDefaultedFunction(FunctionDecl *FD) {
10156 FunctionDecl::DefaultedFunctionKind DFK = FD->getDefaultedFunctionKind();
10157 assert(DFK && "not a defaultable function");
10158 assert(FD->isDefaulted() && FD->isDeleted() && "not defaulted and deleted");
10159
10160 if (DFK.isSpecialMember()) {
10161 ShouldDeleteSpecialMember(MD: cast<CXXMethodDecl>(Val: FD), CSM: DFK.asSpecialMember(),
10162 ICI: nullptr, /*Diagnose=*/true);
10163 } else {
10164 DefaultedComparisonAnalyzer(
10165 *this, cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()), FD,
10166 DFK.asComparison(), DefaultedComparisonAnalyzer::ExplainDeleted)
10167 .visit();
10168 }
10169}
10170
10171/// Perform lookup for a special member of the specified kind, and determine
10172/// whether it is trivial. If the triviality can be determined without the
10173/// lookup, skip it. This is intended for use when determining whether a
10174/// special member of a containing object is trivial, and thus does not ever
10175/// perform overload resolution for default constructors.
10176///
10177/// If \p Selected is not \c NULL, \c *Selected will be filled in with the
10178/// member that was most likely to be intended to be trivial, if any.
10179///
10180/// If \p ForCall is true, look at CXXRecord::HasTrivialSpecialMembersForCall to
10181/// determine whether the special member is trivial.
10182static bool findTrivialSpecialMember(Sema &S, CXXRecordDecl *RD,
10183 CXXSpecialMemberKind CSM, unsigned Quals,
10184 bool ConstRHS, TrivialABIHandling TAH,
10185 CXXMethodDecl **Selected) {
10186 if (Selected)
10187 *Selected = nullptr;
10188
10189 switch (CSM) {
10190 case CXXSpecialMemberKind::Invalid:
10191 llvm_unreachable("not a special member");
10192
10193 case CXXSpecialMemberKind::DefaultConstructor:
10194 // C++11 [class.ctor]p5:
10195 // A default constructor is trivial if:
10196 // - all the [direct subobjects] have trivial default constructors
10197 //
10198 // Note, no overload resolution is performed in this case.
10199 if (RD->hasTrivialDefaultConstructor())
10200 return true;
10201
10202 if (Selected) {
10203 // If there's a default constructor which could have been trivial, dig it
10204 // out. Otherwise, if there's any user-provided default constructor, point
10205 // to that as an example of why there's not a trivial one.
10206 CXXConstructorDecl *DefCtor = nullptr;
10207 if (RD->needsImplicitDefaultConstructor())
10208 S.DeclareImplicitDefaultConstructor(ClassDecl: RD);
10209 for (auto *CI : RD->ctors()) {
10210 if (!CI->isDefaultConstructor())
10211 continue;
10212 DefCtor = CI;
10213 if (!DefCtor->isUserProvided())
10214 break;
10215 }
10216
10217 *Selected = DefCtor;
10218 }
10219
10220 return false;
10221
10222 case CXXSpecialMemberKind::Destructor:
10223 // C++11 [class.dtor]p5:
10224 // A destructor is trivial if:
10225 // - all the direct [subobjects] have trivial destructors
10226 if (RD->hasTrivialDestructor() ||
10227 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10228 RD->hasTrivialDestructorForCall()))
10229 return true;
10230
10231 if (Selected) {
10232 if (RD->needsImplicitDestructor())
10233 S.DeclareImplicitDestructor(ClassDecl: RD);
10234 *Selected = RD->getDestructor();
10235 }
10236
10237 return false;
10238
10239 case CXXSpecialMemberKind::CopyConstructor:
10240 // C++11 [class.copy]p12:
10241 // A copy constructor is trivial if:
10242 // - the constructor selected to copy each direct [subobject] is trivial
10243 if (RD->hasTrivialCopyConstructor() ||
10244 (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10245 RD->hasTrivialCopyConstructorForCall())) {
10246 if (Quals == Qualifiers::Const)
10247 // We must either select the trivial copy constructor or reach an
10248 // ambiguity; no need to actually perform overload resolution.
10249 return true;
10250 } else if (!Selected) {
10251 return false;
10252 }
10253 // In C++98, we are not supposed to perform overload resolution here, but we
10254 // treat that as a language defect, as suggested on cxx-abi-dev, to treat
10255 // cases like B as having a non-trivial copy constructor:
10256 // struct A { template<typename T> A(T&); };
10257 // struct B { mutable A a; };
10258 goto NeedOverloadResolution;
10259
10260 case CXXSpecialMemberKind::CopyAssignment:
10261 // C++11 [class.copy]p25:
10262 // A copy assignment operator is trivial if:
10263 // - the assignment operator selected to copy each direct [subobject] is
10264 // trivial
10265 if (RD->hasTrivialCopyAssignment()) {
10266 if (Quals == Qualifiers::Const)
10267 return true;
10268 } else if (!Selected) {
10269 return false;
10270 }
10271 // In C++98, we are not supposed to perform overload resolution here, but we
10272 // treat that as a language defect.
10273 goto NeedOverloadResolution;
10274
10275 case CXXSpecialMemberKind::MoveConstructor:
10276 case CXXSpecialMemberKind::MoveAssignment:
10277 NeedOverloadResolution:
10278 Sema::SpecialMemberOverloadResult SMOR =
10279 lookupCallFromSpecialMember(S, Class: RD, CSM, FieldQuals: Quals, ConstRHS);
10280
10281 // The standard doesn't describe how to behave if the lookup is ambiguous.
10282 // We treat it as not making the member non-trivial, just like the standard
10283 // mandates for the default constructor. This should rarely matter, because
10284 // the member will also be deleted.
10285 if (SMOR.getKind() == Sema::SpecialMemberOverloadResult::Ambiguous)
10286 return true;
10287
10288 if (!SMOR.getMethod()) {
10289 assert(SMOR.getKind() ==
10290 Sema::SpecialMemberOverloadResult::NoMemberOrDeleted);
10291 return false;
10292 }
10293
10294 // We deliberately don't check if we found a deleted special member. We're
10295 // not supposed to!
10296 if (Selected)
10297 *Selected = SMOR.getMethod();
10298
10299 if (TAH == TrivialABIHandling::ConsiderTrivialABI &&
10300 (CSM == CXXSpecialMemberKind::CopyConstructor ||
10301 CSM == CXXSpecialMemberKind::MoveConstructor))
10302 return SMOR.getMethod()->isTrivialForCall();
10303 return SMOR.getMethod()->isTrivial();
10304 }
10305
10306 llvm_unreachable("unknown special method kind");
10307}
10308
10309static CXXConstructorDecl *findUserDeclaredCtor(CXXRecordDecl *RD) {
10310 for (auto *CI : RD->ctors())
10311 if (!CI->isImplicit())
10312 return CI;
10313
10314 // Look for constructor templates.
10315 typedef CXXRecordDecl::specific_decl_iterator<FunctionTemplateDecl> tmpl_iter;
10316 for (tmpl_iter TI(RD->decls_begin()), TE(RD->decls_end()); TI != TE; ++TI) {
10317 if (CXXConstructorDecl *CD =
10318 dyn_cast<CXXConstructorDecl>(Val: TI->getTemplatedDecl()))
10319 return CD;
10320 }
10321
10322 return nullptr;
10323}
10324
10325/// The kind of subobject we are checking for triviality. The values of this
10326/// enumeration are used in diagnostics.
10327enum TrivialSubobjectKind {
10328 /// The subobject is a base class.
10329 TSK_BaseClass,
10330 /// The subobject is a non-static data member.
10331 TSK_Field,
10332 /// The object is actually the complete object.
10333 TSK_CompleteObject
10334};
10335
10336/// Check whether the special member selected for a given type would be trivial.
10337static bool checkTrivialSubobjectCall(Sema &S, SourceLocation SubobjLoc,
10338 QualType SubType, bool ConstRHS,
10339 CXXSpecialMemberKind CSM,
10340 TrivialSubobjectKind Kind,
10341 TrivialABIHandling TAH, bool Diagnose) {
10342 CXXRecordDecl *SubRD = SubType->getAsCXXRecordDecl();
10343 if (!SubRD)
10344 return true;
10345
10346 CXXMethodDecl *Selected;
10347 if (findTrivialSpecialMember(S, RD: SubRD, CSM, Quals: SubType.getCVRQualifiers(),
10348 ConstRHS, TAH, Selected: Diagnose ? &Selected : nullptr))
10349 return true;
10350
10351 if (Diagnose) {
10352 if (ConstRHS)
10353 SubType.addConst();
10354
10355 if (!Selected && CSM == CXXSpecialMemberKind::DefaultConstructor) {
10356 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_def_ctor)
10357 << Kind << SubType.getUnqualifiedType();
10358 if (CXXConstructorDecl *CD = findUserDeclaredCtor(RD: SubRD))
10359 S.Diag(Loc: CD->getLocation(), DiagID: diag::note_user_declared_ctor);
10360 } else if (!Selected)
10361 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_no_copy)
10362 << Kind << SubType.getUnqualifiedType() << CSM << SubType;
10363 else if (Selected->isUserProvided()) {
10364 if (Kind == TSK_CompleteObject)
10365 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_nontrivial_user_provided)
10366 << Kind << SubType.getUnqualifiedType() << CSM;
10367 else {
10368 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_user_provided)
10369 << Kind << SubType.getUnqualifiedType() << CSM;
10370 S.Diag(Loc: Selected->getLocation(), DiagID: diag::note_declared_at);
10371 }
10372 } else {
10373 if (Kind != TSK_CompleteObject)
10374 S.Diag(Loc: SubobjLoc, DiagID: diag::note_nontrivial_subobject)
10375 << Kind << SubType.getUnqualifiedType() << CSM;
10376
10377 // Explain why the defaulted or deleted special member isn't trivial.
10378 S.SpecialMemberIsTrivial(MD: Selected, CSM,
10379 TAH: TrivialABIHandling::IgnoreTrivialABI, Diagnose);
10380 }
10381 }
10382
10383 return false;
10384}
10385
10386/// Check whether the members of a class type allow a special member to be
10387/// trivial.
10388static bool checkTrivialClassMembers(Sema &S, CXXRecordDecl *RD,
10389 CXXSpecialMemberKind CSM, bool ConstArg,
10390 TrivialABIHandling TAH, bool Diagnose) {
10391 for (const auto *FI : RD->fields()) {
10392 if (FI->isInvalidDecl() || FI->isUnnamedBitField())
10393 continue;
10394
10395 QualType FieldType = S.Context.getBaseElementType(QT: FI->getType());
10396
10397 // Pretend anonymous struct or union members are members of this class.
10398 if (FI->isAnonymousStructOrUnion()) {
10399 if (!checkTrivialClassMembers(S, RD: FieldType->getAsCXXRecordDecl(),
10400 CSM, ConstArg, TAH, Diagnose))
10401 return false;
10402 continue;
10403 }
10404
10405 // C++11 [class.ctor]p5:
10406 // A default constructor is trivial if [...]
10407 // -- no non-static data member of its class has a
10408 // brace-or-equal-initializer
10409 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
10410 FI->hasInClassInitializer()) {
10411 if (Diagnose)
10412 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_default_member_init)
10413 << FI;
10414 return false;
10415 }
10416
10417 // Objective C ARC 4.3.5:
10418 // [...] nontrivally ownership-qualified types are [...] not trivially
10419 // default constructible, copy constructible, move constructible, copy
10420 // assignable, move assignable, or destructible [...]
10421 if (FieldType.hasNonTrivialObjCLifetime()) {
10422 if (Diagnose)
10423 S.Diag(Loc: FI->getLocation(), DiagID: diag::note_nontrivial_objc_ownership)
10424 << RD << FieldType.getObjCLifetime();
10425 return false;
10426 }
10427
10428 bool ConstRHS = ConstArg && !FI->isMutable();
10429 if (!checkTrivialSubobjectCall(S, SubobjLoc: FI->getLocation(), SubType: FieldType, ConstRHS,
10430 CSM, Kind: TSK_Field, TAH, Diagnose))
10431 return false;
10432 }
10433
10434 return true;
10435}
10436
10437void Sema::DiagnoseNontrivial(const CXXRecordDecl *RD,
10438 CXXSpecialMemberKind CSM) {
10439 CanQualType Ty = Context.getCanonicalTagType(TD: RD);
10440
10441 bool ConstArg = (CSM == CXXSpecialMemberKind::CopyConstructor ||
10442 CSM == CXXSpecialMemberKind::CopyAssignment);
10443 checkTrivialSubobjectCall(S&: *this, SubobjLoc: RD->getLocation(), SubType: Ty, ConstRHS: ConstArg, CSM,
10444 Kind: TSK_CompleteObject,
10445 TAH: TrivialABIHandling::IgnoreTrivialABI,
10446 /*Diagnose*/ true);
10447}
10448
10449bool Sema::SpecialMemberIsTrivial(CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
10450 TrivialABIHandling TAH, bool Diagnose) {
10451 assert(!MD->isUserProvided() && CSM != CXXSpecialMemberKind::Invalid &&
10452 "not special enough");
10453
10454 CXXRecordDecl *RD = MD->getParent();
10455
10456 bool ConstArg = false;
10457
10458 // C++11 [class.copy]p12, p25: [DR1593]
10459 // A [special member] is trivial if [...] its parameter-type-list is
10460 // equivalent to the parameter-type-list of an implicit declaration [...]
10461 switch (CSM) {
10462 case CXXSpecialMemberKind::DefaultConstructor:
10463 case CXXSpecialMemberKind::Destructor:
10464 // Trivial default constructors and destructors cannot have parameters.
10465 break;
10466
10467 case CXXSpecialMemberKind::CopyConstructor:
10468 case CXXSpecialMemberKind::CopyAssignment: {
10469 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10470 const ReferenceType *RT = Param0->getType()->getAs<ReferenceType>();
10471
10472 // When ClangABICompat14 is true, CXX copy constructors will only be trivial
10473 // if they are not user-provided and their parameter-type-list is equivalent
10474 // to the parameter-type-list of an implicit declaration. This maintains the
10475 // behavior before dr2171 was implemented.
10476 //
10477 // Otherwise, if ClangABICompat14 is false, All copy constructors can be
10478 // trivial, if they are not user-provided, regardless of the qualifiers on
10479 // the reference type.
10480 const bool ClangABICompat14 =
10481 Context.getLangOpts().isCompatibleWith(Version: LangOptions::ClangABI::Ver14);
10482 if (!RT ||
10483 ((RT->getPointeeType().getCVRQualifiers() != Qualifiers::Const) &&
10484 ClangABICompat14)) {
10485 if (Diagnose)
10486 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10487 << Param0->getSourceRange() << Param0->getType()
10488 << Context.getLValueReferenceType(
10489 T: Context.getCanonicalTagType(TD: RD).withConst());
10490 return false;
10491 }
10492
10493 ConstArg = RT->getPointeeType().isConstQualified();
10494 break;
10495 }
10496
10497 case CXXSpecialMemberKind::MoveConstructor:
10498 case CXXSpecialMemberKind::MoveAssignment: {
10499 // Trivial move operations always have non-cv-qualified parameters.
10500 const ParmVarDecl *Param0 = MD->getNonObjectParameter(I: 0);
10501 const RValueReferenceType *RT =
10502 Param0->getType()->getAs<RValueReferenceType>();
10503 if (!RT || RT->getPointeeType().getCVRQualifiers()) {
10504 if (Diagnose)
10505 Diag(Loc: Param0->getLocation(), DiagID: diag::note_nontrivial_param_type)
10506 << Param0->getSourceRange() << Param0->getType()
10507 << Context.getRValueReferenceType(T: Context.getCanonicalTagType(TD: RD));
10508 return false;
10509 }
10510 break;
10511 }
10512
10513 case CXXSpecialMemberKind::Invalid:
10514 llvm_unreachable("not a special member");
10515 }
10516
10517 if (MD->getMinRequiredArguments() < MD->getNumParams()) {
10518 if (Diagnose)
10519 Diag(Loc: MD->getParamDecl(i: MD->getMinRequiredArguments())->getLocation(),
10520 DiagID: diag::note_nontrivial_default_arg)
10521 << MD->getParamDecl(i: MD->getMinRequiredArguments())->getSourceRange();
10522 return false;
10523 }
10524 if (MD->isVariadic()) {
10525 if (Diagnose)
10526 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_variadic);
10527 return false;
10528 }
10529
10530 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10531 // A copy/move [constructor or assignment operator] is trivial if
10532 // -- the [member] selected to copy/move each direct base class subobject
10533 // is trivial
10534 //
10535 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10536 // A [default constructor or destructor] is trivial if
10537 // -- all the direct base classes have trivial [default constructors or
10538 // destructors]
10539 for (const auto &BI : RD->bases())
10540 if (!checkTrivialSubobjectCall(S&: *this, SubobjLoc: BI.getBeginLoc(), SubType: BI.getType(),
10541 ConstRHS: ConstArg, CSM, Kind: TSK_BaseClass, TAH, Diagnose))
10542 return false;
10543
10544 // C++11 [class.ctor]p5, C++11 [class.dtor]p5:
10545 // A copy/move [constructor or assignment operator] for a class X is
10546 // trivial if
10547 // -- for each non-static data member of X that is of class type (or array
10548 // thereof), the constructor selected to copy/move that member is
10549 // trivial
10550 //
10551 // C++11 [class.copy]p12, C++11 [class.copy]p25:
10552 // A [default constructor or destructor] is trivial if
10553 // -- for all of the non-static data members of its class that are of class
10554 // type (or array thereof), each such class has a trivial [default
10555 // constructor or destructor]
10556 if (!checkTrivialClassMembers(S&: *this, RD, CSM, ConstArg, TAH, Diagnose))
10557 return false;
10558
10559 // C++11 [class.dtor]p5:
10560 // A destructor is trivial if [...]
10561 // -- the destructor is not virtual
10562 if (CSM == CXXSpecialMemberKind::Destructor && MD->isVirtual()) {
10563 if (Diagnose)
10564 Diag(Loc: MD->getLocation(), DiagID: diag::note_nontrivial_virtual_dtor) << RD;
10565 return false;
10566 }
10567
10568 // C++11 [class.ctor]p5, C++11 [class.copy]p12, C++11 [class.copy]p25:
10569 // A [special member] for class X is trivial if [...]
10570 // -- class X has no virtual functions and no virtual base classes
10571 if (CSM != CXXSpecialMemberKind::Destructor &&
10572 MD->getParent()->isDynamicClass()) {
10573 if (!Diagnose)
10574 return false;
10575
10576 if (RD->getNumVBases()) {
10577 // Check for virtual bases. We already know that the corresponding
10578 // member in all bases is trivial, so vbases must all be direct.
10579 CXXBaseSpecifier &BS = *RD->vbases_begin();
10580 assert(BS.isVirtual());
10581 Diag(Loc: BS.getBeginLoc(), DiagID: diag::note_nontrivial_has_virtual) << RD << 1;
10582 return false;
10583 }
10584
10585 // Must have a virtual method.
10586 for (const auto *MI : RD->methods()) {
10587 if (MI->isVirtual()) {
10588 SourceLocation MLoc = MI->getBeginLoc();
10589 Diag(Loc: MLoc, DiagID: diag::note_nontrivial_has_virtual) << RD << 0;
10590 return false;
10591 }
10592 }
10593
10594 llvm_unreachable("dynamic class with no vbases and no virtual functions");
10595 }
10596
10597 // Looks like it's trivial!
10598 return true;
10599}
10600
10601namespace {
10602struct FindHiddenVirtualMethod {
10603 Sema *S;
10604 CXXMethodDecl *Method;
10605 llvm::SmallPtrSet<const CXXMethodDecl *, 8> OverridenAndUsingBaseMethods;
10606 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10607
10608private:
10609 /// Check whether any most overridden method from MD in Methods
10610 static bool CheckMostOverridenMethods(
10611 const CXXMethodDecl *MD,
10612 const llvm::SmallPtrSetImpl<const CXXMethodDecl *> &Methods) {
10613 if (MD->size_overridden_methods() == 0)
10614 return Methods.count(Ptr: MD->getCanonicalDecl());
10615 for (const CXXMethodDecl *O : MD->overridden_methods())
10616 if (CheckMostOverridenMethods(MD: O, Methods))
10617 return true;
10618 return false;
10619 }
10620
10621public:
10622 /// Member lookup function that determines whether a given C++
10623 /// method overloads virtual methods in a base class without overriding any,
10624 /// to be used with CXXRecordDecl::lookupInBases().
10625 bool operator()(const CXXBaseSpecifier *Specifier, CXXBasePath &Path) {
10626 auto *BaseRecord = Specifier->getType()->castAsRecordDecl();
10627 DeclarationName Name = Method->getDeclName();
10628 assert(Name.getNameKind() == DeclarationName::Identifier);
10629
10630 bool foundSameNameMethod = false;
10631 SmallVector<CXXMethodDecl *, 8> overloadedMethods;
10632 for (Path.Decls = BaseRecord->lookup(Name).begin();
10633 Path.Decls != DeclContext::lookup_iterator(); ++Path.Decls) {
10634 NamedDecl *D = *Path.Decls;
10635 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
10636 MD = MD->getCanonicalDecl();
10637 foundSameNameMethod = true;
10638 // Interested only in hidden virtual methods.
10639 if (!MD->isVirtual())
10640 continue;
10641 // If the method we are checking overrides a method from its base
10642 // don't warn about the other overloaded methods. Clang deviates from
10643 // GCC by only diagnosing overloads of inherited virtual functions that
10644 // do not override any other virtual functions in the base. GCC's
10645 // -Woverloaded-virtual diagnoses any derived function hiding a virtual
10646 // function from a base class. These cases may be better served by a
10647 // warning (not specific to virtual functions) on call sites when the
10648 // call would select a different function from the base class, were it
10649 // visible.
10650 // See FIXME in test/SemaCXX/warn-overload-virtual.cpp for an example.
10651 if (!S->IsOverload(New: Method, Old: MD, UseMemberUsingDeclRules: false))
10652 return true;
10653 // Collect the overload only if its hidden.
10654 if (!CheckMostOverridenMethods(MD, Methods: OverridenAndUsingBaseMethods))
10655 overloadedMethods.push_back(Elt: MD);
10656 }
10657 }
10658
10659 if (foundSameNameMethod)
10660 OverloadedMethods.append(in_start: overloadedMethods.begin(),
10661 in_end: overloadedMethods.end());
10662 return foundSameNameMethod;
10663 }
10664};
10665} // end anonymous namespace
10666
10667/// Add the most overridden methods from MD to Methods
10668static void AddMostOverridenMethods(const CXXMethodDecl *MD,
10669 llvm::SmallPtrSetImpl<const CXXMethodDecl *>& Methods) {
10670 if (MD->size_overridden_methods() == 0)
10671 Methods.insert(Ptr: MD->getCanonicalDecl());
10672 else
10673 for (const CXXMethodDecl *O : MD->overridden_methods())
10674 AddMostOverridenMethods(MD: O, Methods);
10675}
10676
10677void Sema::FindHiddenVirtualMethods(CXXMethodDecl *MD,
10678 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10679 if (!MD->getDeclName().isIdentifier())
10680 return;
10681
10682 CXXBasePaths Paths(/*FindAmbiguities=*/true, // true to look in all bases.
10683 /*bool RecordPaths=*/false,
10684 /*bool DetectVirtual=*/false);
10685 FindHiddenVirtualMethod FHVM;
10686 FHVM.Method = MD;
10687 FHVM.S = this;
10688
10689 // Keep the base methods that were overridden or introduced in the subclass
10690 // by 'using' in a set. A base method not in this set is hidden.
10691 CXXRecordDecl *DC = MD->getParent();
10692 for (NamedDecl *ND : DC->lookup(Name: MD->getDeclName())) {
10693 if (UsingShadowDecl *shad = dyn_cast<UsingShadowDecl>(Val: ND))
10694 ND = shad->getTargetDecl();
10695 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: ND))
10696 AddMostOverridenMethods(MD, Methods&: FHVM.OverridenAndUsingBaseMethods);
10697 }
10698
10699 if (DC->lookupInBases(BaseMatches: FHVM, Paths))
10700 OverloadedMethods = FHVM.OverloadedMethods;
10701}
10702
10703void Sema::NoteHiddenVirtualMethods(CXXMethodDecl *MD,
10704 SmallVectorImpl<CXXMethodDecl*> &OverloadedMethods) {
10705 for (const CXXMethodDecl *overloadedMD : OverloadedMethods) {
10706 PartialDiagnostic PD = PDiag(
10707 DiagID: diag::note_hidden_overloaded_virtual_declared_here) << overloadedMD;
10708 HandleFunctionTypeMismatch(PDiag&: PD, FromType: MD->getType(), ToType: overloadedMD->getType());
10709 Diag(Loc: overloadedMD->getLocation(), PD);
10710 }
10711}
10712
10713void Sema::DiagnoseHiddenVirtualMethods(CXXMethodDecl *MD) {
10714 if (MD->isInvalidDecl())
10715 return;
10716
10717 if (Diags.isIgnored(DiagID: diag::warn_overloaded_virtual, Loc: MD->getLocation()))
10718 return;
10719
10720 SmallVector<CXXMethodDecl *, 8> OverloadedMethods;
10721 FindHiddenVirtualMethods(MD, OverloadedMethods);
10722 if (!OverloadedMethods.empty()) {
10723 Diag(Loc: MD->getLocation(), DiagID: diag::warn_overloaded_virtual)
10724 << MD << (OverloadedMethods.size() > 1);
10725
10726 NoteHiddenVirtualMethods(MD, OverloadedMethods);
10727 }
10728}
10729
10730void Sema::checkIllFormedTrivialABIStruct(CXXRecordDecl &RD) {
10731 auto PrintDiagAndRemoveAttr = [&](unsigned N) {
10732 // No diagnostics if this is a template instantiation.
10733 if (!isTemplateInstantiation(Kind: RD.getTemplateSpecializationKind())) {
10734 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10735 DiagID: diag::ext_cannot_use_trivial_abi) << &RD;
10736 Diag(Loc: RD.getAttr<TrivialABIAttr>()->getLocation(),
10737 DiagID: diag::note_cannot_use_trivial_abi_reason) << &RD << N;
10738 }
10739 RD.dropAttr<TrivialABIAttr>();
10740 };
10741
10742 // Ill-formed if the struct has virtual functions.
10743 if (RD.isPolymorphic()) {
10744 PrintDiagAndRemoveAttr(1);
10745 return;
10746 }
10747
10748 for (const auto &B : RD.bases()) {
10749 // Ill-formed if the base class is non-trivial for the purpose of calls or a
10750 // virtual base.
10751 if (!B.getType()->isDependentType() &&
10752 !B.getType()->getAsCXXRecordDecl()->canPassInRegisters()) {
10753 PrintDiagAndRemoveAttr(2);
10754 return;
10755 }
10756
10757 if (B.isVirtual()) {
10758 PrintDiagAndRemoveAttr(3);
10759 return;
10760 }
10761 }
10762
10763 for (const auto *FD : RD.fields()) {
10764 // Ill-formed if the field is an ObjectiveC pointer or of a type that is
10765 // non-trivial for the purpose of calls.
10766 QualType FT = FD->getType();
10767 if (FT.getObjCLifetime() == Qualifiers::OCL_Weak) {
10768 PrintDiagAndRemoveAttr(4);
10769 return;
10770 }
10771
10772 // Ill-formed if the field is an address-discriminated value.
10773 if (FT.hasAddressDiscriminatedPointerAuth()) {
10774 PrintDiagAndRemoveAttr(6);
10775 return;
10776 }
10777
10778 if (const auto *RT =
10779 FT->getBaseElementTypeUnsafe()->getAsCanonical<RecordType>())
10780 if (!RT->isDependentType() &&
10781 !cast<CXXRecordDecl>(Val: RT->getDecl()->getDefinitionOrSelf())
10782 ->canPassInRegisters()) {
10783 PrintDiagAndRemoveAttr(5);
10784 return;
10785 }
10786 }
10787
10788 if (IsCXXTriviallyRelocatableType(RD))
10789 return;
10790
10791 // Ill-formed if the copy and move constructors are deleted.
10792 auto HasNonDeletedCopyOrMoveConstructor = [&]() {
10793 // If the type is dependent, then assume it might have
10794 // implicit copy or move ctor because we won't know yet at this point.
10795 if (RD.isDependentType())
10796 return true;
10797 if (RD.needsImplicitCopyConstructor() &&
10798 !RD.defaultedCopyConstructorIsDeleted())
10799 return true;
10800 if (RD.needsImplicitMoveConstructor() &&
10801 !RD.defaultedMoveConstructorIsDeleted())
10802 return true;
10803 for (const CXXConstructorDecl *CD : RD.ctors())
10804 if (CD->isCopyOrMoveConstructor() && !CD->isDeleted())
10805 return true;
10806 return false;
10807 };
10808
10809 if (!HasNonDeletedCopyOrMoveConstructor()) {
10810 PrintDiagAndRemoveAttr(0);
10811 return;
10812 }
10813}
10814
10815void Sema::checkIncorrectVTablePointerAuthenticationAttribute(
10816 CXXRecordDecl &RD) {
10817 if (RequireCompleteType(Loc: RD.getLocation(), T: Context.getCanonicalTagType(TD: &RD),
10818 DiagID: diag::err_incomplete_type_vtable_pointer_auth))
10819 return;
10820
10821 const CXXRecordDecl *PrimaryBase = &RD;
10822 if (PrimaryBase->hasAnyDependentBases())
10823 return;
10824
10825 while (1) {
10826 assert(PrimaryBase);
10827 const CXXRecordDecl *Base = nullptr;
10828 for (const CXXBaseSpecifier &BasePtr : PrimaryBase->bases()) {
10829 if (!BasePtr.getType()->getAsCXXRecordDecl()->isDynamicClass())
10830 continue;
10831 Base = BasePtr.getType()->getAsCXXRecordDecl();
10832 break;
10833 }
10834 if (!Base || Base == PrimaryBase || !Base->isPolymorphic())
10835 break;
10836 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10837 DiagID: diag::err_non_top_level_vtable_pointer_auth)
10838 << &RD << Base;
10839 PrimaryBase = Base;
10840 }
10841
10842 if (!RD.isPolymorphic())
10843 Diag(Loc: RD.getAttr<VTablePointerAuthenticationAttr>()->getLocation(),
10844 DiagID: diag::err_non_polymorphic_vtable_pointer_auth)
10845 << &RD;
10846}
10847
10848void Sema::ActOnFinishCXXMemberSpecification(
10849 Scope *S, SourceLocation RLoc, Decl *TagDecl, SourceLocation LBrac,
10850 SourceLocation RBrac, const ParsedAttributesView &AttrList) {
10851 if (!TagDecl)
10852 return;
10853
10854 AdjustDeclIfTemplate(Decl&: TagDecl);
10855
10856 for (const ParsedAttr &AL : AttrList) {
10857 if (AL.getKind() != ParsedAttr::AT_Visibility)
10858 continue;
10859 AL.setInvalid();
10860 Diag(Loc: AL.getLoc(), DiagID: diag::warn_attribute_after_definition_ignored) << AL;
10861 }
10862
10863 ActOnFields(S, RecLoc: RLoc, TagDecl,
10864 Fields: llvm::ArrayRef(
10865 // strict aliasing violation!
10866 reinterpret_cast<Decl **>(FieldCollector->getCurFields()),
10867 FieldCollector->getCurNumFields()),
10868 LBrac, RBrac, AttrList);
10869
10870 CheckCompletedCXXClass(S, Record: cast<CXXRecordDecl>(Val: TagDecl));
10871}
10872
10873/// Find the equality comparison functions that should be implicitly declared
10874/// in a given class definition, per C++2a [class.compare.default]p3.
10875static void findImplicitlyDeclaredEqualityComparisons(
10876 ASTContext &Ctx, CXXRecordDecl *RD,
10877 llvm::SmallVectorImpl<FunctionDecl *> &Spaceships) {
10878 DeclarationName EqEq = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_EqualEqual);
10879 if (!RD->lookup(Name: EqEq).empty())
10880 // Member operator== explicitly declared: no implicit operator==s.
10881 return;
10882
10883 // Traverse friends looking for an '==' or a '<=>'.
10884 for (FriendDecl *Friend : RD->friends()) {
10885 FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(Val: Friend->getFriendDecl());
10886 if (!FD) continue;
10887
10888 if (FD->getOverloadedOperator() == OO_EqualEqual) {
10889 // Friend operator== explicitly declared: no implicit operator==s.
10890 Spaceships.clear();
10891 return;
10892 }
10893
10894 if (FD->getOverloadedOperator() == OO_Spaceship &&
10895 FD->isExplicitlyDefaulted())
10896 Spaceships.push_back(Elt: FD);
10897 }
10898
10899 // Look for members named 'operator<=>'.
10900 DeclarationName Cmp = Ctx.DeclarationNames.getCXXOperatorName(Op: OO_Spaceship);
10901 for (NamedDecl *ND : RD->lookup(Name: Cmp)) {
10902 // Note that we could find a non-function here (either a function template
10903 // or a using-declaration). Neither case results in an implicit
10904 // 'operator=='.
10905 if (auto *FD = dyn_cast<FunctionDecl>(Val: ND))
10906 if (FD->isExplicitlyDefaulted())
10907 Spaceships.push_back(Elt: FD);
10908 }
10909}
10910
10911void Sema::AddImplicitlyDeclaredMembersToClass(CXXRecordDecl *ClassDecl) {
10912 // Don't add implicit special members to templated classes.
10913 // FIXME: This means unqualified lookups for 'operator=' within a class
10914 // template don't work properly.
10915 if (!ClassDecl->isDependentType()) {
10916 if (ClassDecl->needsImplicitDefaultConstructor()) {
10917 ++getASTContext().NumImplicitDefaultConstructors;
10918
10919 if (ClassDecl->hasInheritedConstructor())
10920 DeclareImplicitDefaultConstructor(ClassDecl);
10921 }
10922
10923 if (ClassDecl->needsImplicitCopyConstructor()) {
10924 ++getASTContext().NumImplicitCopyConstructors;
10925
10926 // If the properties or semantics of the copy constructor couldn't be
10927 // determined while the class was being declared, force a declaration
10928 // of it now.
10929 if (ClassDecl->needsOverloadResolutionForCopyConstructor() ||
10930 ClassDecl->hasInheritedConstructor())
10931 DeclareImplicitCopyConstructor(ClassDecl);
10932 // For the MS ABI we need to know whether the copy ctor is deleted. A
10933 // prerequisite for deleting the implicit copy ctor is that the class has
10934 // a move ctor or move assignment that is either user-declared or whose
10935 // semantics are inherited from a subobject. FIXME: We should provide a
10936 // more direct way for CodeGen to ask whether the constructor was deleted.
10937 else if (Context.getTargetInfo().getCXXABI().isMicrosoft() &&
10938 (ClassDecl->hasUserDeclaredMoveConstructor() ||
10939 ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10940 ClassDecl->hasUserDeclaredMoveAssignment() ||
10941 ClassDecl->needsOverloadResolutionForMoveAssignment()))
10942 DeclareImplicitCopyConstructor(ClassDecl);
10943 }
10944
10945 if (getLangOpts().CPlusPlus11 &&
10946 ClassDecl->needsImplicitMoveConstructor()) {
10947 ++getASTContext().NumImplicitMoveConstructors;
10948
10949 if (ClassDecl->needsOverloadResolutionForMoveConstructor() ||
10950 ClassDecl->hasInheritedConstructor())
10951 DeclareImplicitMoveConstructor(ClassDecl);
10952 }
10953
10954 if (ClassDecl->needsImplicitCopyAssignment()) {
10955 ++getASTContext().NumImplicitCopyAssignmentOperators;
10956
10957 // If we have a dynamic class, then the copy assignment operator may be
10958 // virtual, so we have to declare it immediately. This ensures that, e.g.,
10959 // it shows up in the right place in the vtable and that we diagnose
10960 // problems with the implicit exception specification.
10961 if (ClassDecl->isDynamicClass() ||
10962 ClassDecl->needsOverloadResolutionForCopyAssignment() ||
10963 ClassDecl->hasInheritedAssignment())
10964 DeclareImplicitCopyAssignment(ClassDecl);
10965 }
10966
10967 if (getLangOpts().CPlusPlus11 && ClassDecl->needsImplicitMoveAssignment()) {
10968 ++getASTContext().NumImplicitMoveAssignmentOperators;
10969
10970 // Likewise for the move assignment operator.
10971 if (ClassDecl->isDynamicClass() ||
10972 ClassDecl->needsOverloadResolutionForMoveAssignment() ||
10973 ClassDecl->hasInheritedAssignment())
10974 DeclareImplicitMoveAssignment(ClassDecl);
10975 }
10976
10977 if (ClassDecl->needsImplicitDestructor()) {
10978 ++getASTContext().NumImplicitDestructors;
10979
10980 // If we have a dynamic class, then the destructor may be virtual, so we
10981 // have to declare the destructor immediately. This ensures that, e.g., it
10982 // shows up in the right place in the vtable and that we diagnose problems
10983 // with the implicit exception specification.
10984 if (ClassDecl->isDynamicClass() ||
10985 ClassDecl->needsOverloadResolutionForDestructor())
10986 DeclareImplicitDestructor(ClassDecl);
10987 }
10988 }
10989
10990 // C++2a [class.compare.default]p3:
10991 // If the member-specification does not explicitly declare any member or
10992 // friend named operator==, an == operator function is declared implicitly
10993 // for each defaulted three-way comparison operator function defined in
10994 // the member-specification
10995 // FIXME: Consider doing this lazily.
10996 // We do this during the initial parse for a class template, not during
10997 // instantiation, so that we can handle unqualified lookups for 'operator=='
10998 // when parsing the template.
10999 if (getLangOpts().CPlusPlus20 && !inTemplateInstantiation()) {
11000 llvm::SmallVector<FunctionDecl *, 4> DefaultedSpaceships;
11001 findImplicitlyDeclaredEqualityComparisons(Ctx&: Context, RD: ClassDecl,
11002 Spaceships&: DefaultedSpaceships);
11003 for (auto *FD : DefaultedSpaceships)
11004 DeclareImplicitEqualityComparison(RD: ClassDecl, Spaceship: FD);
11005 }
11006}
11007
11008unsigned
11009Sema::ActOnReenterTemplateScope(Decl *D,
11010 llvm::function_ref<Scope *()> EnterScope) {
11011 if (!D)
11012 return 0;
11013 AdjustDeclIfTemplate(Decl&: D);
11014
11015 // In order to get name lookup right, reenter template scopes in order from
11016 // outermost to innermost.
11017 SmallVector<TemplateParameterList *, 4> ParameterLists;
11018 DeclContext *LookupDC = dyn_cast<DeclContext>(Val: D);
11019
11020 if (DeclaratorDecl *DD = dyn_cast<DeclaratorDecl>(Val: D)) {
11021 for (TemplateParameterList *TPL : DD->getTemplateParameterLists())
11022 ParameterLists.push_back(Elt: TPL);
11023
11024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D)) {
11025 if (FunctionTemplateDecl *FTD = FD->getDescribedFunctionTemplate())
11026 ParameterLists.push_back(Elt: FTD->getTemplateParameters());
11027 } else if (VarDecl *VD = dyn_cast<VarDecl>(Val: D)) {
11028 LookupDC = VD->getDeclContext();
11029
11030 if (VarTemplateDecl *VTD = VD->getDescribedVarTemplate())
11031 ParameterLists.push_back(Elt: VTD->getTemplateParameters());
11032 else if (auto *PSD = dyn_cast<VarTemplatePartialSpecializationDecl>(Val: D))
11033 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11034 }
11035 } else if (TagDecl *TD = dyn_cast<TagDecl>(Val: D)) {
11036 for (TemplateParameterList *TPL : TD->getTemplateParameterLists())
11037 ParameterLists.push_back(Elt: TPL);
11038
11039 if (CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(Val: TD)) {
11040 if (ClassTemplateDecl *CTD = RD->getDescribedClassTemplate())
11041 ParameterLists.push_back(Elt: CTD->getTemplateParameters());
11042 else if (auto *PSD = dyn_cast<ClassTemplatePartialSpecializationDecl>(Val: D))
11043 ParameterLists.push_back(Elt: PSD->getTemplateParameters());
11044 }
11045 }
11046 // FIXME: Alias declarations and concepts.
11047
11048 unsigned Count = 0;
11049 Scope *InnermostTemplateScope = nullptr;
11050 for (TemplateParameterList *Params : ParameterLists) {
11051 // Ignore explicit specializations; they don't contribute to the template
11052 // depth.
11053 if (Params->size() == 0)
11054 continue;
11055
11056 InnermostTemplateScope = EnterScope();
11057 for (NamedDecl *Param : *Params) {
11058 if (Param->getDeclName()) {
11059 InnermostTemplateScope->AddDecl(D: Param);
11060 IdResolver.AddDecl(D: Param);
11061 }
11062 }
11063 ++Count;
11064 }
11065
11066 // Associate the new template scopes with the corresponding entities.
11067 if (InnermostTemplateScope) {
11068 assert(LookupDC && "no enclosing DeclContext for template lookup");
11069 EnterTemplatedContext(S: InnermostTemplateScope, DC: LookupDC);
11070 }
11071
11072 return Count;
11073}
11074
11075void Sema::ActOnStartDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11076 if (!RecordD) return;
11077 AdjustDeclIfTemplate(Decl&: RecordD);
11078 CXXRecordDecl *Record = cast<CXXRecordDecl>(Val: RecordD);
11079 PushDeclContext(S, DC: Record);
11080}
11081
11082void Sema::ActOnFinishDelayedMemberDeclarations(Scope *S, Decl *RecordD) {
11083 if (!RecordD) return;
11084 PopDeclContext();
11085}
11086
11087void Sema::ActOnReenterCXXMethodParameter(Scope *S, ParmVarDecl *Param) {
11088 if (!Param)
11089 return;
11090
11091 S->AddDecl(D: Param);
11092 if (Param->getDeclName())
11093 IdResolver.AddDecl(D: Param);
11094}
11095
11096void Sema::ActOnStartDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11097}
11098
11099/// ActOnDelayedCXXMethodParameter - We've already started a delayed
11100/// C++ method declaration. We're (re-)introducing the given
11101/// function parameter into scope for use in parsing later parts of
11102/// the method declaration. For example, we could see an
11103/// ActOnParamDefaultArgument event for this parameter.
11104void Sema::ActOnDelayedCXXMethodParameter(Scope *S, Decl *ParamD) {
11105 if (!ParamD)
11106 return;
11107
11108 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamD);
11109
11110 S->AddDecl(D: Param);
11111 if (Param->getDeclName())
11112 IdResolver.AddDecl(D: Param);
11113}
11114
11115void Sema::ActOnFinishDelayedCXXMethodDeclaration(Scope *S, Decl *MethodD) {
11116 if (!MethodD)
11117 return;
11118
11119 AdjustDeclIfTemplate(Decl&: MethodD);
11120
11121 FunctionDecl *Method = cast<FunctionDecl>(Val: MethodD);
11122
11123 // Now that we have our default arguments, check the constructor
11124 // again. It could produce additional diagnostics or affect whether
11125 // the class has implicitly-declared destructors, among other
11126 // things.
11127 if (CXXConstructorDecl *Constructor = dyn_cast<CXXConstructorDecl>(Val: Method))
11128 CheckConstructor(Constructor);
11129
11130 // Check the default arguments, which we may have added.
11131 if (!Method->isInvalidDecl())
11132 CheckCXXDefaultArguments(FD: Method);
11133}
11134
11135// Emit the given diagnostic for each non-address-space qualifier.
11136// Common part of CheckConstructorDeclarator and CheckDestructorDeclarator.
11137static void checkMethodTypeQualifiers(Sema &S, Declarator &D, unsigned DiagID) {
11138 const DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11139 if (FTI.hasMethodTypeQualifiers() && !D.isInvalidType()) {
11140 bool DiagOccurred = false;
11141 FTI.MethodQualifiers->forEachQualifier(
11142 Handle: [DiagID, &S, &DiagOccurred](DeclSpec::TQ, StringRef QualName,
11143 SourceLocation SL) {
11144 // This diagnostic should be emitted on any qualifier except an addr
11145 // space qualifier. However, forEachQualifier currently doesn't visit
11146 // addr space qualifiers, so there's no way to write this condition
11147 // right now; we just diagnose on everything.
11148 S.Diag(Loc: SL, DiagID) << QualName << SourceRange(SL);
11149 DiagOccurred = true;
11150 });
11151 if (DiagOccurred)
11152 D.setInvalidType();
11153 }
11154}
11155
11156static void diagnoseInvalidDeclaratorChunks(Sema &S, Declarator &D,
11157 unsigned Kind) {
11158 if (D.isInvalidType() || D.getNumTypeObjects() <= 1)
11159 return;
11160
11161 DeclaratorChunk &Chunk = D.getTypeObject(i: D.getNumTypeObjects() - 1);
11162 if (Chunk.Kind == DeclaratorChunk::Paren ||
11163 Chunk.Kind == DeclaratorChunk::Function)
11164 return;
11165
11166 SourceLocation PointerLoc = Chunk.getSourceRange().getBegin();
11167 S.Diag(Loc: PointerLoc, DiagID: diag::err_invalid_ctor_dtor_decl)
11168 << Kind << Chunk.getSourceRange();
11169 D.setInvalidType();
11170}
11171
11172QualType Sema::CheckConstructorDeclarator(Declarator &D, QualType R,
11173 StorageClass &SC) {
11174 bool isVirtual = D.getDeclSpec().isVirtualSpecified();
11175
11176 // C++ [class.ctor]p3:
11177 // A constructor shall not be virtual (10.3) or static (9.4). A
11178 // constructor can be invoked for a const, volatile or const
11179 // volatile object. A constructor shall not be declared const,
11180 // volatile, or const volatile (9.3.2).
11181 if (isVirtual) {
11182 if (!D.isInvalidType())
11183 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11184 << "virtual" << SourceRange(D.getDeclSpec().getVirtualSpecLoc())
11185 << SourceRange(D.getIdentifierLoc());
11186 D.setInvalidType();
11187 }
11188 if (SC == SC_Static) {
11189 if (!D.isInvalidType())
11190 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_constructor_cannot_be)
11191 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11192 << SourceRange(D.getIdentifierLoc());
11193 D.setInvalidType();
11194 SC = SC_None;
11195 }
11196
11197 if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11198 diagnoseIgnoredQualifiers(
11199 DiagID: diag::err_constructor_return_type, Quals: TypeQuals, FallbackLoc: SourceLocation(),
11200 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(), VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11201 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11202 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11203 D.setInvalidType();
11204 }
11205
11206 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_constructor);
11207 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*constructor*/ Kind: 0);
11208
11209 // C++0x [class.ctor]p4:
11210 // A constructor shall not be declared with a ref-qualifier.
11211 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11212 if (FTI.hasRefQualifier()) {
11213 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_constructor)
11214 << FTI.RefQualifierIsLValueRef
11215 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11216 D.setInvalidType();
11217 }
11218
11219 // Rebuild the function type "R" without any type qualifiers (in
11220 // case any of the errors above fired) and with "void" as the
11221 // return type, since constructors don't have return types.
11222 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11223 if (Proto->getReturnType() == Context.VoidTy && !D.isInvalidType())
11224 return R;
11225
11226 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11227 EPI.TypeQuals = Qualifiers();
11228 EPI.RefQualifier = RQ_None;
11229
11230 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: Proto->getParamTypes(), EPI);
11231}
11232
11233void Sema::CheckConstructor(CXXConstructorDecl *Constructor) {
11234 CXXRecordDecl *ClassDecl
11235 = dyn_cast<CXXRecordDecl>(Val: Constructor->getDeclContext());
11236 if (!ClassDecl)
11237 return Constructor->setInvalidDecl();
11238
11239 // C++ [class.copy]p3:
11240 // A declaration of a constructor for a class X is ill-formed if
11241 // its first parameter is of type (optionally cv-qualified) X and
11242 // either there are no other parameters or else all other
11243 // parameters have default arguments.
11244 if (!Constructor->isInvalidDecl() &&
11245 Constructor->hasOneParamOrDefaultArgs() &&
11246 !Constructor->isFunctionTemplateSpecialization()) {
11247 CanQualType ParamType =
11248 Constructor->getParamDecl(i: 0)->getType()->getCanonicalTypeUnqualified();
11249 CanQualType ClassTy = Context.getCanonicalTagType(TD: ClassDecl);
11250 if (ParamType == ClassTy) {
11251 SourceLocation ParamLoc = Constructor->getParamDecl(i: 0)->getLocation();
11252 const char *ConstRef
11253 = Constructor->getParamDecl(i: 0)->getIdentifier() ? "const &"
11254 : " const &";
11255 Diag(Loc: ParamLoc, DiagID: diag::err_constructor_byvalue_arg)
11256 << FixItHint::CreateInsertion(InsertionLoc: ParamLoc, Code: ConstRef);
11257
11258 // FIXME: Rather that making the constructor invalid, we should endeavor
11259 // to fix the type.
11260 Constructor->setInvalidDecl();
11261 }
11262 }
11263}
11264
11265bool Sema::CheckDestructor(CXXDestructorDecl *Destructor) {
11266 CXXRecordDecl *RD = Destructor->getParent();
11267
11268 if (!Destructor->getOperatorDelete() && Destructor->isVirtual()) {
11269 SourceLocation Loc;
11270
11271 if (!Destructor->isImplicit())
11272 Loc = Destructor->getLocation();
11273 else
11274 Loc = RD->getLocation();
11275
11276 DeclarationName Name =
11277 Context.DeclarationNames.getCXXOperatorName(Op: OO_Delete);
11278 // If we have a virtual destructor, look up the deallocation function
11279 if (FunctionDecl *OperatorDelete = FindDeallocationFunctionForDestructor(
11280 StartLoc: Loc, RD, /*Diagnose=*/true, /*LookForGlobal=*/false, Name)) {
11281 Expr *ThisArg = nullptr;
11282
11283 // If the notional 'delete this' expression requires a non-trivial
11284 // conversion from 'this' to the type of a destroying operator delete's
11285 // first parameter, perform that conversion now.
11286 if (OperatorDelete->isDestroyingOperatorDelete()) {
11287 unsigned AddressParamIndex = 0;
11288 if (OperatorDelete->isTypeAwareOperatorNewOrDelete())
11289 ++AddressParamIndex;
11290 QualType ParamType =
11291 OperatorDelete->getParamDecl(i: AddressParamIndex)->getType();
11292 if (!declaresSameEntity(D1: ParamType->getAsCXXRecordDecl(), D2: RD)) {
11293 // C++ [class.dtor]p13:
11294 // ... as if for the expression 'delete this' appearing in a
11295 // non-virtual destructor of the destructor's class.
11296 ContextRAII SwitchContext(*this, Destructor);
11297 ExprResult This = ActOnCXXThis(
11298 Loc: OperatorDelete->getParamDecl(i: AddressParamIndex)->getLocation());
11299 assert(!This.isInvalid() && "couldn't form 'this' expr in dtor?");
11300 This = PerformImplicitConversion(From: This.get(), ToType: ParamType,
11301 Action: AssignmentAction::Passing);
11302 if (This.isInvalid()) {
11303 // FIXME: Register this as a context note so that it comes out
11304 // in the right order.
11305 Diag(Loc, DiagID: diag::note_implicit_delete_this_in_destructor_here);
11306 return true;
11307 }
11308 ThisArg = This.get();
11309 }
11310 }
11311
11312 DiagnoseUseOfDecl(D: OperatorDelete, Locs: Loc);
11313 MarkFunctionReferenced(Loc, Func: OperatorDelete);
11314 Destructor->setOperatorDelete(OD: OperatorDelete, ThisArg);
11315
11316 if (isa<CXXMethodDecl>(Val: OperatorDelete) &&
11317 Context.getTargetInfo().callGlobalDeleteInDeletingDtor(
11318 Context.getLangOpts())) {
11319 // In Microsoft ABI whenever a class has a defined operator delete,
11320 // scalar deleting destructors check the 3rd bit of the implicit
11321 // parameter and if it is set, then, global operator delete must be
11322 // called instead of the class-specific one. Find and save the global
11323 // operator delete for that case. Do not diagnose at this point because
11324 // the lack of a global operator delete is not an error if there are no
11325 // delete calls that require it.
11326 FunctionDecl *GlobalOperatorDelete =
11327 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11328 /*LookForGlobal*/ true, Name);
11329 if (GlobalOperatorDelete) {
11330 MarkFunctionReferenced(Loc, Func: GlobalOperatorDelete);
11331 Destructor->setOperatorGlobalDelete(GlobalOperatorDelete);
11332 }
11333 }
11334
11335 if (Context.getTargetInfo().emitVectorDeletingDtors(
11336 Context.getLangOpts())) {
11337 bool DestructorIsExported = Destructor->hasAttr<DLLExportAttr>();
11338 // Lookup delete[] too in case we have to emit a vector deleting dtor.
11339 DeclarationName VDeleteName =
11340 Context.DeclarationNames.getCXXOperatorName(Op: OO_Array_Delete);
11341 FunctionDecl *ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11342 StartLoc: Loc, RD, /*Diagnose*/ false,
11343 /*LookForGlobal*/ false, Name: VDeleteName);
11344 if (ArrOperatorDelete && isa<CXXMethodDecl>(Val: ArrOperatorDelete)) {
11345 FunctionDecl *GlobalArrOperatorDelete =
11346 FindDeallocationFunctionForDestructor(StartLoc: Loc, RD, /*Diagnose*/ false,
11347 /*LookForGlobal*/ true,
11348 Name: VDeleteName);
11349 Destructor->setGlobalOperatorArrayDelete(GlobalArrOperatorDelete);
11350 if (GlobalArrOperatorDelete &&
11351 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11352 DestructorIsExported))
11353 MarkFunctionReferenced(Loc, Func: GlobalArrOperatorDelete);
11354 } else if (!ArrOperatorDelete) {
11355 ArrOperatorDelete = FindDeallocationFunctionForDestructor(
11356 StartLoc: Loc, RD, /*Diagnose*/ false,
11357 /*LookForGlobal*/ true, Name: VDeleteName);
11358 }
11359 Destructor->setOperatorArrayDelete(ArrOperatorDelete);
11360 if (ArrOperatorDelete &&
11361 (Context.classMaybeNeedsVectorDeletingDestructor(RD) ||
11362 DestructorIsExported))
11363 MarkFunctionReferenced(Loc, Func: ArrOperatorDelete);
11364 }
11365 }
11366 }
11367
11368 return false;
11369}
11370
11371QualType Sema::CheckDestructorDeclarator(Declarator &D, QualType R,
11372 StorageClass& SC) {
11373 // C++ [class.dtor]p1:
11374 // [...] A typedef-name that names a class is a class-name
11375 // (7.1.3); however, a typedef-name that names a class shall not
11376 // be used as the identifier in the declarator for a destructor
11377 // declaration.
11378 QualType DeclaratorType = GetTypeFromParser(Ty: D.getName().DestructorName);
11379 if (const TypedefType *TT = DeclaratorType->getAs<TypedefType>())
11380 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11381 << DeclaratorType << isa<TypeAliasDecl>(Val: TT->getDecl());
11382 else if (const TemplateSpecializationType *TST =
11383 DeclaratorType->getAs<TemplateSpecializationType>())
11384 if (TST->isTypeAlias())
11385 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::ext_destructor_typedef_name)
11386 << DeclaratorType << 1;
11387
11388 // C++ [class.dtor]p2:
11389 // A destructor is used to destroy objects of its class type. A
11390 // destructor takes no parameters, and no return type can be
11391 // specified for it (not even void). The address of a destructor
11392 // shall not be taken. A destructor shall not be static. A
11393 // destructor can be invoked for a const, volatile or const
11394 // volatile object. A destructor shall not be declared const,
11395 // volatile or const volatile (9.3.2).
11396 if (SC == SC_Static) {
11397 if (!D.isInvalidType())
11398 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_cannot_be)
11399 << "static" << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11400 << SourceRange(D.getIdentifierLoc())
11401 << FixItHint::CreateRemoval(RemoveRange: D.getDeclSpec().getStorageClassSpecLoc());
11402
11403 SC = SC_None;
11404 }
11405 if (!D.isInvalidType()) {
11406 // Destructors don't have return types, but the parser will
11407 // happily parse something like:
11408 //
11409 // class X {
11410 // float ~X();
11411 // };
11412 //
11413 // The return type will be eliminated later.
11414 if (D.getDeclSpec().hasTypeSpecifier())
11415 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_return_type)
11416 << SourceRange(D.getDeclSpec().getTypeSpecTypeLoc())
11417 << SourceRange(D.getIdentifierLoc());
11418 else if (unsigned TypeQuals = D.getDeclSpec().getTypeQualifiers()) {
11419 diagnoseIgnoredQualifiers(DiagID: diag::err_destructor_return_type, Quals: TypeQuals,
11420 FallbackLoc: SourceLocation(),
11421 ConstQualLoc: D.getDeclSpec().getConstSpecLoc(),
11422 VolatileQualLoc: D.getDeclSpec().getVolatileSpecLoc(),
11423 RestrictQualLoc: D.getDeclSpec().getRestrictSpecLoc(),
11424 AtomicQualLoc: D.getDeclSpec().getAtomicSpecLoc());
11425 D.setInvalidType();
11426 }
11427 }
11428
11429 checkMethodTypeQualifiers(S&: *this, D, DiagID: diag::err_invalid_qualified_destructor);
11430 diagnoseInvalidDeclaratorChunks(S&: *this, D, /*destructor*/ Kind: 1);
11431
11432 // C++0x [class.dtor]p2:
11433 // A destructor shall not be declared with a ref-qualifier.
11434 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11435 if (FTI.hasRefQualifier()) {
11436 Diag(Loc: FTI.getRefQualifierLoc(), DiagID: diag::err_ref_qualifier_destructor)
11437 << FTI.RefQualifierIsLValueRef
11438 << FixItHint::CreateRemoval(RemoveRange: FTI.getRefQualifierLoc());
11439 D.setInvalidType();
11440 }
11441
11442 // Make sure we don't have any parameters.
11443 if (FTIHasNonVoidParameters(FTI)) {
11444 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_with_params);
11445
11446 // Delete the parameters.
11447 FTI.freeParams();
11448 D.setInvalidType();
11449 }
11450
11451 // Make sure the destructor isn't variadic.
11452 if (FTI.isVariadic) {
11453 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_destructor_variadic);
11454 D.setInvalidType();
11455 }
11456
11457 // Rebuild the function type "R" without any type qualifiers or
11458 // parameters (in case any of the errors above fired) and with
11459 // "void" as the return type, since destructors don't have return
11460 // types.
11461 if (!D.isInvalidType())
11462 return R;
11463
11464 const FunctionProtoType *Proto = R->castAs<FunctionProtoType>();
11465 FunctionProtoType::ExtProtoInfo EPI = Proto->getExtProtoInfo();
11466 EPI.Variadic = false;
11467 EPI.TypeQuals = Qualifiers();
11468 EPI.RefQualifier = RQ_None;
11469 return Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI);
11470}
11471
11472static void extendLeft(SourceRange &R, SourceRange Before) {
11473 if (Before.isInvalid())
11474 return;
11475 R.setBegin(Before.getBegin());
11476 if (R.getEnd().isInvalid())
11477 R.setEnd(Before.getEnd());
11478}
11479
11480static void extendRight(SourceRange &R, SourceRange After) {
11481 if (After.isInvalid())
11482 return;
11483 if (R.getBegin().isInvalid())
11484 R.setBegin(After.getBegin());
11485 R.setEnd(After.getEnd());
11486}
11487
11488void Sema::CheckConversionDeclarator(Declarator &D, QualType &R,
11489 StorageClass& SC) {
11490 // C++ [class.conv.fct]p1:
11491 // Neither parameter types nor return type can be specified. The
11492 // type of a conversion function (8.3.5) is "function taking no
11493 // parameter returning conversion-type-id."
11494 if (SC == SC_Static) {
11495 if (!D.isInvalidType())
11496 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_not_member)
11497 << SourceRange(D.getDeclSpec().getStorageClassSpecLoc())
11498 << D.getName().getSourceRange();
11499 D.setInvalidType();
11500 SC = SC_None;
11501 }
11502
11503 TypeSourceInfo *ConvTSI = nullptr;
11504 QualType ConvType =
11505 GetTypeFromParser(Ty: D.getName().ConversionFunctionId, TInfo: &ConvTSI);
11506
11507 const DeclSpec &DS = D.getDeclSpec();
11508 if (DS.hasTypeSpecifier() && !D.isInvalidType()) {
11509 // Conversion functions don't have return types, but the parser will
11510 // happily parse something like:
11511 //
11512 // class X {
11513 // float operator bool();
11514 // };
11515 //
11516 // The return type will be changed later anyway.
11517 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_return_type)
11518 << SourceRange(DS.getTypeSpecTypeLoc())
11519 << SourceRange(D.getIdentifierLoc());
11520 D.setInvalidType();
11521 } else if (DS.getTypeQualifiers() && !D.isInvalidType()) {
11522 // It's also plausible that the user writes type qualifiers in the wrong
11523 // place, such as:
11524 // struct S { const operator int(); };
11525 // FIXME: we could provide a fixit to move the qualifiers onto the
11526 // conversion type.
11527 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_complex_decl)
11528 << SourceRange(D.getIdentifierLoc()) << 0;
11529 D.setInvalidType();
11530 }
11531 const auto *Proto = R->castAs<FunctionProtoType>();
11532 // Make sure we don't have any parameters.
11533 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11534 unsigned NumParam = Proto->getNumParams();
11535
11536 // [C++2b]
11537 // A conversion function shall have no non-object parameters.
11538 if (NumParam == 1) {
11539 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11540 if (const auto *First =
11541 dyn_cast_if_present<ParmVarDecl>(Val: FTI.Params[0].Param);
11542 First && First->isExplicitObjectParameter())
11543 NumParam--;
11544 }
11545
11546 if (NumParam != 0) {
11547 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_with_params);
11548 // Delete the parameters.
11549 FTI.freeParams();
11550 D.setInvalidType();
11551 } else if (Proto->isVariadic()) {
11552 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_variadic);
11553 D.setInvalidType();
11554 }
11555
11556 // Diagnose "&operator bool()" and other such nonsense. This
11557 // is actually a gcc extension which we don't support.
11558 if (Proto->getReturnType() != ConvType) {
11559 bool NeedsTypedef = false;
11560 SourceRange Before, After;
11561
11562 // Walk the chunks and extract information on them for our diagnostic.
11563 bool PastFunctionChunk = false;
11564 for (auto &Chunk : D.type_objects()) {
11565 switch (Chunk.Kind) {
11566 case DeclaratorChunk::Function:
11567 if (!PastFunctionChunk) {
11568 if (Chunk.Fun.HasTrailingReturnType) {
11569 TypeSourceInfo *TRT = nullptr;
11570 GetTypeFromParser(Ty: Chunk.Fun.getTrailingReturnType(), TInfo: &TRT);
11571 if (TRT) extendRight(R&: After, After: TRT->getTypeLoc().getSourceRange());
11572 }
11573 PastFunctionChunk = true;
11574 break;
11575 }
11576 [[fallthrough]];
11577 case DeclaratorChunk::Array:
11578 NeedsTypedef = true;
11579 extendRight(R&: After, After: Chunk.getSourceRange());
11580 break;
11581
11582 case DeclaratorChunk::Pointer:
11583 case DeclaratorChunk::BlockPointer:
11584 case DeclaratorChunk::Reference:
11585 case DeclaratorChunk::MemberPointer:
11586 case DeclaratorChunk::Pipe:
11587 extendLeft(R&: Before, Before: Chunk.getSourceRange());
11588 break;
11589
11590 case DeclaratorChunk::Paren:
11591 extendLeft(R&: Before, Before: Chunk.Loc);
11592 extendRight(R&: After, After: Chunk.EndLoc);
11593 break;
11594 }
11595 }
11596
11597 SourceLocation Loc = Before.isValid() ? Before.getBegin() :
11598 After.isValid() ? After.getBegin() :
11599 D.getIdentifierLoc();
11600 auto &&DB = Diag(Loc, DiagID: diag::err_conv_function_with_complex_decl);
11601 DB << Before << After;
11602
11603 if (!NeedsTypedef) {
11604 DB << /*don't need a typedef*/0;
11605
11606 // If we can provide a correct fix-it hint, do so.
11607 if (After.isInvalid() && ConvTSI) {
11608 SourceLocation InsertLoc =
11609 getLocForEndOfToken(Loc: ConvTSI->getTypeLoc().getEndLoc());
11610 DB << FixItHint::CreateInsertion(InsertionLoc: InsertLoc, Code: " ")
11611 << FixItHint::CreateInsertionFromRange(
11612 InsertionLoc: InsertLoc, FromRange: CharSourceRange::getTokenRange(R: Before))
11613 << FixItHint::CreateRemoval(RemoveRange: Before);
11614 }
11615 } else if (!Proto->getReturnType()->isDependentType()) {
11616 DB << /*typedef*/1 << Proto->getReturnType();
11617 } else if (getLangOpts().CPlusPlus11) {
11618 DB << /*alias template*/2 << Proto->getReturnType();
11619 } else {
11620 DB << /*might not be fixable*/3;
11621 }
11622
11623 // Recover by incorporating the other type chunks into the result type.
11624 // Note, this does *not* change the name of the function. This is compatible
11625 // with the GCC extension:
11626 // struct S { &operator int(); } s;
11627 // int &r = s.operator int(); // ok in GCC
11628 // S::operator int&() {} // error in GCC, function name is 'operator int'.
11629 ConvType = Proto->getReturnType();
11630 }
11631
11632 // C++ [class.conv.fct]p4:
11633 // The conversion-type-id shall not represent a function type nor
11634 // an array type.
11635 if (ConvType->isArrayType()) {
11636 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_array);
11637 ConvType = Context.getPointerType(T: ConvType);
11638 D.setInvalidType();
11639 } else if (ConvType->isFunctionType()) {
11640 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_conv_function_to_function);
11641 ConvType = Context.getPointerType(T: ConvType);
11642 D.setInvalidType();
11643 }
11644
11645 // Rebuild the function type "R" without any parameters (in case any
11646 // of the errors above fired) and with the conversion type as the
11647 // return type.
11648 if (D.isInvalidType())
11649 R = Context.getFunctionType(ResultTy: ConvType, Args: {}, EPI: Proto->getExtProtoInfo());
11650
11651 // C++0x explicit conversion operators.
11652 if (DS.hasExplicitSpecifier())
11653 DiagCompat(Loc: DS.getExplicitSpecLoc(),
11654 CompatDiagId: diag_compat::explicit_conversion_functions)
11655 << SourceRange(DS.getExplicitSpecRange());
11656}
11657
11658Decl *Sema::ActOnConversionDeclarator(CXXConversionDecl *Conversion) {
11659 assert(Conversion && "Expected to receive a conversion function declaration");
11660
11661 CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(Val: Conversion->getDeclContext());
11662
11663 // Make sure we aren't redeclaring the conversion function.
11664 QualType ConvType = Context.getCanonicalType(T: Conversion->getConversionType());
11665 // C++ [class.conv.fct]p1:
11666 // [...] A conversion function is never used to convert a
11667 // (possibly cv-qualified) object to the (possibly cv-qualified)
11668 // same object type (or a reference to it), to a (possibly
11669 // cv-qualified) base class of that type (or a reference to it),
11670 // or to (possibly cv-qualified) void.
11671 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
11672 if (const ReferenceType *ConvTypeRef = ConvType->getAs<ReferenceType>())
11673 ConvType = ConvTypeRef->getPointeeType();
11674 if (Conversion->getTemplateSpecializationKind() != TSK_Undeclared &&
11675 Conversion->getTemplateSpecializationKind() != TSK_ExplicitSpecialization)
11676 /* Suppress diagnostics for instantiations. */;
11677 else if (Conversion->size_overridden_methods() != 0)
11678 /* Suppress diagnostics for overriding virtual function in a base class. */;
11679 else if (ConvType->isRecordType()) {
11680 ConvType = Context.getCanonicalType(T: ConvType).getUnqualifiedType();
11681 if (ConvType == ClassType)
11682 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_self_not_used)
11683 << ClassType;
11684 else if (IsDerivedFrom(Loc: Conversion->getLocation(), Derived: ClassType, Base: ConvType))
11685 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_base_not_used)
11686 << ClassType << ConvType;
11687 } else if (ConvType->isVoidType()) {
11688 Diag(Loc: Conversion->getLocation(), DiagID: diag::warn_conv_to_void_not_used)
11689 << ClassType << ConvType;
11690 }
11691
11692 if (FunctionTemplateDecl *ConversionTemplate =
11693 Conversion->getDescribedFunctionTemplate()) {
11694 if (const auto *ConvTypePtr = ConvType->getAs<PointerType>()) {
11695 ConvType = ConvTypePtr->getPointeeType();
11696 }
11697 if (ConvType->isUndeducedAutoType()) {
11698 Diag(Loc: Conversion->getTypeSpecStartLoc(), DiagID: diag::err_auto_not_allowed)
11699 << getReturnTypeLoc(FD: Conversion).getSourceRange()
11700 << ConvType->castAs<AutoType>()->getKeyword()
11701 << /* in declaration of conversion function template= */ 24;
11702 }
11703
11704 return ConversionTemplate;
11705 }
11706
11707 return Conversion;
11708}
11709
11710void Sema::CheckExplicitObjectMemberFunction(DeclContext *DC, Declarator &D,
11711 DeclarationName Name, QualType R) {
11712 CheckExplicitObjectMemberFunction(D, Name, R, IsLambda: false, DC);
11713}
11714
11715void Sema::CheckExplicitObjectLambda(Declarator &D) {
11716 CheckExplicitObjectMemberFunction(D, Name: {}, R: {}, IsLambda: true);
11717}
11718
11719void Sema::CheckExplicitObjectMemberFunction(Declarator &D,
11720 DeclarationName Name, QualType R,
11721 bool IsLambda, DeclContext *DC) {
11722 if (!D.isFunctionDeclarator())
11723 return;
11724
11725 DeclaratorChunk::FunctionTypeInfo &FTI = D.getFunctionTypeInfo();
11726 if (FTI.NumParams == 0)
11727 return;
11728 ParmVarDecl *ExplicitObjectParam = nullptr;
11729 for (unsigned Idx = 0; Idx < FTI.NumParams; Idx++) {
11730 const auto &ParamInfo = FTI.Params[Idx];
11731 if (!ParamInfo.Param)
11732 continue;
11733 ParmVarDecl *Param = cast<ParmVarDecl>(Val: ParamInfo.Param);
11734 if (!Param->isExplicitObjectParameter())
11735 continue;
11736 if (Idx == 0) {
11737 ExplicitObjectParam = Param;
11738 continue;
11739 } else {
11740 Diag(Loc: Param->getLocation(),
11741 DiagID: diag::err_explicit_object_parameter_must_be_first)
11742 << IsLambda << Param->getSourceRange();
11743 }
11744 }
11745 if (!ExplicitObjectParam)
11746 return;
11747
11748 if (ExplicitObjectParam->hasDefaultArg()) {
11749 Diag(Loc: ExplicitObjectParam->getLocation(),
11750 DiagID: diag::err_explicit_object_default_arg)
11751 << ExplicitObjectParam->getSourceRange();
11752 D.setInvalidType();
11753 }
11754
11755 if (D.getDeclSpec().getStorageClassSpec() == DeclSpec::SCS_static ||
11756 (D.getContext() == clang::DeclaratorContext::Member &&
11757 D.isStaticMember())) {
11758 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11759 DiagID: diag::err_explicit_object_parameter_nonmember)
11760 << D.getSourceRange() << /*static=*/0 << IsLambda;
11761 D.setInvalidType();
11762 }
11763
11764 if (D.getDeclSpec().isVirtualSpecified()) {
11765 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11766 DiagID: diag::err_explicit_object_parameter_nonmember)
11767 << D.getSourceRange() << /*virtual=*/1 << IsLambda;
11768 D.setInvalidType();
11769 }
11770
11771 // Friend declarations require some care. Consider:
11772 //
11773 // namespace N {
11774 // struct A{};
11775 // int f(A);
11776 // }
11777 //
11778 // struct S {
11779 // struct T {
11780 // int f(this T);
11781 // };
11782 //
11783 // friend int T::f(this T); // Allow this.
11784 // friend int f(this S); // But disallow this.
11785 // friend int N::f(this A); // And disallow this.
11786 // };
11787 //
11788 // Here, it seems to suffice to check whether the scope
11789 // specifier designates a class type.
11790 if (D.getDeclSpec().isFriendSpecified() &&
11791 !isa_and_present<CXXRecordDecl>(
11792 Val: computeDeclContext(SS: D.getCXXScopeSpec()))) {
11793 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11794 DiagID: diag::err_explicit_object_parameter_nonmember)
11795 << D.getSourceRange() << /*non-member=*/2 << IsLambda;
11796 D.setInvalidType();
11797 }
11798
11799 if (IsLambda && FTI.hasMutableQualifier()) {
11800 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11801 DiagID: diag::err_explicit_object_parameter_mutable)
11802 << D.getSourceRange();
11803 }
11804
11805 if (IsLambda)
11806 return;
11807
11808 if (!DC || !DC->isRecord()) {
11809 assert(D.isInvalidType() && "Explicit object parameter in non-member "
11810 "should have been diagnosed already");
11811 return;
11812 }
11813
11814 // CWG2674: constructors and destructors cannot have explicit parameters.
11815 if (Name.getNameKind() == DeclarationName::CXXConstructorName ||
11816 Name.getNameKind() == DeclarationName::CXXDestructorName) {
11817 Diag(Loc: ExplicitObjectParam->getBeginLoc(),
11818 DiagID: diag::err_explicit_object_parameter_constructor)
11819 << (Name.getNameKind() == DeclarationName::CXXDestructorName)
11820 << D.getSourceRange();
11821 D.setInvalidType();
11822 }
11823}
11824
11825namespace {
11826/// Utility class to accumulate and print a diagnostic listing the invalid
11827/// specifier(s) on a declaration.
11828struct BadSpecifierDiagnoser {
11829 BadSpecifierDiagnoser(Sema &S, SourceLocation Loc, unsigned DiagID)
11830 : S(S), Diagnostic(S.Diag(Loc, DiagID)) {}
11831 ~BadSpecifierDiagnoser() {
11832 Diagnostic << Specifiers;
11833 }
11834
11835 template<typename T> void check(SourceLocation SpecLoc, T Spec) {
11836 return check(SpecLoc, DeclSpec::getSpecifierName(Spec));
11837 }
11838 void check(SourceLocation SpecLoc, DeclSpec::TST Spec) {
11839 return check(SpecLoc,
11840 Spec: DeclSpec::getSpecifierName(T: Spec, Policy: S.getPrintingPolicy()));
11841 }
11842 void check(SourceLocation SpecLoc, const char *Spec) {
11843 if (SpecLoc.isInvalid()) return;
11844 Diagnostic << SourceRange(SpecLoc, SpecLoc);
11845 if (!Specifiers.empty()) Specifiers += " ";
11846 Specifiers += Spec;
11847 }
11848
11849 Sema &S;
11850 Sema::SemaDiagnosticBuilder Diagnostic;
11851 std::string Specifiers;
11852};
11853}
11854
11855bool Sema::CheckDeductionGuideDeclarator(Declarator &D, QualType &R,
11856 StorageClass &SC) {
11857 TemplateName GuidedTemplate = D.getName().TemplateName.get().get();
11858 TemplateDecl *GuidedTemplateDecl = GuidedTemplate.getAsTemplateDecl();
11859 assert(GuidedTemplateDecl && "missing template decl for deduction guide");
11860
11861 // C++ [temp.deduct.guide]p3:
11862 // A deduction-gide shall be declared in the same scope as the
11863 // corresponding class template.
11864 if (!CurContext->getRedeclContext()->Equals(
11865 DC: GuidedTemplateDecl->getDeclContext()->getRedeclContext())) {
11866 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_wrong_scope)
11867 << GuidedTemplateDecl;
11868 NoteTemplateLocation(Decl: *GuidedTemplateDecl);
11869 }
11870
11871 auto &DS = D.getMutableDeclSpec();
11872 // We leave 'friend' and 'virtual' to be rejected in the normal way.
11873 if (DS.hasTypeSpecifier() || DS.getTypeQualifiers() ||
11874 DS.getStorageClassSpecLoc().isValid() || DS.isInlineSpecified() ||
11875 DS.isNoreturnSpecified() || DS.hasConstexprSpecifier()) {
11876 BadSpecifierDiagnoser Diagnoser(
11877 *this, D.getIdentifierLoc(),
11878 diag::err_deduction_guide_invalid_specifier);
11879
11880 Diagnoser.check(SpecLoc: DS.getStorageClassSpecLoc(), Spec: DS.getStorageClassSpec());
11881 DS.ClearStorageClassSpecs();
11882 SC = SC_None;
11883
11884 // 'explicit' is permitted.
11885 Diagnoser.check(SpecLoc: DS.getInlineSpecLoc(), Spec: "inline");
11886 Diagnoser.check(SpecLoc: DS.getNoreturnSpecLoc(), Spec: "_Noreturn");
11887 Diagnoser.check(SpecLoc: DS.getConstexprSpecLoc(), Spec: "constexpr");
11888 DS.ClearConstexprSpec();
11889
11890 Diagnoser.check(SpecLoc: DS.getConstSpecLoc(), Spec: "const");
11891 Diagnoser.check(SpecLoc: DS.getRestrictSpecLoc(), Spec: "__restrict");
11892 Diagnoser.check(SpecLoc: DS.getVolatileSpecLoc(), Spec: "volatile");
11893 Diagnoser.check(SpecLoc: DS.getAtomicSpecLoc(), Spec: "_Atomic");
11894 Diagnoser.check(SpecLoc: DS.getUnalignedSpecLoc(), Spec: "__unaligned");
11895 DS.ClearTypeQualifiers();
11896
11897 Diagnoser.check(SpecLoc: DS.getTypeSpecComplexLoc(), Spec: DS.getTypeSpecComplex());
11898 Diagnoser.check(SpecLoc: DS.getTypeSpecSignLoc(), Spec: DS.getTypeSpecSign());
11899 Diagnoser.check(SpecLoc: DS.getTypeSpecWidthLoc(), Spec: DS.getTypeSpecWidth());
11900 Diagnoser.check(SpecLoc: DS.getTypeSpecTypeLoc(), Spec: DS.getTypeSpecType());
11901 DS.ClearTypeSpecType();
11902 }
11903
11904 if (D.isInvalidType())
11905 return true;
11906
11907 // Check the declarator is simple enough.
11908 bool FoundFunction = false;
11909 for (const DeclaratorChunk &Chunk : llvm::reverse(C: D.type_objects())) {
11910 if (Chunk.Kind == DeclaratorChunk::Paren)
11911 continue;
11912 if (Chunk.Kind != DeclaratorChunk::Function || FoundFunction) {
11913 Diag(Loc: D.getDeclSpec().getBeginLoc(),
11914 DiagID: diag::err_deduction_guide_with_complex_decl)
11915 << D.getSourceRange();
11916 break;
11917 }
11918 if (!Chunk.Fun.hasTrailingReturnType())
11919 return Diag(Loc: D.getName().getBeginLoc(),
11920 DiagID: diag::err_deduction_guide_no_trailing_return_type);
11921
11922 // Check that the return type is written as a specialization of
11923 // the template specified as the deduction-guide's name.
11924 // The template name may not be qualified. [temp.deduct.guide]
11925 ParsedType TrailingReturnType = Chunk.Fun.getTrailingReturnType();
11926 TypeSourceInfo *TSI = nullptr;
11927 QualType RetTy = GetTypeFromParser(Ty: TrailingReturnType, TInfo: &TSI);
11928 assert(TSI && "deduction guide has valid type but invalid return type?");
11929 bool AcceptableReturnType = false;
11930 bool MightInstantiateToSpecialization = false;
11931 if (auto RetTST =
11932 TSI->getTypeLoc().getAsAdjusted<TemplateSpecializationTypeLoc>()) {
11933 TemplateName SpecifiedName = RetTST.getTypePtr()->getTemplateName();
11934 bool TemplateMatches = Context.hasSameTemplateName(
11935 X: SpecifiedName, Y: GuidedTemplate, /*IgnoreDeduced=*/true);
11936
11937 const QualifiedTemplateName *Qualifiers =
11938 SpecifiedName.getAsQualifiedTemplateName();
11939 // A Template template parameter is never wrapped in a
11940 // QualifiedTemplateName, but it's always simply-written.
11941 bool SimplyWritten = !Qualifiers || (!Qualifiers->hasTemplateKeyword() &&
11942 !Qualifiers->getQualifier());
11943 if (SimplyWritten && TemplateMatches)
11944 AcceptableReturnType = true;
11945 else {
11946 // This could still instantiate to the right type, unless we know it
11947 // names the wrong class template.
11948 auto *TD = SpecifiedName.getAsTemplateDecl();
11949 MightInstantiateToSpecialization =
11950 !(TD && isa<ClassTemplateDecl>(Val: TD) && !TemplateMatches);
11951 }
11952 } else if (!RetTy.hasQualifiers() && RetTy->isDependentType()) {
11953 MightInstantiateToSpecialization = true;
11954 }
11955
11956 if (!AcceptableReturnType)
11957 return Diag(Loc: TSI->getTypeLoc().getBeginLoc(),
11958 DiagID: diag::err_deduction_guide_bad_trailing_return_type)
11959 << GuidedTemplate << TSI->getType()
11960 << MightInstantiateToSpecialization
11961 << TSI->getTypeLoc().getSourceRange();
11962
11963 // Keep going to check that we don't have any inner declarator pieces (we
11964 // could still have a function returning a pointer to a function).
11965 FoundFunction = true;
11966 }
11967
11968 if (D.isFunctionDefinition())
11969 // we can still create a valid deduction guide here.
11970 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_deduction_guide_defines_function);
11971 return false;
11972}
11973
11974//===----------------------------------------------------------------------===//
11975// Namespace Handling
11976//===----------------------------------------------------------------------===//
11977
11978/// Diagnose a mismatch in 'inline' qualifiers when a namespace is
11979/// reopened.
11980static void DiagnoseNamespaceInlineMismatch(Sema &S, SourceLocation KeywordLoc,
11981 SourceLocation Loc,
11982 IdentifierInfo *II, bool *IsInline,
11983 NamespaceDecl *PrevNS) {
11984 assert(*IsInline != PrevNS->isInline());
11985
11986 // 'inline' must appear on the original definition, but not necessarily
11987 // on all extension definitions, so the note should point to the first
11988 // definition to avoid confusion.
11989 PrevNS = PrevNS->getFirstDecl();
11990
11991 if (PrevNS->isInline())
11992 // The user probably just forgot the 'inline', so suggest that it
11993 // be added back.
11994 S.Diag(Loc, DiagID: diag::warn_inline_namespace_reopened_noninline)
11995 << FixItHint::CreateInsertion(InsertionLoc: KeywordLoc, Code: "inline ");
11996 else
11997 S.Diag(Loc, DiagID: diag::err_inline_namespace_mismatch);
11998
11999 S.Diag(Loc: PrevNS->getLocation(), DiagID: diag::note_previous_definition);
12000 *IsInline = PrevNS->isInline();
12001}
12002
12003/// ActOnStartNamespaceDef - This is called at the start of a namespace
12004/// definition.
12005Decl *Sema::ActOnStartNamespaceDef(Scope *NamespcScope,
12006 SourceLocation InlineLoc,
12007 SourceLocation NamespaceLoc,
12008 SourceLocation IdentLoc, IdentifierInfo *II,
12009 SourceLocation LBrace,
12010 const ParsedAttributesView &AttrList,
12011 UsingDirectiveDecl *&UD, bool IsNested) {
12012 SourceLocation StartLoc = InlineLoc.isValid() ? InlineLoc : NamespaceLoc;
12013 // For anonymous namespace, take the location of the left brace.
12014 SourceLocation Loc = II ? IdentLoc : LBrace;
12015 bool IsInline = InlineLoc.isValid();
12016 bool IsInvalid = false;
12017 bool IsStd = false;
12018 bool AddToKnown = false;
12019 Scope *DeclRegionScope = NamespcScope->getParent();
12020
12021 NamespaceDecl *PrevNS = nullptr;
12022 if (II) {
12023 // C++ [namespace.std]p7:
12024 // A translation unit shall not declare namespace std to be an inline
12025 // namespace (9.8.2).
12026 //
12027 // Precondition: the std namespace is in the file scope and is declared to
12028 // be inline
12029 auto DiagnoseInlineStdNS = [&]() {
12030 assert(IsInline && II->isStr("std") &&
12031 CurContext->getRedeclContext()->isTranslationUnit() &&
12032 "Precondition of DiagnoseInlineStdNS not met");
12033 Diag(Loc: InlineLoc, DiagID: diag::err_inline_namespace_std)
12034 << SourceRange(InlineLoc, InlineLoc.getLocWithOffset(Offset: 6));
12035 IsInline = false;
12036 };
12037 // C++ [namespace.def]p2:
12038 // The identifier in an original-namespace-definition shall not
12039 // have been previously defined in the declarative region in
12040 // which the original-namespace-definition appears. The
12041 // identifier in an original-namespace-definition is the name of
12042 // the namespace. Subsequently in that declarative region, it is
12043 // treated as an original-namespace-name.
12044 //
12045 // Since namespace names are unique in their scope, and we don't
12046 // look through using directives, just look for any ordinary names
12047 // as if by qualified name lookup.
12048 LookupResult R(*this, II, IdentLoc, LookupOrdinaryName,
12049 RedeclarationKind::ForExternalRedeclaration);
12050 LookupQualifiedName(R, LookupCtx: CurContext->getRedeclContext());
12051 NamedDecl *PrevDecl =
12052 R.isSingleResult() ? R.getRepresentativeDecl() : nullptr;
12053 PrevNS = dyn_cast_or_null<NamespaceDecl>(Val: PrevDecl);
12054
12055 if (PrevNS) {
12056 // This is an extended namespace definition.
12057 if (IsInline && II->isStr(Str: "std") &&
12058 CurContext->getRedeclContext()->isTranslationUnit())
12059 DiagnoseInlineStdNS();
12060 else if (IsInline != PrevNS->isInline())
12061 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc, II,
12062 IsInline: &IsInline, PrevNS);
12063 } else if (PrevDecl) {
12064 // This is an invalid name redefinition.
12065 Diag(Loc, DiagID: diag::err_redefinition_different_kind)
12066 << II;
12067 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
12068 IsInvalid = true;
12069 // Continue on to push Namespc as current DeclContext and return it.
12070 } else if (II->isStr(Str: "std") &&
12071 CurContext->getRedeclContext()->isTranslationUnit()) {
12072 if (IsInline)
12073 DiagnoseInlineStdNS();
12074 // This is the first "real" definition of the namespace "std", so update
12075 // our cache of the "std" namespace to point at this definition.
12076 PrevNS = getStdNamespace();
12077 IsStd = true;
12078 AddToKnown = !IsInline;
12079 } else {
12080 // We've seen this namespace for the first time.
12081 AddToKnown = !IsInline;
12082 }
12083 } else {
12084 // Anonymous namespaces.
12085
12086 // Determine whether the parent already has an anonymous namespace.
12087 DeclContext *Parent = CurContext->getRedeclContext();
12088 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12089 PrevNS = TU->getAnonymousNamespace();
12090 } else {
12091 NamespaceDecl *ND = cast<NamespaceDecl>(Val: Parent);
12092 PrevNS = ND->getAnonymousNamespace();
12093 }
12094
12095 if (PrevNS && IsInline != PrevNS->isInline())
12096 DiagnoseNamespaceInlineMismatch(S&: *this, KeywordLoc: NamespaceLoc, Loc: NamespaceLoc, II,
12097 IsInline: &IsInline, PrevNS);
12098 }
12099
12100 NamespaceDecl *Namespc = NamespaceDecl::Create(
12101 C&: Context, DC: CurContext, Inline: IsInline, StartLoc, IdLoc: Loc, Id: II, PrevDecl: PrevNS, Nested: IsNested);
12102 if (IsInvalid)
12103 Namespc->setInvalidDecl();
12104
12105 ProcessDeclAttributeList(S: DeclRegionScope, D: Namespc, AttrList);
12106 AddPragmaAttributes(S: DeclRegionScope, D: Namespc);
12107 ProcessAPINotes(D: Namespc);
12108
12109 // FIXME: Should we be merging attributes?
12110 if (const VisibilityAttr *Attr = Namespc->getAttr<VisibilityAttr>())
12111 PushNamespaceVisibilityAttr(Attr, Loc);
12112
12113 if (IsStd)
12114 StdNamespace = Namespc;
12115 if (AddToKnown)
12116 KnownNamespaces[Namespc] = false;
12117
12118 if (II) {
12119 PushOnScopeChains(D: Namespc, S: DeclRegionScope);
12120 } else {
12121 // Link the anonymous namespace into its parent.
12122 DeclContext *Parent = CurContext->getRedeclContext();
12123 if (TranslationUnitDecl *TU = dyn_cast<TranslationUnitDecl>(Val: Parent)) {
12124 TU->setAnonymousNamespace(Namespc);
12125 } else {
12126 cast<NamespaceDecl>(Val: Parent)->setAnonymousNamespace(Namespc);
12127 }
12128
12129 CurContext->addDecl(D: Namespc);
12130
12131 // C++ [namespace.unnamed]p1. An unnamed-namespace-definition
12132 // behaves as if it were replaced by
12133 // namespace unique { /* empty body */ }
12134 // using namespace unique;
12135 // namespace unique { namespace-body }
12136 // where all occurrences of 'unique' in a translation unit are
12137 // replaced by the same identifier and this identifier differs
12138 // from all other identifiers in the entire program.
12139
12140 // We just create the namespace with an empty name and then add an
12141 // implicit using declaration, just like the standard suggests.
12142 //
12143 // CodeGen enforces the "universally unique" aspect by giving all
12144 // declarations semantically contained within an anonymous
12145 // namespace internal linkage.
12146
12147 if (!PrevNS) {
12148 UD = UsingDirectiveDecl::Create(C&: Context, DC: Parent,
12149 /* 'using' */ UsingLoc: LBrace,
12150 /* 'namespace' */ NamespaceLoc: SourceLocation(),
12151 /* qualifier */ QualifierLoc: NestedNameSpecifierLoc(),
12152 /* identifier */ IdentLoc: SourceLocation(),
12153 Nominated: Namespc,
12154 /* Ancestor */ CommonAncestor: Parent);
12155 UD->setImplicit();
12156 Parent->addDecl(D: UD);
12157 }
12158 }
12159
12160 ActOnDocumentableDecl(D: Namespc);
12161
12162 // Although we could have an invalid decl (i.e. the namespace name is a
12163 // redefinition), push it as current DeclContext and try to continue parsing.
12164 // FIXME: We should be able to push Namespc here, so that the each DeclContext
12165 // for the namespace has the declarations that showed up in that particular
12166 // namespace definition.
12167 PushDeclContext(S: NamespcScope, DC: Namespc);
12168 return Namespc;
12169}
12170
12171/// getNamespaceDecl - Returns the namespace a decl represents. If the decl
12172/// is a namespace alias, returns the namespace it points to.
12173static inline NamespaceDecl *getNamespaceDecl(NamespaceBaseDecl *D) {
12174 if (NamespaceAliasDecl *AD = dyn_cast_or_null<NamespaceAliasDecl>(Val: D))
12175 return AD->getNamespace();
12176 return dyn_cast_or_null<NamespaceDecl>(Val: D);
12177}
12178
12179void Sema::ActOnFinishNamespaceDef(Decl *Dcl, SourceLocation RBrace) {
12180 NamespaceDecl *Namespc = dyn_cast_or_null<NamespaceDecl>(Val: Dcl);
12181 assert(Namespc && "Invalid parameter, expected NamespaceDecl");
12182 Namespc->setRBraceLoc(RBrace);
12183 PopDeclContext();
12184 if (Namespc->hasAttr<VisibilityAttr>())
12185 PopPragmaVisibility(IsNamespaceEnd: true, EndLoc: RBrace);
12186 // If this namespace contains an export-declaration, export it now.
12187 if (DeferredExportedNamespaces.erase(Ptr: Namespc))
12188 Dcl->setModuleOwnershipKind(Decl::ModuleOwnershipKind::VisibleWhenImported);
12189}
12190
12191CXXRecordDecl *Sema::getStdBadAlloc() const {
12192 return cast_or_null<CXXRecordDecl>(
12193 Val: StdBadAlloc.get(Source: Context.getExternalSource()));
12194}
12195
12196EnumDecl *Sema::getStdAlignValT() const {
12197 return cast_or_null<EnumDecl>(Val: StdAlignValT.get(Source: Context.getExternalSource()));
12198}
12199
12200NamespaceDecl *Sema::getStdNamespace() const {
12201 return cast_or_null<NamespaceDecl>(
12202 Val: StdNamespace.get(Source: Context.getExternalSource()));
12203}
12204
12205namespace {
12206
12207enum UnsupportedSTLSelect {
12208 USS_InvalidMember,
12209 USS_MissingMember,
12210 USS_NonTrivial,
12211 USS_Other
12212};
12213
12214struct InvalidSTLDiagnoser {
12215 Sema &S;
12216 SourceLocation Loc;
12217 QualType TyForDiags;
12218
12219 QualType operator()(UnsupportedSTLSelect Sel = USS_Other, StringRef Name = "",
12220 const VarDecl *VD = nullptr) {
12221 {
12222 auto D = S.Diag(Loc, DiagID: diag::err_std_compare_type_not_supported)
12223 << TyForDiags << ((int)Sel);
12224 if (Sel == USS_InvalidMember || Sel == USS_MissingMember) {
12225 assert(!Name.empty());
12226 D << Name;
12227 }
12228 }
12229 if (Sel == USS_InvalidMember) {
12230 S.Diag(Loc: VD->getLocation(), DiagID: diag::note_var_declared_here)
12231 << VD << VD->getSourceRange();
12232 }
12233 return QualType();
12234 }
12235};
12236} // namespace
12237
12238QualType Sema::CheckComparisonCategoryType(ComparisonCategoryType Kind,
12239 SourceLocation Loc,
12240 ComparisonCategoryUsage Usage) {
12241 assert(getLangOpts().CPlusPlus &&
12242 "Looking for comparison category type outside of C++.");
12243
12244 // Use an elaborated type for diagnostics which has a name containing the
12245 // prepended 'std' namespace but not any inline namespace names.
12246 auto TyForDiags = [&](ComparisonCategoryInfo *Info) {
12247 NestedNameSpecifier Qualifier(Context, getStdNamespace(),
12248 /*Prefix=*/std::nullopt);
12249 return Context.getTagType(Keyword: ElaboratedTypeKeyword::None, Qualifier,
12250 TD: Info->Record,
12251 /*OwnsTag=*/false);
12252 };
12253
12254 // Check if we've already successfully checked the comparison category type
12255 // before. If so, skip checking it again.
12256 ComparisonCategoryInfo *Info = Context.CompCategories.lookupInfo(Kind);
12257 if (Info && FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)]) {
12258 // The only thing we need to check is that the type has a reachable
12259 // definition in the current context.
12260 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12261 return QualType();
12262
12263 return Info->getType();
12264 }
12265
12266 // If lookup failed
12267 if (!Info) {
12268 std::string NameForDiags = "std::";
12269 NameForDiags += ComparisonCategories::getCategoryString(Kind);
12270 Diag(Loc, DiagID: diag::err_implied_comparison_category_type_not_found)
12271 << NameForDiags << (int)Usage;
12272 return QualType();
12273 }
12274
12275 assert(Info->Kind == Kind);
12276 assert(Info->Record);
12277
12278 // Update the Record decl in case we encountered a forward declaration on our
12279 // first pass. FIXME: This is a bit of a hack.
12280 if (Info->Record->hasDefinition())
12281 Info->Record = Info->Record->getDefinition();
12282
12283 if (RequireCompleteType(Loc, T: TyForDiags(Info), DiagID: diag::err_incomplete_type))
12284 return QualType();
12285
12286 InvalidSTLDiagnoser UnsupportedSTLError{.S: *this, .Loc: Loc, .TyForDiags: TyForDiags(Info)};
12287
12288 if (!Info->Record->isTriviallyCopyable())
12289 return UnsupportedSTLError(USS_NonTrivial);
12290
12291 for (const CXXBaseSpecifier &BaseSpec : Info->Record->bases()) {
12292 CXXRecordDecl *Base = BaseSpec.getType()->getAsCXXRecordDecl();
12293 // Tolerate empty base classes.
12294 if (Base->isEmpty())
12295 continue;
12296 // Reject STL implementations which have at least one non-empty base.
12297 return UnsupportedSTLError();
12298 }
12299
12300 // Check that the STL has implemented the types using a single integer field.
12301 // This expectation allows better codegen for builtin operators. We require:
12302 // (1) The class has exactly one field.
12303 // (2) The field is an integral or enumeration type.
12304 auto FIt = Info->Record->field_begin(), FEnd = Info->Record->field_end();
12305 if (std::distance(first: FIt, last: FEnd) != 1 ||
12306 !FIt->getType()->isIntegralOrEnumerationType()) {
12307 return UnsupportedSTLError();
12308 }
12309
12310 // Build each of the require values and store them in Info.
12311 for (ComparisonCategoryResult CCR :
12312 ComparisonCategories::getPossibleResultsForType(Type: Kind)) {
12313 StringRef MemName = ComparisonCategories::getResultString(Kind: CCR);
12314 ComparisonCategoryInfo::ValueInfo *ValInfo = Info->lookupValueInfo(ValueKind: CCR);
12315
12316 if (!ValInfo)
12317 return UnsupportedSTLError(USS_MissingMember, MemName);
12318
12319 VarDecl *VD = ValInfo->VD;
12320 assert(VD && "should not be null!");
12321
12322 // Attempt to diagnose reasons why the STL definition of this type
12323 // might be foobar, including it failing to be a constant expression.
12324 // TODO Handle more ways the lookup or result can be invalid.
12325 if (!VD->isStaticDataMember() ||
12326 !VD->isUsableInConstantExpressions(C: Context))
12327 return UnsupportedSTLError(USS_InvalidMember, MemName, VD);
12328
12329 // Attempt to evaluate the var decl as a constant expression and extract
12330 // the value of its first field as a ICE. If this fails, the STL
12331 // implementation is not supported.
12332 if (!ValInfo->hasValidIntValue())
12333 return UnsupportedSTLError();
12334
12335 MarkVariableReferenced(Loc, Var: VD);
12336 }
12337
12338 // We've successfully built the required types and expressions. Update
12339 // the cache and return the newly cached value.
12340 FullyCheckedComparisonCategories[static_cast<unsigned>(Kind)] = true;
12341 return Info->getType();
12342}
12343
12344NamespaceDecl *Sema::getOrCreateStdNamespace() {
12345 if (!StdNamespace) {
12346 // The "std" namespace has not yet been defined, so build one implicitly.
12347 StdNamespace = NamespaceDecl::Create(
12348 C&: Context, DC: Context.getTranslationUnitDecl(),
12349 /*Inline=*/false, StartLoc: SourceLocation(), IdLoc: SourceLocation(),
12350 Id: &PP.getIdentifierTable().get(Name: "std"),
12351 /*PrevDecl=*/nullptr, /*Nested=*/false);
12352 getStdNamespace()->setImplicit(true);
12353 // We want the created NamespaceDecl to be available for redeclaration
12354 // lookups, but not for regular name lookups.
12355 Context.getTranslationUnitDecl()->addDecl(D: getStdNamespace());
12356 getStdNamespace()->clearIdentifierNamespace();
12357 }
12358
12359 return getStdNamespace();
12360}
12361
12362static bool isStdClassTemplate(Sema &S, QualType SugaredType, QualType *TypeArg,
12363 const char *ClassName,
12364 ClassTemplateDecl **CachedDecl,
12365 const Decl **MalformedDecl) {
12366 // We're looking for implicit instantiations of
12367 // template <typename U> class std::{ClassName}.
12368
12369 if (!S.StdNamespace) // If we haven't seen namespace std yet, this can't be
12370 // it.
12371 return false;
12372
12373 auto ReportMatchingNameAsMalformed = [&](NamedDecl *D) {
12374 if (!MalformedDecl)
12375 return;
12376 if (!D)
12377 D = SugaredType->getAsTagDecl();
12378 if (!D || !D->isInStdNamespace())
12379 return;
12380 IdentifierInfo *II = D->getDeclName().getAsIdentifierInfo();
12381 if (II && II == &S.PP.getIdentifierTable().get(Name: ClassName))
12382 *MalformedDecl = D;
12383 };
12384
12385 ClassTemplateDecl *Template = nullptr;
12386 ArrayRef<TemplateArgument> Arguments;
12387 if (const TemplateSpecializationType *TST =
12388 SugaredType->getAsNonAliasTemplateSpecializationType()) {
12389 Template = dyn_cast_or_null<ClassTemplateDecl>(
12390 Val: TST->getTemplateName().getAsTemplateDecl());
12391 Arguments = TST->template_arguments();
12392 } else if (const auto *TT = SugaredType->getAs<TagType>()) {
12393 Template = TT->getTemplateDecl();
12394 Arguments = TT->getTemplateArgs(Ctx: S.Context);
12395 }
12396
12397 if (!Template) {
12398 ReportMatchingNameAsMalformed(SugaredType->getAsTagDecl());
12399 return false;
12400 }
12401
12402 if (!*CachedDecl) {
12403 // Haven't recognized std::{ClassName} yet, maybe this is it.
12404 // FIXME: It seems we should just reuse LookupStdClassTemplate but the
12405 // semantics of this are slightly different, most notably the existing
12406 // "lookup" semantics explicitly diagnose an invalid definition as an
12407 // error.
12408 CXXRecordDecl *TemplateClass = Template->getTemplatedDecl();
12409 if (TemplateClass->getIdentifier() !=
12410 &S.PP.getIdentifierTable().get(Name: ClassName) ||
12411 !S.getStdNamespace()->InEnclosingNamespaceSetOf(
12412 NS: TemplateClass->getNonTransparentDeclContext()))
12413 return false;
12414 // This is a template called std::{ClassName}, but is it the right
12415 // template?
12416 TemplateParameterList *Params = Template->getTemplateParameters();
12417 if (Params->getMinRequiredArguments() != 1 ||
12418 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0)) ||
12419 Params->getParam(Idx: 0)->isTemplateParameterPack()) {
12420 if (MalformedDecl)
12421 *MalformedDecl = TemplateClass;
12422 return false;
12423 }
12424
12425 // It's the right template.
12426 *CachedDecl = Template;
12427 }
12428
12429 if (Template->getCanonicalDecl() != (*CachedDecl)->getCanonicalDecl())
12430 return false;
12431
12432 // This is an instance of std::{ClassName}. Find the argument type.
12433 if (TypeArg) {
12434 QualType ArgType = Arguments[0].getAsType();
12435 // FIXME: Since TST only has as-written arguments, we have to perform the
12436 // only kind of conversion applicable to type arguments; in Objective-C ARC:
12437 // - If an explicitly-specified template argument type is a lifetime type
12438 // with no lifetime qualifier, the __strong lifetime qualifier is
12439 // inferred.
12440 if (S.getLangOpts().ObjCAutoRefCount && ArgType->isObjCLifetimeType() &&
12441 !ArgType.getObjCLifetime()) {
12442 Qualifiers Qs;
12443 Qs.setObjCLifetime(Qualifiers::OCL_Strong);
12444 ArgType = S.Context.getQualifiedType(T: ArgType, Qs);
12445 }
12446 *TypeArg = ArgType;
12447 }
12448
12449 return true;
12450}
12451
12452bool Sema::isStdInitializerList(QualType Ty, QualType *Element) {
12453 assert(getLangOpts().CPlusPlus &&
12454 "Looking for std::initializer_list outside of C++.");
12455
12456 // We're looking for implicit instantiations of
12457 // template <typename E> class std::initializer_list.
12458
12459 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "initializer_list",
12460 CachedDecl: &StdInitializerList, /*MalformedDecl=*/nullptr);
12461}
12462
12463bool Sema::isStdTypeIdentity(QualType Ty, QualType *Element,
12464 const Decl **MalformedDecl) {
12465 assert(getLangOpts().CPlusPlus &&
12466 "Looking for std::type_identity outside of C++.");
12467
12468 // We're looking for implicit instantiations of
12469 // template <typename T> struct std::type_identity.
12470
12471 return isStdClassTemplate(S&: *this, SugaredType: Ty, TypeArg: Element, ClassName: "type_identity",
12472 CachedDecl: &StdTypeIdentity, MalformedDecl);
12473}
12474
12475static ClassTemplateDecl *LookupStdClassTemplate(Sema &S, SourceLocation Loc,
12476 const char *ClassName,
12477 bool *WasMalformed) {
12478 if (!S.StdNamespace)
12479 return nullptr;
12480
12481 LookupResult Result(S, &S.PP.getIdentifierTable().get(Name: ClassName), Loc,
12482 Sema::LookupOrdinaryName);
12483 if (!S.LookupQualifiedName(R&: Result, LookupCtx: S.getStdNamespace()))
12484 return nullptr;
12485
12486 ClassTemplateDecl *Template = Result.getAsSingle<ClassTemplateDecl>();
12487 if (!Template) {
12488 Result.suppressDiagnostics();
12489 // We found something weird. Complain about the first thing we found.
12490 NamedDecl *Found = *Result.begin();
12491 S.Diag(Loc: Found->getLocation(), DiagID: diag::err_malformed_std_class_template)
12492 << ClassName;
12493 if (WasMalformed)
12494 *WasMalformed = true;
12495 return nullptr;
12496 }
12497
12498 // We found some template with the correct name. Now verify that it's
12499 // correct.
12500 TemplateParameterList *Params = Template->getTemplateParameters();
12501 if (Params->getMinRequiredArguments() != 1 ||
12502 !isa<TemplateTypeParmDecl>(Val: Params->getParam(Idx: 0))) {
12503 S.Diag(Loc: Template->getLocation(), DiagID: diag::err_malformed_std_class_template)
12504 << ClassName;
12505 if (WasMalformed)
12506 *WasMalformed = true;
12507 return nullptr;
12508 }
12509
12510 return Template;
12511}
12512
12513static QualType BuildStdClassTemplate(Sema &S, ClassTemplateDecl *CTD,
12514 QualType TypeParam, SourceLocation Loc) {
12515 assert(S.getStdNamespace());
12516 TemplateArgumentListInfo Args(Loc, Loc);
12517 auto TSI = S.Context.getTrivialTypeSourceInfo(T: TypeParam, Loc);
12518 Args.addArgument(Loc: TemplateArgumentLoc(TemplateArgument(TypeParam), TSI));
12519
12520 return S.CheckTemplateIdType(Keyword: ElaboratedTypeKeyword::None, Template: TemplateName(CTD),
12521 TemplateLoc: Loc, TemplateArgs&: Args, /*Scope=*/nullptr,
12522 /*ForNestedNameSpecifier=*/false);
12523}
12524
12525QualType Sema::BuildStdInitializerList(QualType Element, SourceLocation Loc) {
12526 if (!StdInitializerList) {
12527 bool WasMalformed = false;
12528 StdInitializerList =
12529 LookupStdClassTemplate(S&: *this, Loc, ClassName: "initializer_list", WasMalformed: &WasMalformed);
12530 if (!StdInitializerList) {
12531 if (!WasMalformed)
12532 Diag(Loc, DiagID: diag::err_implied_std_initializer_list_not_found);
12533 return QualType();
12534 }
12535 }
12536 return BuildStdClassTemplate(S&: *this, CTD: StdInitializerList, TypeParam: Element, Loc);
12537}
12538
12539QualType Sema::tryBuildStdTypeIdentity(QualType Type, SourceLocation Loc) {
12540 if (!StdTypeIdentity) {
12541 StdTypeIdentity = LookupStdClassTemplate(S&: *this, Loc, ClassName: "type_identity",
12542 /*WasMalformed=*/nullptr);
12543 if (!StdTypeIdentity)
12544 return QualType();
12545 }
12546 return BuildStdClassTemplate(S&: *this, CTD: StdTypeIdentity, TypeParam: Type, Loc);
12547}
12548
12549bool Sema::isInitListConstructor(const FunctionDecl *Ctor) {
12550 // C++ [dcl.init.list]p2:
12551 // A constructor is an initializer-list constructor if its first parameter
12552 // is of type std::initializer_list<E> or reference to possibly cv-qualified
12553 // std::initializer_list<E> for some type E, and either there are no other
12554 // parameters or else all other parameters have default arguments.
12555 if (!Ctor->hasOneParamOrDefaultArgs())
12556 return false;
12557
12558 QualType ArgType = Ctor->getParamDecl(i: 0)->getType();
12559 if (const ReferenceType *RT = ArgType->getAs<ReferenceType>())
12560 ArgType = RT->getPointeeType().getUnqualifiedType();
12561
12562 return isStdInitializerList(Ty: ArgType, Element: nullptr);
12563}
12564
12565/// Determine whether a using statement is in a context where it will be
12566/// apply in all contexts.
12567static bool IsUsingDirectiveInToplevelContext(DeclContext *CurContext) {
12568 switch (CurContext->getDeclKind()) {
12569 case Decl::TranslationUnit:
12570 return true;
12571 case Decl::LinkageSpec:
12572 return IsUsingDirectiveInToplevelContext(CurContext: CurContext->getParent());
12573 default:
12574 return false;
12575 }
12576}
12577
12578namespace {
12579
12580// Callback to only accept typo corrections that are namespaces.
12581class NamespaceValidatorCCC final : public CorrectionCandidateCallback {
12582public:
12583 bool ValidateCandidate(const TypoCorrection &candidate) override {
12584 if (NamedDecl *ND = candidate.getCorrectionDecl())
12585 return isa<NamespaceDecl>(Val: ND) || isa<NamespaceAliasDecl>(Val: ND);
12586 return false;
12587 }
12588
12589 std::unique_ptr<CorrectionCandidateCallback> clone() override {
12590 return std::make_unique<NamespaceValidatorCCC>(args&: *this);
12591 }
12592};
12593
12594}
12595
12596static void DiagnoseInvisibleNamespace(const TypoCorrection &Corrected,
12597 Sema &S) {
12598 auto *ND = cast<NamespaceDecl>(Val: Corrected.getFoundDecl());
12599 Module *M = ND->getOwningModule();
12600 assert(M && "hidden namespace definition not in a module?");
12601
12602 if (M->isExplicitGlobalModule())
12603 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12604 DiagID: diag::err_module_unimported_use_header)
12605 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12606 << /*Header Name*/ false;
12607 else
12608 S.Diag(Loc: Corrected.getCorrectionRange().getBegin(),
12609 DiagID: diag::err_module_unimported_use)
12610 << (int)Sema::MissingImportKind::Declaration << Corrected.getFoundDecl()
12611 << M->getTopLevelModuleName();
12612}
12613
12614static bool TryNamespaceTypoCorrection(Sema &S, LookupResult &R, Scope *Sc,
12615 CXXScopeSpec &SS,
12616 SourceLocation IdentLoc,
12617 IdentifierInfo *Ident) {
12618 R.clear();
12619 NamespaceValidatorCCC CCC{};
12620 if (TypoCorrection Corrected =
12621 S.CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S: Sc, SS: &SS, CCC,
12622 Mode: CorrectTypoKind::ErrorRecovery)) {
12623 // Generally we find it is confusing more than helpful to diagnose the
12624 // invisible namespace.
12625 // See https://github.com/llvm/llvm-project/issues/73893.
12626 //
12627 // However, we should diagnose when the users are trying to using an
12628 // invisible namespace. So we handle the case specially here.
12629 if (isa_and_nonnull<NamespaceDecl>(Val: Corrected.getFoundDecl()) &&
12630 Corrected.requiresImport()) {
12631 DiagnoseInvisibleNamespace(Corrected, S);
12632 } else if (DeclContext *DC = S.computeDeclContext(SS, EnteringContext: false)) {
12633 std::string CorrectedStr(Corrected.getAsString(LO: S.getLangOpts()));
12634 bool DroppedSpecifier =
12635 Corrected.WillReplaceSpecifier() && Ident->getName() == CorrectedStr;
12636 S.diagnoseTypo(Correction: Corrected,
12637 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_member_suggest)
12638 << Ident << DC << DroppedSpecifier << SS.getRange(),
12639 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12640 } else {
12641 S.diagnoseTypo(Correction: Corrected,
12642 TypoDiag: S.PDiag(DiagID: diag::err_using_directive_suggest) << Ident,
12643 PrevNote: S.PDiag(DiagID: diag::note_namespace_defined_here));
12644 }
12645 R.addDecl(D: Corrected.getFoundDecl());
12646 return true;
12647 }
12648 return false;
12649}
12650
12651Decl *Sema::ActOnUsingDirective(Scope *S, SourceLocation UsingLoc,
12652 SourceLocation NamespcLoc, CXXScopeSpec &SS,
12653 SourceLocation IdentLoc,
12654 IdentifierInfo *NamespcName,
12655 const ParsedAttributesView &AttrList) {
12656 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
12657 assert(NamespcName && "Invalid NamespcName.");
12658 assert(IdentLoc.isValid() && "Invalid NamespceName location.");
12659
12660 // Get the innermost enclosing declaration scope.
12661 S = S->getDeclParent();
12662
12663 UsingDirectiveDecl *UDir = nullptr;
12664 NestedNameSpecifier Qualifier = SS.getScopeRep();
12665
12666 // Lookup namespace name.
12667 LookupResult R(*this, NamespcName, IdentLoc, LookupNamespaceName);
12668 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
12669 if (R.isAmbiguous())
12670 return nullptr;
12671
12672 if (R.empty()) {
12673 R.clear();
12674 // Allow "using namespace std;" or "using namespace ::std;" even if
12675 // "std" hasn't been defined yet, for GCC compatibility.
12676 if ((!Qualifier ||
12677 Qualifier.getKind() == NestedNameSpecifier::Kind::Global) &&
12678 NamespcName->isStr(Str: "std")) {
12679 Diag(Loc: IdentLoc, DiagID: diag::ext_using_undefined_std);
12680 R.addDecl(D: getOrCreateStdNamespace());
12681 R.resolveKind();
12682 }
12683 // Otherwise, attempt typo correction.
12684 else
12685 TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident: NamespcName);
12686 }
12687
12688 if (!R.empty()) {
12689 NamedDecl *Named = R.getRepresentativeDecl();
12690 NamespaceDecl *NS = R.getAsSingle<NamespaceDecl>();
12691 assert(NS && "expected namespace decl");
12692
12693 // The use of a nested name specifier may trigger deprecation warnings.
12694 DiagnoseUseOfDecl(D: Named, Locs: IdentLoc);
12695
12696 // C++ [namespace.udir]p1:
12697 // A using-directive specifies that the names in the nominated
12698 // namespace can be used in the scope in which the
12699 // using-directive appears after the using-directive. During
12700 // unqualified name lookup (3.4.1), the names appear as if they
12701 // were declared in the nearest enclosing namespace which
12702 // contains both the using-directive and the nominated
12703 // namespace. [Note: in this context, "contains" means "contains
12704 // directly or indirectly". ]
12705
12706 // Find enclosing context containing both using-directive and
12707 // nominated namespace.
12708 DeclContext *CommonAncestor = NS;
12709 while (CommonAncestor && !CommonAncestor->Encloses(DC: CurContext))
12710 CommonAncestor = CommonAncestor->getParent();
12711
12712 UDir = UsingDirectiveDecl::Create(C&: Context, DC: CurContext, UsingLoc, NamespaceLoc: NamespcLoc,
12713 QualifierLoc: SS.getWithLocInContext(Context),
12714 IdentLoc, Nominated: Named, CommonAncestor);
12715
12716 if (IsUsingDirectiveInToplevelContext(CurContext) &&
12717 !SourceMgr.isInMainFile(Loc: SourceMgr.getExpansionLoc(Loc: IdentLoc))) {
12718 Diag(Loc: IdentLoc, DiagID: diag::warn_using_directive_in_header);
12719 }
12720
12721 PushUsingDirective(S, UDir);
12722 } else {
12723 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
12724 }
12725
12726 if (UDir) {
12727 ProcessDeclAttributeList(S, D: UDir, AttrList);
12728 ProcessAPINotes(D: UDir);
12729 }
12730
12731 return UDir;
12732}
12733
12734void Sema::PushUsingDirective(Scope *S, UsingDirectiveDecl *UDir) {
12735 // If the scope has an associated entity and the using directive is at
12736 // namespace or translation unit scope, add the UsingDirectiveDecl into
12737 // its lookup structure so qualified name lookup can find it.
12738 DeclContext *Ctx = S->getEntity();
12739 if (Ctx && !Ctx->isFunctionOrMethod())
12740 Ctx->addDecl(D: UDir);
12741 else
12742 // Otherwise, it is at block scope. The using-directives will affect lookup
12743 // only to the end of the scope.
12744 S->PushUsingDirective(UDir);
12745}
12746
12747Decl *Sema::ActOnUsingDeclaration(Scope *S, AccessSpecifier AS,
12748 SourceLocation UsingLoc,
12749 SourceLocation TypenameLoc, CXXScopeSpec &SS,
12750 UnqualifiedId &Name,
12751 SourceLocation EllipsisLoc,
12752 const ParsedAttributesView &AttrList) {
12753 assert(S->getFlags() & Scope::DeclScope && "Invalid Scope.");
12754
12755 if (SS.isEmpty()) {
12756 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_requires_qualname);
12757 return nullptr;
12758 }
12759
12760 switch (Name.getKind()) {
12761 case UnqualifiedIdKind::IK_ImplicitSelfParam:
12762 case UnqualifiedIdKind::IK_Identifier:
12763 case UnqualifiedIdKind::IK_OperatorFunctionId:
12764 case UnqualifiedIdKind::IK_LiteralOperatorId:
12765 case UnqualifiedIdKind::IK_ConversionFunctionId:
12766 break;
12767
12768 case UnqualifiedIdKind::IK_ConstructorName:
12769 case UnqualifiedIdKind::IK_ConstructorTemplateId:
12770 // C++11 inheriting constructors.
12771 Diag(Loc: Name.getBeginLoc(),
12772 DiagID: getLangOpts().CPlusPlus11
12773 ? diag::warn_cxx98_compat_using_decl_constructor
12774 : diag::err_using_decl_constructor)
12775 << SS.getRange();
12776
12777 if (getLangOpts().CPlusPlus11) break;
12778
12779 return nullptr;
12780
12781 case UnqualifiedIdKind::IK_DestructorName:
12782 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_destructor) << SS.getRange();
12783 return nullptr;
12784
12785 case UnqualifiedIdKind::IK_TemplateId:
12786 Diag(Loc: Name.getBeginLoc(), DiagID: diag::err_using_decl_template_id)
12787 << SourceRange(Name.TemplateId->LAngleLoc, Name.TemplateId->RAngleLoc);
12788 return nullptr;
12789
12790 case UnqualifiedIdKind::IK_DeductionGuideName:
12791 llvm_unreachable("cannot parse qualified deduction guide name");
12792 }
12793
12794 DeclarationNameInfo TargetNameInfo = GetNameFromUnqualifiedId(Name);
12795 DeclarationName TargetName = TargetNameInfo.getName();
12796 if (!TargetName)
12797 return nullptr;
12798
12799 // Warn about access declarations.
12800 if (UsingLoc.isInvalid()) {
12801 Diag(Loc: Name.getBeginLoc(), DiagID: getLangOpts().CPlusPlus11
12802 ? diag::err_access_decl
12803 : diag::warn_access_decl_deprecated)
12804 << FixItHint::CreateInsertion(InsertionLoc: SS.getRange().getBegin(), Code: "using ");
12805 }
12806
12807 if (EllipsisLoc.isInvalid()) {
12808 if (DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_UsingDeclaration) ||
12809 DiagnoseUnexpandedParameterPack(NameInfo: TargetNameInfo, UPPC: UPPC_UsingDeclaration))
12810 return nullptr;
12811 } else {
12812 if (!SS.getScopeRep().containsUnexpandedParameterPack() &&
12813 !TargetNameInfo.containsUnexpandedParameterPack()) {
12814 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
12815 << SourceRange(SS.getBeginLoc(), TargetNameInfo.getEndLoc());
12816 EllipsisLoc = SourceLocation();
12817 }
12818 }
12819
12820 NamedDecl *UD =
12821 BuildUsingDeclaration(S, AS, UsingLoc, HasTypenameKeyword: TypenameLoc.isValid(), TypenameLoc,
12822 SS, NameInfo: TargetNameInfo, EllipsisLoc, AttrList,
12823 /*IsInstantiation*/ false,
12824 IsUsingIfExists: AttrList.hasAttribute(K: ParsedAttr::AT_UsingIfExists));
12825 if (UD)
12826 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12827
12828 return UD;
12829}
12830
12831Decl *Sema::ActOnUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
12832 SourceLocation UsingLoc,
12833 SourceLocation EnumLoc, SourceRange TyLoc,
12834 const IdentifierInfo &II, ParsedType Ty,
12835 const CXXScopeSpec &SS) {
12836 TypeSourceInfo *TSI = nullptr;
12837 SourceLocation IdentLoc = TyLoc.getBegin();
12838 QualType EnumTy = GetTypeFromParser(Ty, TInfo: &TSI);
12839 if (EnumTy.isNull()) {
12840 Diag(Loc: IdentLoc, DiagID: isDependentScopeSpecifier(SS)
12841 ? diag::err_using_enum_is_dependent
12842 : diag::err_unknown_typename)
12843 << II.getName()
12844 << SourceRange(SS.isValid() ? SS.getBeginLoc() : IdentLoc,
12845 TyLoc.getEnd());
12846 return nullptr;
12847 }
12848
12849 if (EnumTy->isDependentType()) {
12850 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_is_dependent);
12851 return nullptr;
12852 }
12853
12854 auto *Enum = EnumTy->getAsEnumDecl();
12855 if (!Enum) {
12856 Diag(Loc: IdentLoc, DiagID: diag::err_using_enum_not_enum) << EnumTy;
12857 return nullptr;
12858 }
12859
12860 if (TSI == nullptr)
12861 TSI = Context.getTrivialTypeSourceInfo(T: EnumTy, Loc: IdentLoc);
12862
12863 auto *UD =
12864 BuildUsingEnumDeclaration(S, AS, UsingLoc, EnumLoc, NameLoc: IdentLoc, EnumType: TSI, ED: Enum);
12865
12866 if (UD)
12867 PushOnScopeChains(D: UD, S, /*AddToContext*/ false);
12868
12869 return UD;
12870}
12871
12872/// Determine whether a using declaration considers the given
12873/// declarations as "equivalent", e.g., if they are redeclarations of
12874/// the same entity or are both typedefs of the same type.
12875static bool
12876IsEquivalentForUsingDecl(ASTContext &Context, NamedDecl *D1, NamedDecl *D2) {
12877 if (D1->getCanonicalDecl() == D2->getCanonicalDecl())
12878 return true;
12879
12880 if (TypedefNameDecl *TD1 = dyn_cast<TypedefNameDecl>(Val: D1))
12881 if (TypedefNameDecl *TD2 = dyn_cast<TypedefNameDecl>(Val: D2))
12882 return Context.hasSameType(T1: TD1->getUnderlyingType(),
12883 T2: TD2->getUnderlyingType());
12884
12885 // Two using_if_exists using-declarations are equivalent if both are
12886 // unresolved.
12887 if (isa<UnresolvedUsingIfExistsDecl>(Val: D1) &&
12888 isa<UnresolvedUsingIfExistsDecl>(Val: D2))
12889 return true;
12890
12891 return false;
12892}
12893
12894bool Sema::CheckUsingShadowDecl(BaseUsingDecl *BUD, NamedDecl *Orig,
12895 const LookupResult &Previous,
12896 UsingShadowDecl *&PrevShadow) {
12897 // Diagnose finding a decl which is not from a base class of the
12898 // current class. We do this now because there are cases where this
12899 // function will silently decide not to build a shadow decl, which
12900 // will pre-empt further diagnostics.
12901 //
12902 // We don't need to do this in C++11 because we do the check once on
12903 // the qualifier.
12904 //
12905 // FIXME: diagnose the following if we care enough:
12906 // struct A { int foo; };
12907 // struct B : A { using A::foo; };
12908 // template <class T> struct C : A {};
12909 // template <class T> struct D : C<T> { using B::foo; } // <---
12910 // This is invalid (during instantiation) in C++03 because B::foo
12911 // resolves to the using decl in B, which is not a base class of D<T>.
12912 // We can't diagnose it immediately because C<T> is an unknown
12913 // specialization. The UsingShadowDecl in D<T> then points directly
12914 // to A::foo, which will look well-formed when we instantiate.
12915 // The right solution is to not collapse the shadow-decl chain.
12916 if (!getLangOpts().CPlusPlus11 && CurContext->isRecord())
12917 if (auto *Using = dyn_cast<UsingDecl>(Val: BUD)) {
12918 DeclContext *OrigDC = Orig->getDeclContext();
12919
12920 // Handle enums and anonymous structs.
12921 if (isa<EnumDecl>(Val: OrigDC))
12922 OrigDC = OrigDC->getParent();
12923 CXXRecordDecl *OrigRec = cast<CXXRecordDecl>(Val: OrigDC);
12924 while (OrigRec->isAnonymousStructOrUnion())
12925 OrigRec = cast<CXXRecordDecl>(Val: OrigRec->getDeclContext());
12926
12927 if (cast<CXXRecordDecl>(Val: CurContext)->isProvablyNotDerivedFrom(Base: OrigRec)) {
12928 if (OrigDC == CurContext) {
12929 Diag(Loc: Using->getLocation(),
12930 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
12931 << Using->getQualifierLoc().getSourceRange();
12932 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12933 Using->setInvalidDecl();
12934 return true;
12935 }
12936
12937 Diag(Loc: Using->getQualifierLoc().getBeginLoc(),
12938 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
12939 << Using->getQualifier() << cast<CXXRecordDecl>(Val: CurContext)
12940 << Using->getQualifierLoc().getSourceRange();
12941 Diag(Loc: Orig->getLocation(), DiagID: diag::note_using_decl_target);
12942 Using->setInvalidDecl();
12943 return true;
12944 }
12945 }
12946
12947 if (Previous.empty()) return false;
12948
12949 NamedDecl *Target = Orig;
12950 if (isa<UsingShadowDecl>(Val: Target))
12951 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
12952
12953 // If the target happens to be one of the previous declarations, we
12954 // don't have a conflict.
12955 //
12956 // FIXME: but we might be increasing its access, in which case we
12957 // should redeclare it.
12958 NamedDecl *NonTag = nullptr, *Tag = nullptr;
12959 bool FoundEquivalentDecl = false;
12960 for (NamedDecl *Element : Previous) {
12961 NamedDecl *D = Element->getUnderlyingDecl();
12962 // We can have UsingDecls in our Previous results because we use the same
12963 // LookupResult for checking whether the UsingDecl itself is a valid
12964 // redeclaration.
12965 if (isa<UsingDecl>(Val: D) || isa<UsingPackDecl>(Val: D) || isa<UsingEnumDecl>(Val: D))
12966 continue;
12967
12968 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: D)) {
12969 // C++ [class.mem]p19:
12970 // If T is the name of a class, then [every named member other than
12971 // a non-static data member] shall have a name different from T
12972 if (RD->isInjectedClassName() && !isa<FieldDecl>(Val: Target) &&
12973 !isa<IndirectFieldDecl>(Val: Target) &&
12974 !isa<UnresolvedUsingValueDecl>(Val: Target) &&
12975 DiagnoseClassNameShadow(
12976 DC: CurContext,
12977 Info: DeclarationNameInfo(BUD->getDeclName(), BUD->getLocation())))
12978 return true;
12979 }
12980
12981 if (IsEquivalentForUsingDecl(Context, D1: D, D2: Target)) {
12982 if (UsingShadowDecl *Shadow = dyn_cast<UsingShadowDecl>(Val: Element))
12983 PrevShadow = Shadow;
12984 FoundEquivalentDecl = true;
12985 } else if (isEquivalentInternalLinkageDeclaration(A: D, B: Target)) {
12986 // We don't conflict with an existing using shadow decl of an equivalent
12987 // declaration, but we're not a redeclaration of it.
12988 FoundEquivalentDecl = true;
12989 }
12990
12991 if (isVisible(D))
12992 (isa<TagDecl>(Val: D) ? Tag : NonTag) = D;
12993 }
12994
12995 if (FoundEquivalentDecl)
12996 return false;
12997
12998 // Always emit a diagnostic for a mismatch between an unresolved
12999 // using_if_exists and a resolved using declaration in either direction.
13000 if (isa<UnresolvedUsingIfExistsDecl>(Val: Target) !=
13001 (isa_and_nonnull<UnresolvedUsingIfExistsDecl>(Val: NonTag))) {
13002 if (!NonTag && !Tag)
13003 return false;
13004 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13005 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13006 Diag(Loc: (NonTag ? NonTag : Tag)->getLocation(),
13007 DiagID: diag::note_using_decl_conflict);
13008 BUD->setInvalidDecl();
13009 return true;
13010 }
13011
13012 if (FunctionDecl *FD = Target->getAsFunction()) {
13013 NamedDecl *OldDecl = nullptr;
13014 switch (CheckOverload(S: nullptr, New: FD, OldDecls: Previous, OldDecl,
13015 /*IsForUsingDecl*/ UseMemberUsingDeclRules: true)) {
13016 case OverloadKind::Overload:
13017 return false;
13018
13019 case OverloadKind::NonFunction:
13020 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13021 break;
13022
13023 // We found a decl with the exact signature.
13024 case OverloadKind::Match:
13025 // If we're in a record, we want to hide the target, so we
13026 // return true (without a diagnostic) to tell the caller not to
13027 // build a shadow decl.
13028 if (CurContext->isRecord())
13029 return true;
13030
13031 // If we're not in a record, this is an error.
13032 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13033 break;
13034 }
13035
13036 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13037 Diag(Loc: OldDecl->getLocation(), DiagID: diag::note_using_decl_conflict);
13038 BUD->setInvalidDecl();
13039 return true;
13040 }
13041
13042 // Target is not a function.
13043
13044 if (isa<TagDecl>(Val: Target)) {
13045 // No conflict between a tag and a non-tag.
13046 if (!Tag) return false;
13047
13048 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13049 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13050 Diag(Loc: Tag->getLocation(), DiagID: diag::note_using_decl_conflict);
13051 BUD->setInvalidDecl();
13052 return true;
13053 }
13054
13055 // No conflict between a tag and a non-tag.
13056 if (!NonTag) return false;
13057
13058 Diag(Loc: BUD->getLocation(), DiagID: diag::err_using_decl_conflict);
13059 Diag(Loc: Target->getLocation(), DiagID: diag::note_using_decl_target);
13060 Diag(Loc: NonTag->getLocation(), DiagID: diag::note_using_decl_conflict);
13061 BUD->setInvalidDecl();
13062 return true;
13063}
13064
13065/// Determine whether a direct base class is a virtual base class.
13066static bool isVirtualDirectBase(CXXRecordDecl *Derived, CXXRecordDecl *Base) {
13067 if (!Derived->getNumVBases())
13068 return false;
13069 for (auto &B : Derived->bases())
13070 if (B.getType()->getAsCXXRecordDecl() == Base)
13071 return B.isVirtual();
13072 llvm_unreachable("not a direct base class");
13073}
13074
13075UsingShadowDecl *Sema::BuildUsingShadowDecl(Scope *S, BaseUsingDecl *BUD,
13076 NamedDecl *Orig,
13077 UsingShadowDecl *PrevDecl) {
13078 // If we resolved to another shadow declaration, just coalesce them.
13079 NamedDecl *Target = Orig;
13080 if (isa<UsingShadowDecl>(Val: Target)) {
13081 Target = cast<UsingShadowDecl>(Val: Target)->getTargetDecl();
13082 assert(!isa<UsingShadowDecl>(Target) && "nested shadow declaration");
13083 }
13084
13085 NamedDecl *NonTemplateTarget = Target;
13086 if (auto *TargetTD = dyn_cast<TemplateDecl>(Val: Target))
13087 NonTemplateTarget = TargetTD->getTemplatedDecl();
13088
13089 UsingShadowDecl *Shadow;
13090 if (NonTemplateTarget && isa<CXXConstructorDecl>(Val: NonTemplateTarget)) {
13091 UsingDecl *Using = cast<UsingDecl>(Val: BUD);
13092 bool IsVirtualBase =
13093 isVirtualDirectBase(Derived: cast<CXXRecordDecl>(Val: CurContext),
13094 Base: Using->getQualifier().getAsRecordDecl());
13095 Shadow = ConstructorUsingShadowDecl::Create(
13096 C&: Context, DC: CurContext, Loc: Using->getLocation(), Using, Target: Orig, IsVirtual: IsVirtualBase);
13097 } else {
13098 Shadow = UsingShadowDecl::Create(C&: Context, DC: CurContext, Loc: BUD->getLocation(),
13099 Name: Target->getDeclName(), Introducer: BUD, Target);
13100 }
13101 BUD->addShadowDecl(S: Shadow);
13102
13103 Shadow->setAccess(BUD->getAccess());
13104 if (Orig->isInvalidDecl() || BUD->isInvalidDecl())
13105 Shadow->setInvalidDecl();
13106
13107 Shadow->setPreviousDecl(PrevDecl);
13108
13109 if (S)
13110 PushOnScopeChains(D: Shadow, S);
13111 else
13112 CurContext->addDecl(D: Shadow);
13113
13114
13115 return Shadow;
13116}
13117
13118void Sema::HideUsingShadowDecl(Scope *S, UsingShadowDecl *Shadow) {
13119 if (Shadow->getDeclName().getNameKind() ==
13120 DeclarationName::CXXConversionFunctionName)
13121 cast<CXXRecordDecl>(Val: Shadow->getDeclContext())->removeConversion(Old: Shadow);
13122
13123 // Remove it from the DeclContext...
13124 Shadow->getDeclContext()->removeDecl(D: Shadow);
13125
13126 // ...and the scope, if applicable...
13127 if (S) {
13128 S->RemoveDecl(D: Shadow);
13129 IdResolver.RemoveDecl(D: Shadow);
13130 }
13131
13132 // ...and the using decl.
13133 Shadow->getIntroducer()->removeShadowDecl(S: Shadow);
13134
13135 // TODO: complain somehow if Shadow was used. It shouldn't
13136 // be possible for this to happen, because...?
13137}
13138
13139/// Find the base specifier for a base class with the given type.
13140static CXXBaseSpecifier *findDirectBaseWithType(CXXRecordDecl *Derived,
13141 QualType DesiredBase,
13142 bool &AnyDependentBases) {
13143 // Check whether the named type is a direct base class.
13144 CanQualType CanonicalDesiredBase = DesiredBase->getCanonicalTypeUnqualified();
13145 for (auto &Base : Derived->bases()) {
13146 CanQualType BaseType = Base.getType()->getCanonicalTypeUnqualified();
13147 if (CanonicalDesiredBase == BaseType)
13148 return &Base;
13149 if (BaseType->isDependentType())
13150 AnyDependentBases = true;
13151 }
13152 return nullptr;
13153}
13154
13155namespace {
13156class UsingValidatorCCC final : public CorrectionCandidateCallback {
13157public:
13158 UsingValidatorCCC(bool HasTypenameKeyword, bool IsInstantiation,
13159 NestedNameSpecifier NNS, CXXRecordDecl *RequireMemberOf)
13160 : HasTypenameKeyword(HasTypenameKeyword),
13161 IsInstantiation(IsInstantiation), OldNNS(NNS),
13162 RequireMemberOf(RequireMemberOf) {}
13163
13164 bool ValidateCandidate(const TypoCorrection &Candidate) override {
13165 NamedDecl *ND = Candidate.getCorrectionDecl();
13166
13167 // Keywords are not valid here.
13168 if (!ND || isa<NamespaceDecl>(Val: ND))
13169 return false;
13170
13171 // Completely unqualified names are invalid for a 'using' declaration.
13172 if (Candidate.WillReplaceSpecifier() && !Candidate.getCorrectionSpecifier())
13173 return false;
13174
13175 // FIXME: Don't correct to a name that CheckUsingDeclRedeclaration would
13176 // reject.
13177
13178 if (RequireMemberOf) {
13179 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13180 if (FoundRecord && FoundRecord->isInjectedClassName()) {
13181 // No-one ever wants a using-declaration to name an injected-class-name
13182 // of a base class, unless they're declaring an inheriting constructor.
13183 ASTContext &Ctx = ND->getASTContext();
13184 if (!Ctx.getLangOpts().CPlusPlus11)
13185 return false;
13186 CanQualType FoundType = Ctx.getCanonicalTagType(TD: FoundRecord);
13187
13188 // Check that the injected-class-name is named as a member of its own
13189 // type; we don't want to suggest 'using Derived::Base;', since that
13190 // means something else.
13191 NestedNameSpecifier Specifier = Candidate.WillReplaceSpecifier()
13192 ? Candidate.getCorrectionSpecifier()
13193 : OldNNS;
13194 if (Specifier.getKind() != NestedNameSpecifier::Kind::Type ||
13195 !Ctx.hasSameType(T1: QualType(Specifier.getAsType(), 0), T2: FoundType))
13196 return false;
13197
13198 // Check that this inheriting constructor declaration actually names a
13199 // direct base class of the current class.
13200 bool AnyDependentBases = false;
13201 if (!findDirectBaseWithType(Derived: RequireMemberOf,
13202 DesiredBase: Ctx.getCanonicalTagType(TD: FoundRecord),
13203 AnyDependentBases) &&
13204 !AnyDependentBases)
13205 return false;
13206 } else {
13207 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND->getDeclContext());
13208 if (!RD || RequireMemberOf->isProvablyNotDerivedFrom(Base: RD))
13209 return false;
13210
13211 // FIXME: Check that the base class member is accessible?
13212 }
13213 } else {
13214 auto *FoundRecord = dyn_cast<CXXRecordDecl>(Val: ND);
13215 if (FoundRecord && FoundRecord->isInjectedClassName())
13216 return false;
13217 }
13218
13219 if (isa<TypeDecl>(Val: ND))
13220 return HasTypenameKeyword || !IsInstantiation;
13221
13222 return !HasTypenameKeyword;
13223 }
13224
13225 std::unique_ptr<CorrectionCandidateCallback> clone() override {
13226 return std::make_unique<UsingValidatorCCC>(args&: *this);
13227 }
13228
13229private:
13230 bool HasTypenameKeyword;
13231 bool IsInstantiation;
13232 NestedNameSpecifier OldNNS;
13233 CXXRecordDecl *RequireMemberOf;
13234};
13235} // end anonymous namespace
13236
13237void Sema::FilterUsingLookup(Scope *S, LookupResult &Previous) {
13238 // It is really dumb that we have to do this.
13239 LookupResult::Filter F = Previous.makeFilter();
13240 while (F.hasNext()) {
13241 NamedDecl *D = F.next();
13242 if (!isDeclInScope(D, Ctx: CurContext, S))
13243 F.erase();
13244 // If we found a local extern declaration that's not ordinarily visible,
13245 // and this declaration is being added to a non-block scope, ignore it.
13246 // We're only checking for scope conflicts here, not also for violations
13247 // of the linkage rules.
13248 else if (!CurContext->isFunctionOrMethod() && D->isLocalExternDecl() &&
13249 !(D->getIdentifierNamespace() & Decl::IDNS_Ordinary))
13250 F.erase();
13251 }
13252 F.done();
13253}
13254
13255NamedDecl *Sema::BuildUsingDeclaration(
13256 Scope *S, AccessSpecifier AS, SourceLocation UsingLoc,
13257 bool HasTypenameKeyword, SourceLocation TypenameLoc, CXXScopeSpec &SS,
13258 DeclarationNameInfo NameInfo, SourceLocation EllipsisLoc,
13259 const ParsedAttributesView &AttrList, bool IsInstantiation,
13260 bool IsUsingIfExists) {
13261 assert(!SS.isInvalid() && "Invalid CXXScopeSpec.");
13262 SourceLocation IdentLoc = NameInfo.getLoc();
13263 assert(IdentLoc.isValid() && "Invalid TargetName location.");
13264
13265 // FIXME: We ignore attributes for now.
13266
13267 // For an inheriting constructor declaration, the name of the using
13268 // declaration is the name of a constructor in this class, not in the
13269 // base class.
13270 DeclarationNameInfo UsingName = NameInfo;
13271 if (UsingName.getName().getNameKind() == DeclarationName::CXXConstructorName)
13272 if (auto *RD = dyn_cast<CXXRecordDecl>(Val: CurContext))
13273 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13274 Ty: Context.getCanonicalTagType(TD: RD)));
13275
13276 // Do the redeclaration lookup in the current scope.
13277 LookupResult Previous(*this, UsingName, LookupUsingDeclName,
13278 RedeclarationKind::ForVisibleRedeclaration);
13279 Previous.setHideTags(false);
13280 if (S) {
13281 LookupName(R&: Previous, S);
13282
13283 FilterUsingLookup(S, Previous);
13284 } else {
13285 assert(IsInstantiation && "no scope in non-instantiation");
13286 if (CurContext->isRecord())
13287 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13288 else {
13289 // No redeclaration check is needed here; in non-member contexts we
13290 // diagnosed all possible conflicts with other using-declarations when
13291 // building the template:
13292 //
13293 // For a dependent non-type using declaration, the only valid case is
13294 // if we instantiate to a single enumerator. We check for conflicts
13295 // between shadow declarations we introduce, and we check in the template
13296 // definition for conflicts between a non-type using declaration and any
13297 // other declaration, which together covers all cases.
13298 //
13299 // A dependent typename using declaration will never successfully
13300 // instantiate, since it will always name a class member, so we reject
13301 // that in the template definition.
13302 }
13303 }
13304
13305 // Check for invalid redeclarations.
13306 if (CheckUsingDeclRedeclaration(UsingLoc, HasTypenameKeyword,
13307 SS, NameLoc: IdentLoc, Previous))
13308 return nullptr;
13309
13310 // 'using_if_exists' doesn't make sense on an inherited constructor.
13311 if (IsUsingIfExists && UsingName.getName().getNameKind() ==
13312 DeclarationName::CXXConstructorName) {
13313 Diag(Loc: UsingLoc, DiagID: diag::err_using_if_exists_on_ctor);
13314 return nullptr;
13315 }
13316
13317 DeclContext *LookupContext = computeDeclContext(SS);
13318 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
13319 if (!LookupContext || EllipsisLoc.isValid()) {
13320 NamedDecl *D;
13321 // Dependent scope, or an unexpanded pack
13322 if (!LookupContext && CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword,
13323 SS, NameInfo, NameLoc: IdentLoc))
13324 return nullptr;
13325
13326 if (Previous.isSingleResult() &&
13327 Previous.getFoundDecl()->isTemplateParameter())
13328 DiagnoseTemplateParameterShadow(Loc: IdentLoc, PrevDecl: Previous.getFoundDecl());
13329
13330 if (HasTypenameKeyword) {
13331 // FIXME: not all declaration name kinds are legal here
13332 D = UnresolvedUsingTypenameDecl::Create(C&: Context, DC: CurContext,
13333 UsingLoc, TypenameLoc,
13334 QualifierLoc,
13335 TargetNameLoc: IdentLoc, TargetName: NameInfo.getName(),
13336 EllipsisLoc);
13337 } else {
13338 D = UnresolvedUsingValueDecl::Create(C&: Context, DC: CurContext, UsingLoc,
13339 QualifierLoc, NameInfo, EllipsisLoc);
13340 }
13341 D->setAccess(AS);
13342 CurContext->addDecl(D);
13343 ProcessDeclAttributeList(S, D, AttrList);
13344 return D;
13345 }
13346
13347 auto Build = [&](bool Invalid) {
13348 UsingDecl *UD =
13349 UsingDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc, QualifierLoc,
13350 NameInfo: UsingName, HasTypenameKeyword);
13351 UD->setAccess(AS);
13352 CurContext->addDecl(D: UD);
13353 ProcessDeclAttributeList(S, D: UD, AttrList);
13354 UD->setInvalidDecl(Invalid);
13355 return UD;
13356 };
13357 auto BuildInvalid = [&]{ return Build(true); };
13358 auto BuildValid = [&]{ return Build(false); };
13359
13360 if (RequireCompleteDeclContext(SS, DC: LookupContext))
13361 return BuildInvalid();
13362
13363 // Look up the target name.
13364 LookupResult R(*this, NameInfo, LookupOrdinaryName);
13365
13366 // Unlike most lookups, we don't always want to hide tag
13367 // declarations: tag names are visible through the using declaration
13368 // even if hidden by ordinary names, *except* in a dependent context
13369 // where they may be used by two-phase lookup.
13370 if (!IsInstantiation)
13371 R.setHideTags(false);
13372
13373 // For the purposes of this lookup, we have a base object type
13374 // equal to that of the current context.
13375 if (CurContext->isRecord()) {
13376 R.setBaseObjectType(
13377 Context.getCanonicalTagType(TD: cast<CXXRecordDecl>(Val: CurContext)));
13378 }
13379
13380 LookupQualifiedName(R, LookupCtx: LookupContext);
13381
13382 // Validate the context, now we have a lookup
13383 if (CheckUsingDeclQualifier(UsingLoc, HasTypename: HasTypenameKeyword, SS, NameInfo,
13384 NameLoc: IdentLoc, R: &R))
13385 return nullptr;
13386
13387 if (R.empty() && IsUsingIfExists)
13388 R.addDecl(D: UnresolvedUsingIfExistsDecl::Create(Ctx&: Context, DC: CurContext, Loc: UsingLoc,
13389 Name: UsingName.getName()),
13390 AS: AS_public);
13391
13392 // Try to correct typos if possible. If constructor name lookup finds no
13393 // results, that means the named class has no explicit constructors, and we
13394 // suppressed declaring implicit ones (probably because it's dependent or
13395 // invalid).
13396 if (R.empty() &&
13397 NameInfo.getName().getNameKind() != DeclarationName::CXXConstructorName) {
13398 // HACK 2017-01-08: Work around an issue with libstdc++'s detection of
13399 // ::gets. Sometimes it believes that glibc provides a ::gets in cases where
13400 // it does not. The issue was fixed in libstdc++ 6.3 (2016-12-21) and later.
13401 auto *II = NameInfo.getName().getAsIdentifierInfo();
13402 if (getLangOpts().CPlusPlus14 && II && II->isStr(Str: "gets") &&
13403 CurContext->isStdNamespace() &&
13404 isa<TranslationUnitDecl>(Val: LookupContext) &&
13405 PP.NeedsStdLibCxxWorkaroundBefore(FixedVersion: 2016'12'21) &&
13406 getSourceManager().isInSystemHeader(Loc: UsingLoc))
13407 return nullptr;
13408 UsingValidatorCCC CCC(HasTypenameKeyword, IsInstantiation, SS.getScopeRep(),
13409 dyn_cast<CXXRecordDecl>(Val: CurContext));
13410 if (TypoCorrection Corrected =
13411 CorrectTypo(Typo: R.getLookupNameInfo(), LookupKind: R.getLookupKind(), S, SS: &SS, CCC,
13412 Mode: CorrectTypoKind::ErrorRecovery)) {
13413 // We reject candidates where DroppedSpecifier == true, hence the
13414 // literal '0' below.
13415 diagnoseTypo(Correction: Corrected, TypoDiag: PDiag(DiagID: diag::err_no_member_suggest)
13416 << NameInfo.getName() << LookupContext << 0
13417 << SS.getRange());
13418
13419 // If we picked a correction with no attached Decl we can't do anything
13420 // useful with it, bail out.
13421 NamedDecl *ND = Corrected.getCorrectionDecl();
13422 if (!ND)
13423 return BuildInvalid();
13424
13425 // If we corrected to an inheriting constructor, handle it as one.
13426 auto *RD = dyn_cast<CXXRecordDecl>(Val: ND);
13427 if (RD && RD->isInjectedClassName()) {
13428 // The parent of the injected class name is the class itself.
13429 RD = cast<CXXRecordDecl>(Val: RD->getParent());
13430
13431 // Fix up the information we'll use to build the using declaration.
13432 if (Corrected.WillReplaceSpecifier()) {
13433 NestedNameSpecifierLocBuilder Builder;
13434 Builder.MakeTrivial(Context, Qualifier: Corrected.getCorrectionSpecifier(),
13435 R: QualifierLoc.getSourceRange());
13436 QualifierLoc = Builder.getWithLocInContext(Context);
13437 }
13438
13439 // In this case, the name we introduce is the name of a derived class
13440 // constructor.
13441 auto *CurClass = cast<CXXRecordDecl>(Val: CurContext);
13442 UsingName.setName(Context.DeclarationNames.getCXXConstructorName(
13443 Ty: Context.getCanonicalTagType(TD: CurClass)));
13444 UsingName.setNamedTypeInfo(nullptr);
13445 for (auto *Ctor : LookupConstructors(Class: RD))
13446 R.addDecl(D: Ctor);
13447 R.resolveKind();
13448 } else {
13449 // FIXME: Pick up all the declarations if we found an overloaded
13450 // function.
13451 UsingName.setName(ND->getDeclName());
13452 R.addDecl(D: ND);
13453 }
13454 } else {
13455 Diag(Loc: IdentLoc, DiagID: diag::err_no_member)
13456 << NameInfo.getName() << LookupContext << SS.getRange();
13457 return BuildInvalid();
13458 }
13459 }
13460
13461 if (R.isAmbiguous())
13462 return BuildInvalid();
13463
13464 if (HasTypenameKeyword) {
13465 // If we asked for a typename and got a non-type decl, error out.
13466 if (!R.getAsSingle<TypeDecl>() &&
13467 !R.getAsSingle<UnresolvedUsingIfExistsDecl>()) {
13468 Diag(Loc: IdentLoc, DiagID: diag::err_using_typename_non_type);
13469 for (const NamedDecl *D : R)
13470 Diag(Loc: D->getUnderlyingDecl()->getLocation(),
13471 DiagID: diag::note_using_decl_target);
13472 return BuildInvalid();
13473 }
13474 } else {
13475 // If we asked for a non-typename and we got a type, error out,
13476 // but only if this is an instantiation of an unresolved using
13477 // decl. Otherwise just silently find the type name.
13478 if (IsInstantiation && R.getAsSingle<TypeDecl>()) {
13479 Diag(Loc: IdentLoc, DiagID: diag::err_using_dependent_value_is_type);
13480 Diag(Loc: R.getFoundDecl()->getLocation(), DiagID: diag::note_using_decl_target);
13481 return BuildInvalid();
13482 }
13483 }
13484
13485 // C++14 [namespace.udecl]p6:
13486 // A using-declaration shall not name a namespace.
13487 if (R.getAsSingle<NamespaceDecl>()) {
13488 Diag(Loc: IdentLoc, DiagID: diag::err_using_decl_can_not_refer_to_namespace)
13489 << SS.getRange();
13490 // Suggest using 'using namespace ...' instead.
13491 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_namespace_using_decl)
13492 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(), Code: "namespace ");
13493 return BuildInvalid();
13494 }
13495
13496 UsingDecl *UD = BuildValid();
13497
13498 // Some additional rules apply to inheriting constructors.
13499 if (UsingName.getName().getNameKind() ==
13500 DeclarationName::CXXConstructorName) {
13501 // Suppress access diagnostics; the access check is instead performed at the
13502 // point of use for an inheriting constructor.
13503 R.suppressDiagnostics();
13504 if (CheckInheritingConstructorUsingDecl(UD))
13505 return UD;
13506 }
13507
13508 for (NamedDecl *D : R) {
13509 UsingShadowDecl *PrevDecl = nullptr;
13510 if (!CheckUsingShadowDecl(BUD: UD, Orig: D, Previous, PrevShadow&: PrevDecl))
13511 BuildUsingShadowDecl(S, BUD: UD, Orig: D, PrevDecl);
13512 }
13513
13514 return UD;
13515}
13516
13517NamedDecl *Sema::BuildUsingEnumDeclaration(Scope *S, AccessSpecifier AS,
13518 SourceLocation UsingLoc,
13519 SourceLocation EnumLoc,
13520 SourceLocation NameLoc,
13521 TypeSourceInfo *EnumType,
13522 EnumDecl *ED) {
13523 bool Invalid = false;
13524
13525 if (CurContext->getRedeclContext()->isRecord()) {
13526 /// In class scope, check if this is a duplicate, for better a diagnostic.
13527 DeclarationNameInfo UsingEnumName(ED->getDeclName(), NameLoc);
13528 LookupResult Previous(*this, UsingEnumName, LookupUsingDeclName,
13529 RedeclarationKind::ForVisibleRedeclaration);
13530
13531 LookupQualifiedName(R&: Previous, LookupCtx: CurContext);
13532
13533 for (NamedDecl *D : Previous)
13534 if (UsingEnumDecl *UED = dyn_cast<UsingEnumDecl>(Val: D))
13535 if (UED->getEnumDecl() == ED) {
13536 Diag(Loc: UsingLoc, DiagID: diag::err_using_enum_decl_redeclaration)
13537 << SourceRange(EnumLoc, NameLoc);
13538 Diag(Loc: D->getLocation(), DiagID: diag::note_using_enum_decl) << 1;
13539 Invalid = true;
13540 break;
13541 }
13542 }
13543
13544 if (RequireCompleteEnumDecl(D: ED, L: NameLoc))
13545 Invalid = true;
13546
13547 UsingEnumDecl *UD = UsingEnumDecl::Create(C&: Context, DC: CurContext, UsingL: UsingLoc,
13548 EnumL: EnumLoc, NameL: NameLoc, EnumType);
13549 UD->setAccess(AS);
13550 CurContext->addDecl(D: UD);
13551
13552 if (Invalid) {
13553 UD->setInvalidDecl();
13554 return UD;
13555 }
13556
13557 // Create the shadow decls for each enumerator
13558 for (EnumConstantDecl *EC : ED->enumerators()) {
13559 UsingShadowDecl *PrevDecl = nullptr;
13560 DeclarationNameInfo DNI(EC->getDeclName(), EC->getLocation());
13561 LookupResult Previous(*this, DNI, LookupOrdinaryName,
13562 RedeclarationKind::ForVisibleRedeclaration);
13563 LookupName(R&: Previous, S);
13564 FilterUsingLookup(S, Previous);
13565
13566 if (!CheckUsingShadowDecl(BUD: UD, Orig: EC, Previous, PrevShadow&: PrevDecl))
13567 BuildUsingShadowDecl(S, BUD: UD, Orig: EC, PrevDecl);
13568 }
13569
13570 return UD;
13571}
13572
13573NamedDecl *Sema::BuildUsingPackDecl(NamedDecl *InstantiatedFrom,
13574 ArrayRef<NamedDecl *> Expansions) {
13575 assert(isa<UnresolvedUsingValueDecl>(InstantiatedFrom) ||
13576 isa<UnresolvedUsingTypenameDecl>(InstantiatedFrom) ||
13577 isa<UsingPackDecl>(InstantiatedFrom));
13578
13579 auto *UPD =
13580 UsingPackDecl::Create(C&: Context, DC: CurContext, InstantiatedFrom, UsingDecls: Expansions);
13581 UPD->setAccess(InstantiatedFrom->getAccess());
13582 CurContext->addDecl(D: UPD);
13583 return UPD;
13584}
13585
13586bool Sema::CheckInheritingConstructorUsingDecl(UsingDecl *UD) {
13587 assert(!UD->hasTypename() && "expecting a constructor name");
13588
13589 QualType SourceType(UD->getQualifier().getAsType(), 0);
13590 CXXRecordDecl *TargetClass = cast<CXXRecordDecl>(Val: CurContext);
13591
13592 // Check whether the named type is a direct base class.
13593 bool AnyDependentBases = false;
13594 auto *Base =
13595 findDirectBaseWithType(Derived: TargetClass, DesiredBase: SourceType, AnyDependentBases);
13596 if (!Base && !AnyDependentBases) {
13597 Diag(Loc: UD->getUsingLoc(), DiagID: diag::err_using_decl_constructor_not_in_direct_base)
13598 << UD->getNameInfo().getSourceRange() << SourceType << TargetClass;
13599 UD->setInvalidDecl();
13600 return true;
13601 }
13602
13603 if (Base)
13604 Base->setInheritConstructors();
13605
13606 return false;
13607}
13608
13609bool Sema::CheckUsingDeclRedeclaration(SourceLocation UsingLoc,
13610 bool HasTypenameKeyword,
13611 const CXXScopeSpec &SS,
13612 SourceLocation NameLoc,
13613 const LookupResult &Prev) {
13614 NestedNameSpecifier Qual = SS.getScopeRep();
13615
13616 // C++03 [namespace.udecl]p8:
13617 // C++0x [namespace.udecl]p10:
13618 // A using-declaration is a declaration and can therefore be used
13619 // repeatedly where (and only where) multiple declarations are
13620 // allowed.
13621 //
13622 // That's in non-member contexts.
13623 if (!CurContext->getRedeclContext()->isRecord()) {
13624 // A dependent qualifier outside a class can only ever resolve to an
13625 // enumeration type. Therefore it conflicts with any other non-type
13626 // declaration in the same scope.
13627 // FIXME: How should we check for dependent type-type conflicts at block
13628 // scope?
13629 if (Qual.isDependent() && !HasTypenameKeyword) {
13630 for (auto *D : Prev) {
13631 if (!isa<TypeDecl>(Val: D) && !isa<UsingDecl>(Val: D) && !isa<UsingPackDecl>(Val: D)) {
13632 bool OldCouldBeEnumerator =
13633 isa<UnresolvedUsingValueDecl>(Val: D) || isa<EnumConstantDecl>(Val: D);
13634 Diag(Loc: NameLoc,
13635 DiagID: OldCouldBeEnumerator ? diag::err_redefinition
13636 : diag::err_redefinition_different_kind)
13637 << Prev.getLookupName();
13638 Diag(Loc: D->getLocation(), DiagID: diag::note_previous_definition);
13639 return true;
13640 }
13641 }
13642 }
13643 return false;
13644 }
13645
13646 NestedNameSpecifier CNNS = Qual.getCanonical();
13647 for (const NamedDecl *D : Prev) {
13648 bool DTypename;
13649 NestedNameSpecifier DQual = std::nullopt;
13650 if (const auto *UD = dyn_cast<UsingDecl>(Val: D)) {
13651 DTypename = UD->hasTypename();
13652 DQual = UD->getQualifier();
13653 } else if (const auto *UD = dyn_cast<UnresolvedUsingValueDecl>(Val: D)) {
13654 DTypename = false;
13655 DQual = UD->getQualifier();
13656 } else if (const auto *UD = dyn_cast<UnresolvedUsingTypenameDecl>(Val: D)) {
13657 DTypename = true;
13658 DQual = UD->getQualifier();
13659 } else
13660 continue;
13661
13662 // using decls differ if one says 'typename' and the other doesn't.
13663 // FIXME: non-dependent using decls?
13664 if (HasTypenameKeyword != DTypename) continue;
13665
13666 // using decls differ if they name different scopes (but note that
13667 // template instantiation can cause this check to trigger when it
13668 // didn't before instantiation).
13669 if (CNNS != DQual.getCanonical())
13670 continue;
13671
13672 Diag(Loc: NameLoc, DiagID: diag::err_using_decl_redeclaration) << SS.getRange();
13673 Diag(Loc: D->getLocation(), DiagID: diag::note_using_decl) << 1;
13674 return true;
13675 }
13676
13677 return false;
13678}
13679
13680bool Sema::CheckUsingDeclQualifier(SourceLocation UsingLoc, bool HasTypename,
13681 const CXXScopeSpec &SS,
13682 const DeclarationNameInfo &NameInfo,
13683 SourceLocation NameLoc,
13684 const LookupResult *R, const UsingDecl *UD) {
13685 DeclContext *NamedContext = computeDeclContext(SS);
13686 assert(bool(NamedContext) == (R || UD) && !(R && UD) &&
13687 "resolvable context must have exactly one set of decls");
13688
13689 // C++ 20 permits using an enumerator that does not have a class-hierarchy
13690 // relationship.
13691 bool Cxx20Enumerator = false;
13692 if (NamedContext) {
13693 EnumConstantDecl *EC = nullptr;
13694 if (R)
13695 EC = R->getAsSingle<EnumConstantDecl>();
13696 else if (UD && UD->shadow_size() == 1)
13697 EC = dyn_cast<EnumConstantDecl>(Val: UD->shadow_begin()->getTargetDecl());
13698 if (EC)
13699 Cxx20Enumerator = getLangOpts().CPlusPlus20;
13700
13701 if (auto *ED = dyn_cast<EnumDecl>(Val: NamedContext)) {
13702 // C++14 [namespace.udecl]p7:
13703 // A using-declaration shall not name a scoped enumerator.
13704 // C++20 p1099 permits enumerators.
13705 if (EC && R && ED->isScoped())
13706 DiagCompat(Loc: SS.getBeginLoc(), CompatDiagId: diag_compat::using_decl_scoped_enumerator)
13707 << SS.getRange();
13708
13709 // We want to consider the scope of the enumerator
13710 NamedContext = ED->getDeclContext();
13711 }
13712 }
13713
13714 if (!CurContext->isRecord()) {
13715 // C++03 [namespace.udecl]p3:
13716 // C++0x [namespace.udecl]p8:
13717 // A using-declaration for a class member shall be a member-declaration.
13718 // C++20 [namespace.udecl]p7
13719 // ... other than an enumerator ...
13720
13721 // If we weren't able to compute a valid scope, it might validly be a
13722 // dependent class or enumeration scope. If we have a 'typename' keyword,
13723 // the scope must resolve to a class type.
13724 if (NamedContext ? !NamedContext->getRedeclContext()->isRecord()
13725 : !HasTypename)
13726 return false; // OK
13727
13728 Diag(Loc: NameLoc,
13729 DiagID: Cxx20Enumerator
13730 ? diag::warn_cxx17_compat_using_decl_class_member_enumerator
13731 : diag::err_using_decl_can_not_refer_to_class_member)
13732 << SS.getRange();
13733
13734 if (Cxx20Enumerator)
13735 return false; // OK
13736
13737 auto *RD = NamedContext
13738 ? cast<CXXRecordDecl>(Val: NamedContext->getRedeclContext())
13739 : nullptr;
13740 if (RD && !RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec &>(SS), DC: RD)) {
13741 // See if there's a helpful fixit
13742
13743 if (!R) {
13744 // We will have already diagnosed the problem on the template
13745 // definition, Maybe we should do so again?
13746 } else if (R->getAsSingle<TypeDecl>()) {
13747 if (getLangOpts().CPlusPlus11) {
13748 // Convert 'using X::Y;' to 'using Y = X::Y;'.
13749 Diag(Loc: SS.getBeginLoc(), DiagID: diag::note_using_decl_class_member_workaround)
13750 << diag::MemClassWorkaround::AliasDecl
13751 << FixItHint::CreateInsertion(InsertionLoc: SS.getBeginLoc(),
13752 Code: NameInfo.getName().getAsString() +
13753 " = ");
13754 } else {
13755 // Convert 'using X::Y;' to 'typedef X::Y Y;'.
13756 SourceLocation InsertLoc = getLocForEndOfToken(Loc: NameInfo.getEndLoc());
13757 Diag(Loc: InsertLoc, DiagID: diag::note_using_decl_class_member_workaround)
13758 << diag::MemClassWorkaround::TypedefDecl
13759 << FixItHint::CreateReplacement(RemoveRange: UsingLoc, Code: "typedef")
13760 << FixItHint::CreateInsertion(
13761 InsertionLoc: InsertLoc, Code: " " + NameInfo.getName().getAsString());
13762 }
13763 } else if (R->getAsSingle<VarDecl>()) {
13764 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13765 // repeating the type of the static data member here.
13766 FixItHint FixIt;
13767 if (getLangOpts().CPlusPlus11) {
13768 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13769 FixIt = FixItHint::CreateReplacement(
13770 RemoveRange: UsingLoc, Code: "auto &" + NameInfo.getName().getAsString() + " = ");
13771 }
13772
13773 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13774 << diag::MemClassWorkaround::ReferenceDecl << FixIt;
13775 } else if (R->getAsSingle<EnumConstantDecl>()) {
13776 // Don't provide a fixit outside C++11 mode; we don't want to suggest
13777 // repeating the type of the enumeration here, and we can't do so if
13778 // the type is anonymous.
13779 FixItHint FixIt;
13780 if (getLangOpts().CPlusPlus11) {
13781 // Convert 'using X::Y;' to 'auto &Y = X::Y;'.
13782 FixIt = FixItHint::CreateReplacement(
13783 RemoveRange: UsingLoc,
13784 Code: "constexpr auto " + NameInfo.getName().getAsString() + " = ");
13785 }
13786
13787 Diag(Loc: UsingLoc, DiagID: diag::note_using_decl_class_member_workaround)
13788 << (getLangOpts().CPlusPlus11
13789 ? diag::MemClassWorkaround::ConstexprVar
13790 : diag::MemClassWorkaround::ConstVar)
13791 << FixIt;
13792 }
13793 }
13794
13795 return true; // Fail
13796 }
13797
13798 // If the named context is dependent, we can't decide much.
13799 if (!NamedContext) {
13800 // FIXME: in C++0x, we can diagnose if we can prove that the
13801 // nested-name-specifier does not refer to a base class, which is
13802 // still possible in some cases.
13803
13804 // Otherwise we have to conservatively report that things might be
13805 // okay.
13806 return false;
13807 }
13808
13809 // The current scope is a record.
13810 if (!NamedContext->isRecord()) {
13811 // Ideally this would point at the last name in the specifier,
13812 // but we don't have that level of source info.
13813 Diag(Loc: SS.getBeginLoc(),
13814 DiagID: Cxx20Enumerator
13815 ? diag::warn_cxx17_compat_using_decl_non_member_enumerator
13816 : diag::err_using_decl_nested_name_specifier_is_not_class)
13817 << SS.getScopeRep() << SS.getRange();
13818
13819 if (Cxx20Enumerator)
13820 return false; // OK
13821
13822 return true;
13823 }
13824
13825 if (!NamedContext->isDependentContext() &&
13826 RequireCompleteDeclContext(SS&: const_cast<CXXScopeSpec&>(SS), DC: NamedContext))
13827 return true;
13828
13829 // C++26 [namespace.udecl]p3:
13830 // In a using-declaration used as a member-declaration, each
13831 // using-declarator shall either name an enumerator or have a
13832 // nested-name-specifier naming a base class of the current class
13833 // ([expr.prim.this]). ...
13834 // "have a nested-name-specifier naming a base class of the current class"
13835 // was introduced by CWG400.
13836
13837 if (cast<CXXRecordDecl>(Val: CurContext)
13838 ->isProvablyNotDerivedFrom(Base: cast<CXXRecordDecl>(Val: NamedContext))) {
13839
13840 if (Cxx20Enumerator) {
13841 Diag(Loc: NameLoc, DiagID: diag::warn_cxx17_compat_using_decl_non_member_enumerator)
13842 << SS.getScopeRep() << SS.getRange();
13843 return false;
13844 }
13845
13846 if (CurContext == NamedContext) {
13847 Diag(Loc: SS.getBeginLoc(),
13848 DiagID: diag::err_using_decl_nested_name_specifier_is_current_class)
13849 << SS.getRange();
13850 return true;
13851 }
13852
13853 if (!cast<CXXRecordDecl>(Val: NamedContext)->isInvalidDecl()) {
13854 Diag(Loc: SS.getBeginLoc(),
13855 DiagID: diag::err_using_decl_nested_name_specifier_is_not_base_class)
13856 << SS.getScopeRep() << cast<CXXRecordDecl>(Val: CurContext)
13857 << SS.getRange();
13858 }
13859 return true;
13860 }
13861
13862 return false;
13863}
13864
13865Decl *Sema::ActOnAliasDeclaration(Scope *S, AccessSpecifier AS,
13866 MultiTemplateParamsArg TemplateParamLists,
13867 SourceLocation UsingLoc, UnqualifiedId &Name,
13868 const ParsedAttributesView &AttrList,
13869 TypeResult Type, Decl *DeclFromDeclSpec) {
13870
13871 if (Type.isInvalid())
13872 return nullptr;
13873
13874 bool Invalid = false;
13875 DeclarationNameInfo NameInfo = GetNameFromUnqualifiedId(Name);
13876 TypeSourceInfo *TInfo = nullptr;
13877 GetTypeFromParser(Ty: Type.get(), TInfo: &TInfo);
13878
13879 if (DiagnoseClassNameShadow(DC: CurContext, Info: NameInfo))
13880 return nullptr;
13881
13882 if (DiagnoseUnexpandedParameterPack(Loc: Name.StartLocation, T: TInfo,
13883 UPPC: UPPC_DeclarationType)) {
13884 Invalid = true;
13885 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
13886 Loc: TInfo->getTypeLoc().getBeginLoc());
13887 }
13888
13889 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
13890 TemplateParamLists.size()
13891 ? forRedeclarationInCurContext()
13892 : RedeclarationKind::ForVisibleRedeclaration);
13893 LookupName(R&: Previous, S);
13894
13895 // Warn about shadowing the name of a template parameter.
13896 if (Previous.isSingleResult() &&
13897 Previous.getFoundDecl()->isTemplateParameter()) {
13898 DiagnoseTemplateParameterShadow(Loc: Name.StartLocation,PrevDecl: Previous.getFoundDecl());
13899 Previous.clear();
13900 }
13901
13902 assert(Name.getKind() == UnqualifiedIdKind::IK_Identifier &&
13903 "name in alias declaration must be an identifier");
13904 TypeAliasDecl *NewTD = TypeAliasDecl::Create(C&: Context, DC: CurContext, StartLoc: UsingLoc,
13905 IdLoc: Name.StartLocation,
13906 Id: Name.Identifier, TInfo);
13907
13908 NewTD->setAccess(AS);
13909
13910 if (Invalid)
13911 NewTD->setInvalidDecl();
13912
13913 ProcessDeclAttributeList(S, D: NewTD, AttrList);
13914 AddPragmaAttributes(S, D: NewTD);
13915 ProcessAPINotes(D: NewTD);
13916
13917 CheckTypedefForVariablyModifiedType(S, D: NewTD);
13918 Invalid |= NewTD->isInvalidDecl();
13919
13920 // Get the innermost enclosing declaration scope.
13921 S = S->getDeclParent();
13922
13923 bool Redeclaration = false;
13924
13925 NamedDecl *NewND;
13926 if (TemplateParamLists.size()) {
13927 TypeAliasTemplateDecl *OldDecl = nullptr;
13928 TemplateParameterList *OldTemplateParams = nullptr;
13929
13930 TemplateParameterList *TemplateParams = TemplateParamLists[0];
13931 if (TemplateParamLists.size() != 1) {
13932 Diag(Loc: UsingLoc, DiagID: diag::err_alias_template_extra_headers)
13933 << SourceRange(TemplateParamLists[1]->getTemplateLoc(),
13934 TemplateParamLists[TemplateParamLists.size()-1]->getRAngleLoc());
13935 Invalid = true;
13936
13937 // Recover by picking the last non-empty template parameter list.
13938 auto It = llvm::find_if(
13939 Range: llvm::reverse(C&: TemplateParamLists),
13940 P: [](TemplateParameterList *TPL) { return !TPL->empty(); });
13941 assert(It != TemplateParamLists.rend() &&
13942 "if all template parameter lists were empty, this should have "
13943 "been rejected as an explicit specialization");
13944 TemplateParams = *It;
13945 }
13946
13947 // Check that we can declare a template here.
13948 if (CheckTemplateDeclScope(S, TemplateParams))
13949 return nullptr;
13950
13951 // Only consider previous declarations in the same scope.
13952 FilterLookupForScope(R&: Previous, Ctx: CurContext, S, /*ConsiderLinkage*/false,
13953 /*ExplicitInstantiationOrSpecialization*/AllowInlineNamespace: false);
13954 if (!Previous.empty()) {
13955 Redeclaration = true;
13956
13957 OldDecl = Previous.getAsSingle<TypeAliasTemplateDecl>();
13958 if (!OldDecl && !Invalid) {
13959 Diag(Loc: UsingLoc, DiagID: diag::err_redefinition_different_kind)
13960 << Name.Identifier;
13961
13962 NamedDecl *OldD = Previous.getRepresentativeDecl();
13963 if (OldD->getLocation().isValid())
13964 Diag(Loc: OldD->getLocation(), DiagID: diag::note_previous_definition);
13965
13966 Invalid = true;
13967 }
13968
13969 if (!Invalid && OldDecl && !OldDecl->isInvalidDecl()) {
13970 if (TemplateParameterListsAreEqual(New: TemplateParams,
13971 Old: OldDecl->getTemplateParameters(),
13972 /*Complain=*/true,
13973 Kind: TPL_TemplateMatch))
13974 OldTemplateParams =
13975 OldDecl->getMostRecentDecl()->getTemplateParameters();
13976 else
13977 Invalid = true;
13978
13979 TypeAliasDecl *OldTD = OldDecl->getTemplatedDecl();
13980 if (!Invalid &&
13981 !Context.hasSameType(T1: OldTD->getUnderlyingType(),
13982 T2: NewTD->getUnderlyingType())) {
13983 // FIXME: The C++0x standard does not clearly say this is ill-formed,
13984 // but we can't reasonably accept it.
13985 Diag(Loc: NewTD->getLocation(), DiagID: diag::err_redefinition_different_typedef)
13986 << 2 << NewTD->getUnderlyingType() << OldTD->getUnderlyingType();
13987 if (OldTD->getLocation().isValid())
13988 Diag(Loc: OldTD->getLocation(), DiagID: diag::note_previous_definition);
13989 Invalid = true;
13990 }
13991 }
13992 }
13993
13994 // Merge any previous default template arguments into our parameters,
13995 // and check the parameter list.
13996 if (CheckTemplateParameterList(NewParams: TemplateParams, OldParams: OldTemplateParams,
13997 TPC: TPC_Other))
13998 return nullptr;
13999
14000 TypeAliasTemplateDecl *NewDecl =
14001 TypeAliasTemplateDecl::Create(C&: Context, DC: CurContext, L: UsingLoc,
14002 Name: Name.Identifier, Params: TemplateParams,
14003 Decl: NewTD);
14004 NewTD->setDescribedAliasTemplate(NewDecl);
14005
14006 NewDecl->setAccess(AS);
14007
14008 if (Invalid)
14009 NewDecl->setInvalidDecl();
14010 else if (OldDecl) {
14011 NewDecl->setPreviousDecl(OldDecl);
14012 CheckRedeclarationInModule(New: NewDecl, Old: OldDecl);
14013 }
14014
14015 NewND = NewDecl;
14016 } else {
14017 if (auto *TD = dyn_cast_or_null<TagDecl>(Val: DeclFromDeclSpec)) {
14018 setTagNameForLinkagePurposes(TagFromDeclSpec: TD, NewTD);
14019 handleTagNumbering(Tag: TD, TagScope: S);
14020 }
14021 ActOnTypedefNameDecl(S, DC: CurContext, D: NewTD, Previous, Redeclaration);
14022 NewND = NewTD;
14023 }
14024
14025 PushOnScopeChains(D: NewND, S);
14026 ActOnDocumentableDecl(D: NewND);
14027 return NewND;
14028}
14029
14030Decl *Sema::ActOnNamespaceAliasDef(Scope *S, SourceLocation NamespaceLoc,
14031 SourceLocation AliasLoc,
14032 IdentifierInfo *Alias, CXXScopeSpec &SS,
14033 SourceLocation IdentLoc,
14034 IdentifierInfo *Ident) {
14035
14036 // Lookup the namespace name.
14037 LookupResult R(*this, Ident, IdentLoc, LookupNamespaceName);
14038 LookupParsedName(R, S, SS: &SS, /*ObjectType=*/QualType());
14039
14040 if (R.isAmbiguous())
14041 return nullptr;
14042
14043 if (R.empty()) {
14044 if (!TryNamespaceTypoCorrection(S&: *this, R, Sc: S, SS, IdentLoc, Ident)) {
14045 Diag(Loc: IdentLoc, DiagID: diag::err_expected_namespace_name) << SS.getRange();
14046 return nullptr;
14047 }
14048 }
14049 assert(!R.isAmbiguous() && !R.empty());
14050 auto *ND = cast<NamespaceBaseDecl>(Val: R.getRepresentativeDecl());
14051
14052 // Check if we have a previous declaration with the same name.
14053 LookupResult PrevR(*this, Alias, AliasLoc, LookupOrdinaryName,
14054 RedeclarationKind::ForVisibleRedeclaration);
14055 LookupName(R&: PrevR, S);
14056
14057 // Check we're not shadowing a template parameter.
14058 if (PrevR.isSingleResult() && PrevR.getFoundDecl()->isTemplateParameter()) {
14059 DiagnoseTemplateParameterShadow(Loc: AliasLoc, PrevDecl: PrevR.getFoundDecl());
14060 PrevR.clear();
14061 }
14062
14063 // Filter out any other lookup result from an enclosing scope.
14064 FilterLookupForScope(R&: PrevR, Ctx: CurContext, S, /*ConsiderLinkage*/false,
14065 /*AllowInlineNamespace*/false);
14066
14067 // Find the previous declaration and check that we can redeclare it.
14068 NamespaceAliasDecl *Prev = nullptr;
14069 if (PrevR.isSingleResult()) {
14070 NamedDecl *PrevDecl = PrevR.getRepresentativeDecl();
14071 if (NamespaceAliasDecl *AD = dyn_cast<NamespaceAliasDecl>(Val: PrevDecl)) {
14072 // We already have an alias with the same name that points to the same
14073 // namespace; check that it matches.
14074 if (AD->getNamespace()->Equals(DC: getNamespaceDecl(D: ND))) {
14075 Prev = AD;
14076 } else if (isVisible(D: PrevDecl)) {
14077 Diag(Loc: AliasLoc, DiagID: diag::err_redefinition_different_namespace_alias)
14078 << Alias;
14079 Diag(Loc: AD->getLocation(), DiagID: diag::note_previous_namespace_alias)
14080 << AD->getNamespace();
14081 return nullptr;
14082 }
14083 } else if (isVisible(D: PrevDecl)) {
14084 unsigned DiagID = isa<NamespaceDecl>(Val: PrevDecl->getUnderlyingDecl())
14085 ? diag::err_redefinition
14086 : diag::err_redefinition_different_kind;
14087 Diag(Loc: AliasLoc, DiagID) << Alias;
14088 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
14089 return nullptr;
14090 }
14091 }
14092
14093 // The use of a nested name specifier may trigger deprecation warnings.
14094 DiagnoseUseOfDecl(D: ND, Locs: IdentLoc);
14095
14096 NamespaceAliasDecl *AliasDecl =
14097 NamespaceAliasDecl::Create(C&: Context, DC: CurContext, NamespaceLoc, AliasLoc,
14098 Alias, QualifierLoc: SS.getWithLocInContext(Context),
14099 IdentLoc, Namespace: ND);
14100 if (Prev)
14101 AliasDecl->setPreviousDecl(Prev);
14102
14103 PushOnScopeChains(D: AliasDecl, S);
14104 return AliasDecl;
14105}
14106
14107namespace {
14108struct SpecialMemberExceptionSpecInfo
14109 : SpecialMemberVisitor<SpecialMemberExceptionSpecInfo> {
14110 SourceLocation Loc;
14111 Sema::ImplicitExceptionSpecification ExceptSpec;
14112
14113 SpecialMemberExceptionSpecInfo(Sema &S, CXXMethodDecl *MD,
14114 CXXSpecialMemberKind CSM,
14115 Sema::InheritedConstructorInfo *ICI,
14116 SourceLocation Loc)
14117 : SpecialMemberVisitor(S, MD, CSM, ICI), Loc(Loc), ExceptSpec(S) {}
14118
14119 bool visitBase(CXXBaseSpecifier *Base);
14120 bool visitField(FieldDecl *FD);
14121
14122 void visitClassSubobject(CXXRecordDecl *Class, Subobject Subobj,
14123 unsigned Quals);
14124
14125 void visitSubobjectCall(Subobject Subobj,
14126 Sema::SpecialMemberOverloadResult SMOR);
14127};
14128}
14129
14130bool SpecialMemberExceptionSpecInfo::visitBase(CXXBaseSpecifier *Base) {
14131 auto *BaseClass = Base->getType()->getAsCXXRecordDecl();
14132 if (!BaseClass)
14133 return false;
14134
14135 Sema::SpecialMemberOverloadResult SMOR = lookupInheritedCtor(Class: BaseClass);
14136 if (auto *BaseCtor = SMOR.getMethod()) {
14137 visitSubobjectCall(Subobj: Base, SMOR: BaseCtor);
14138 return false;
14139 }
14140
14141 visitClassSubobject(Class: BaseClass, Subobj: Base, Quals: 0);
14142 return false;
14143}
14144
14145bool SpecialMemberExceptionSpecInfo::visitField(FieldDecl *FD) {
14146 if (CSM == CXXSpecialMemberKind::DefaultConstructor &&
14147 FD->hasInClassInitializer()) {
14148 Expr *E = FD->getInClassInitializer();
14149 if (!E)
14150 // FIXME: It's a little wasteful to build and throw away a
14151 // CXXDefaultInitExpr here.
14152 // FIXME: We should have a single context note pointing at Loc, and
14153 // this location should be MD->getLocation() instead, since that's
14154 // the location where we actually use the default init expression.
14155 E = S.BuildCXXCtorDefaultInitExpr(Loc, Field: FD).get();
14156 if (E)
14157 ExceptSpec.CalledExpr(E);
14158 } else if (auto *RD = S.Context.getBaseElementType(QT: FD->getType())
14159 ->getAsCXXRecordDecl()) {
14160 visitClassSubobject(Class: RD, Subobj: FD, Quals: FD->getType().getCVRQualifiers());
14161 }
14162 return false;
14163}
14164
14165void SpecialMemberExceptionSpecInfo::visitClassSubobject(CXXRecordDecl *Class,
14166 Subobject Subobj,
14167 unsigned Quals) {
14168 FieldDecl *Field = dyn_cast<FieldDecl *>(Val&: Subobj);
14169 bool IsMutable = Field && Field->isMutable();
14170 visitSubobjectCall(Subobj, SMOR: lookupIn(Class, Quals, IsMutable));
14171}
14172
14173void SpecialMemberExceptionSpecInfo::visitSubobjectCall(
14174 Subobject Subobj, Sema::SpecialMemberOverloadResult SMOR) {
14175 // Note, if lookup fails, it doesn't matter what exception specification we
14176 // choose because the special member will be deleted.
14177 if (CXXMethodDecl *MD = SMOR.getMethod())
14178 ExceptSpec.CalledDecl(CallLoc: getSubobjectLoc(Subobj), Method: MD);
14179}
14180
14181bool Sema::tryResolveExplicitSpecifier(ExplicitSpecifier &ExplicitSpec) {
14182 llvm::APSInt Result;
14183 ExprResult Converted = CheckConvertedConstantExpression(
14184 From: ExplicitSpec.getExpr(), T: Context.BoolTy, Value&: Result, CCE: CCEKind::ExplicitBool);
14185 ExplicitSpec.setExpr(Converted.get());
14186 if (Converted.isUsable() && !Converted.get()->isValueDependent()) {
14187 ExplicitSpec.setKind(Result.getBoolValue()
14188 ? ExplicitSpecKind::ResolvedTrue
14189 : ExplicitSpecKind::ResolvedFalse);
14190 return true;
14191 }
14192 ExplicitSpec.setKind(ExplicitSpecKind::Unresolved);
14193 return false;
14194}
14195
14196ExplicitSpecifier Sema::ActOnExplicitBoolSpecifier(Expr *ExplicitExpr) {
14197 ExplicitSpecifier ES(ExplicitExpr, ExplicitSpecKind::Unresolved);
14198 if (!ExplicitExpr->isTypeDependent())
14199 tryResolveExplicitSpecifier(ExplicitSpec&: ES);
14200 return ES;
14201}
14202
14203static Sema::ImplicitExceptionSpecification
14204ComputeDefaultedSpecialMemberExceptionSpec(
14205 Sema &S, SourceLocation Loc, CXXMethodDecl *MD, CXXSpecialMemberKind CSM,
14206 Sema::InheritedConstructorInfo *ICI) {
14207 ComputingExceptionSpec CES(S, MD, Loc);
14208
14209 CXXRecordDecl *ClassDecl = MD->getParent();
14210
14211 // C++ [except.spec]p14:
14212 // An implicitly declared special member function (Clause 12) shall have an
14213 // exception-specification. [...]
14214 SpecialMemberExceptionSpecInfo Info(S, MD, CSM, ICI, MD->getLocation());
14215 if (ClassDecl->isInvalidDecl())
14216 return Info.ExceptSpec;
14217
14218 // FIXME: If this diagnostic fires, we're probably missing a check for
14219 // attempting to resolve an exception specification before it's known
14220 // at a higher level.
14221 if (S.RequireCompleteType(Loc: MD->getLocation(),
14222 T: S.Context.getCanonicalTagType(TD: ClassDecl),
14223 DiagID: diag::err_exception_spec_incomplete_type))
14224 return Info.ExceptSpec;
14225
14226 // C++1z [except.spec]p7:
14227 // [Look for exceptions thrown by] a constructor selected [...] to
14228 // initialize a potentially constructed subobject,
14229 // C++1z [except.spec]p8:
14230 // The exception specification for an implicitly-declared destructor, or a
14231 // destructor without a noexcept-specifier, is potentially-throwing if and
14232 // only if any of the destructors for any of its potentially constructed
14233 // subojects is potentially throwing.
14234 // FIXME: We respect the first rule but ignore the "potentially constructed"
14235 // in the second rule to resolve a core issue (no number yet) that would have
14236 // us reject:
14237 // struct A { virtual void f() = 0; virtual ~A() noexcept(false) = 0; };
14238 // struct B : A {};
14239 // struct C : B { void f(); };
14240 // ... due to giving B::~B() a non-throwing exception specification.
14241 Info.visit(Bases: Info.IsConstructor ? Info.VisitPotentiallyConstructedBases
14242 : Info.VisitAllBases);
14243
14244 return Info.ExceptSpec;
14245}
14246
14247namespace {
14248/// RAII object to register a special member as being currently declared.
14249struct DeclaringSpecialMember {
14250 Sema &S;
14251 Sema::SpecialMemberDecl D;
14252 Sema::ContextRAII SavedContext;
14253 bool WasAlreadyBeingDeclared;
14254
14255 DeclaringSpecialMember(Sema &S, CXXRecordDecl *RD, CXXSpecialMemberKind CSM)
14256 : S(S), D(RD, CSM), SavedContext(S, RD) {
14257 WasAlreadyBeingDeclared = !S.SpecialMembersBeingDeclared.insert(Ptr: D).second;
14258 if (WasAlreadyBeingDeclared)
14259 // This almost never happens, but if it does, ensure that our cache
14260 // doesn't contain a stale result.
14261 S.SpecialMemberCache.clear();
14262 else {
14263 // Register a note to be produced if we encounter an error while
14264 // declaring the special member.
14265 Sema::CodeSynthesisContext Ctx;
14266 Ctx.Kind = Sema::CodeSynthesisContext::DeclaringSpecialMember;
14267 // FIXME: We don't have a location to use here. Using the class's
14268 // location maintains the fiction that we declare all special members
14269 // with the class, but (1) it's not clear that lying about that helps our
14270 // users understand what's going on, and (2) there may be outer contexts
14271 // on the stack (some of which are relevant) and printing them exposes
14272 // our lies.
14273 Ctx.PointOfInstantiation = RD->getLocation();
14274 Ctx.Entity = RD;
14275 Ctx.SpecialMember = CSM;
14276 S.pushCodeSynthesisContext(Ctx);
14277 }
14278 }
14279 ~DeclaringSpecialMember() {
14280 if (!WasAlreadyBeingDeclared) {
14281 S.SpecialMembersBeingDeclared.erase(Ptr: D);
14282 S.popCodeSynthesisContext();
14283 }
14284 }
14285
14286 /// Are we already trying to declare this special member?
14287 bool isAlreadyBeingDeclared() const {
14288 return WasAlreadyBeingDeclared;
14289 }
14290};
14291}
14292
14293void Sema::CheckImplicitSpecialMemberDeclaration(Scope *S, FunctionDecl *FD) {
14294 // Look up any existing declarations, but don't trigger declaration of all
14295 // implicit special members with this name.
14296 DeclarationName Name = FD->getDeclName();
14297 LookupResult R(*this, Name, SourceLocation(), LookupOrdinaryName,
14298 RedeclarationKind::ForExternalRedeclaration);
14299 for (auto *D : FD->getParent()->lookup(Name))
14300 if (auto *Acceptable = R.getAcceptableDecl(D))
14301 R.addDecl(D: Acceptable);
14302 R.resolveKind();
14303 R.suppressDiagnostics();
14304
14305 CheckFunctionDeclaration(S, NewFD: FD, Previous&: R, /*IsMemberSpecialization*/ false,
14306 DeclIsDefn: FD->isThisDeclarationADefinition());
14307}
14308
14309void Sema::setupImplicitSpecialMemberType(CXXMethodDecl *SpecialMem,
14310 QualType ResultTy,
14311 ArrayRef<QualType> Args) {
14312 // Build an exception specification pointing back at this constructor.
14313 FunctionProtoType::ExtProtoInfo EPI = getImplicitMethodEPI(S&: *this, MD: SpecialMem);
14314
14315 LangAS AS = getDefaultCXXMethodAddrSpace();
14316 if (AS != LangAS::Default) {
14317 EPI.TypeQuals.addAddressSpace(space: AS);
14318 }
14319
14320 auto QT = Context.getFunctionType(ResultTy, Args, EPI);
14321 SpecialMem->setType(QT);
14322
14323 // During template instantiation of implicit special member functions we need
14324 // a reliable TypeSourceInfo for the function prototype in order to allow
14325 // functions to be substituted.
14326 if (inTemplateInstantiation() && isLambdaMethod(DC: SpecialMem)) {
14327 TypeSourceInfo *TSI =
14328 Context.getTrivialTypeSourceInfo(T: SpecialMem->getType());
14329 SpecialMem->setTypeSourceInfo(TSI);
14330 }
14331}
14332
14333CXXConstructorDecl *Sema::DeclareImplicitDefaultConstructor(
14334 CXXRecordDecl *ClassDecl) {
14335 // C++ [class.ctor]p5:
14336 // A default constructor for a class X is a constructor of class X
14337 // that can be called without an argument. If there is no
14338 // user-declared constructor for class X, a default constructor is
14339 // implicitly declared. An implicitly-declared default constructor
14340 // is an inline public member of its class.
14341 assert(ClassDecl->needsImplicitDefaultConstructor() &&
14342 "Should not build implicit default constructor!");
14343
14344 DeclaringSpecialMember DSM(*this, ClassDecl,
14345 CXXSpecialMemberKind::DefaultConstructor);
14346 if (DSM.isAlreadyBeingDeclared())
14347 return nullptr;
14348
14349 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14350 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, ConstArg: false);
14351
14352 // Create the actual constructor declaration.
14353 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14354 SourceLocation ClassLoc = ClassDecl->getLocation();
14355 DeclarationName Name
14356 = Context.DeclarationNames.getCXXConstructorName(Ty: ClassType);
14357 DeclarationNameInfo NameInfo(Name, ClassLoc);
14358 CXXConstructorDecl *DefaultCon = CXXConstructorDecl::Create(
14359 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, /*Type*/ T: QualType(),
14360 /*TInfo=*/nullptr, ES: ExplicitSpecifier(),
14361 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14362 /*isInline=*/true, /*isImplicitlyDeclared=*/true,
14363 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14364 : ConstexprSpecKind::Unspecified);
14365 DefaultCon->setAccess(AS_public);
14366 DefaultCon->setDefaulted();
14367
14368 setupImplicitSpecialMemberType(SpecialMem: DefaultCon, ResultTy: Context.VoidTy, Args: {});
14369
14370 if (getLangOpts().CUDA)
14371 CUDA().inferTargetForImplicitSpecialMember(
14372 ClassDecl, CSM: CXXSpecialMemberKind::DefaultConstructor, MemberDecl: DefaultCon,
14373 /* ConstRHS */ false,
14374 /* Diagnose */ false);
14375
14376 // We don't need to use SpecialMemberIsTrivial here; triviality for default
14377 // constructors is easy to compute.
14378 DefaultCon->setTrivial(ClassDecl->hasTrivialDefaultConstructor());
14379
14380 // Note that we have declared this constructor.
14381 ++getASTContext().NumImplicitDefaultConstructorsDeclared;
14382
14383 Scope *S = getScopeForContext(Ctx: ClassDecl);
14384 CheckImplicitSpecialMemberDeclaration(S, FD: DefaultCon);
14385
14386 if (ShouldDeleteSpecialMember(MD: DefaultCon,
14387 CSM: CXXSpecialMemberKind::DefaultConstructor))
14388 SetDeclDeleted(dcl: DefaultCon, DelLoc: ClassLoc);
14389
14390 if (S)
14391 PushOnScopeChains(D: DefaultCon, S, AddToContext: false);
14392 ClassDecl->addDecl(D: DefaultCon);
14393
14394 return DefaultCon;
14395}
14396
14397void Sema::DefineImplicitDefaultConstructor(SourceLocation CurrentLocation,
14398 CXXConstructorDecl *Constructor) {
14399 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Constructor);
14400 assert((Constructor->isDefaulted() && Constructor->isDefaultConstructor() &&
14401 !Constructor->doesThisDeclarationHaveABody() &&
14402 !Constructor->isDeleted()) &&
14403 "DefineImplicitDefaultConstructor - call it for implicit default ctor");
14404 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14405 return;
14406
14407 CXXRecordDecl *ClassDecl = Constructor->getParent();
14408 assert(ClassDecl && "DefineImplicitDefaultConstructor - invalid constructor");
14409 if (ClassDecl->isInvalidDecl()) {
14410 return;
14411 }
14412
14413 SynthesizedFunctionScope Scope(*this, Constructor);
14414
14415 // The exception specification is needed because we are defining the
14416 // function.
14417 ResolveExceptionSpec(Loc: CurrentLocation,
14418 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14419 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14420
14421 // Add a context note for diagnostics produced after this point.
14422 Scope.addContextNote(UseLoc: CurrentLocation);
14423
14424 if (SetCtorInitializers(Constructor, /*AnyErrors=*/false)) {
14425 Constructor->setInvalidDecl();
14426 return;
14427 }
14428
14429 SourceLocation Loc = Constructor->getEndLoc().isValid()
14430 ? Constructor->getEndLoc()
14431 : Constructor->getLocation();
14432 Constructor->setBody(new (Context) CompoundStmt(Loc));
14433 Constructor->markUsed(C&: Context);
14434
14435 if (ASTMutationListener *L = getASTMutationListener()) {
14436 L->CompletedImplicitDefinition(D: Constructor);
14437 }
14438
14439 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14440
14441 // The synthesized body applies the class's NSDMIs and never reaches the
14442 // normal IssueWarnings path, so run lifetime safety on it here.
14443 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14444}
14445
14446void Sema::ActOnFinishDelayedMemberInitializers(Decl *D) {
14447 // Perform any delayed checks on exception specifications.
14448 CheckDelayedMemberExceptionSpecs();
14449}
14450
14451/// Find or create the fake constructor we synthesize to model constructing an
14452/// object of a derived class via a constructor of a base class.
14453CXXConstructorDecl *
14454Sema::findInheritingConstructor(SourceLocation Loc,
14455 CXXConstructorDecl *BaseCtor,
14456 ConstructorUsingShadowDecl *Shadow) {
14457 CXXRecordDecl *Derived = Shadow->getParent();
14458 SourceLocation UsingLoc = Shadow->getLocation();
14459
14460 // FIXME: Add a new kind of DeclarationName for an inherited constructor.
14461 // For now we use the name of the base class constructor as a member of the
14462 // derived class to indicate a (fake) inherited constructor name.
14463 DeclarationName Name = BaseCtor->getDeclName();
14464
14465 // Check to see if we already have a fake constructor for this inherited
14466 // constructor call.
14467 for (NamedDecl *Ctor : Derived->lookup(Name))
14468 if (declaresSameEntity(D1: cast<CXXConstructorDecl>(Val: Ctor)
14469 ->getInheritedConstructor()
14470 .getConstructor(),
14471 D2: BaseCtor))
14472 return cast<CXXConstructorDecl>(Val: Ctor);
14473
14474 DeclarationNameInfo NameInfo(Name, UsingLoc);
14475 TypeSourceInfo *TInfo =
14476 Context.getTrivialTypeSourceInfo(T: BaseCtor->getType(), Loc: UsingLoc);
14477 FunctionProtoTypeLoc ProtoLoc =
14478 TInfo->getTypeLoc().IgnoreParens().castAs<FunctionProtoTypeLoc>();
14479
14480 // Check the inherited constructor is valid and find the list of base classes
14481 // from which it was inherited.
14482 InheritedConstructorInfo ICI(*this, Loc, Shadow);
14483
14484 bool Constexpr = BaseCtor->isConstexpr() &&
14485 defaultedSpecialMemberIsConstexpr(
14486 S&: *this, ClassDecl: Derived, CSM: CXXSpecialMemberKind::DefaultConstructor,
14487 ConstArg: false, InheritedCtor: BaseCtor, Inherited: &ICI);
14488
14489 CXXConstructorDecl *DerivedCtor = CXXConstructorDecl::Create(
14490 C&: Context, RD: Derived, StartLoc: UsingLoc, NameInfo, T: TInfo->getType(), TInfo,
14491 ES: BaseCtor->getExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14492 /*isInline=*/true,
14493 /*isImplicitlyDeclared=*/true,
14494 ConstexprKind: Constexpr ? BaseCtor->getConstexprKind() : ConstexprSpecKind::Unspecified,
14495 Inherited: InheritedConstructor(Shadow, BaseCtor),
14496 TrailingRequiresClause: BaseCtor->getTrailingRequiresClause());
14497 if (Shadow->isInvalidDecl())
14498 DerivedCtor->setInvalidDecl();
14499
14500 // Build an unevaluated exception specification for this fake constructor.
14501 const FunctionProtoType *FPT = TInfo->getType()->castAs<FunctionProtoType>();
14502 FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
14503 EPI.ExceptionSpec.Type = EST_Unevaluated;
14504 EPI.ExceptionSpec.SourceDecl = DerivedCtor;
14505 DerivedCtor->setType(Context.getFunctionType(ResultTy: FPT->getReturnType(),
14506 Args: FPT->getParamTypes(), EPI));
14507
14508 // Build the parameter declarations.
14509 SmallVector<ParmVarDecl *, 16> ParamDecls;
14510 for (unsigned I = 0, N = FPT->getNumParams(); I != N; ++I) {
14511 TypeSourceInfo *TInfo =
14512 Context.getTrivialTypeSourceInfo(T: FPT->getParamType(i: I), Loc: UsingLoc);
14513 ParmVarDecl *PD = ParmVarDecl::Create(
14514 C&: Context, DC: DerivedCtor, StartLoc: UsingLoc, IdLoc: UsingLoc, /*IdentifierInfo=*/Id: nullptr,
14515 T: FPT->getParamType(i: I), TInfo, S: SC_None, /*DefArg=*/nullptr);
14516 PD->setScopeInfo(scopeDepth: 0, parameterIndex: I);
14517 PD->setImplicit();
14518 // Ensure attributes are propagated onto parameters (this matters for
14519 // format, pass_object_size, ...).
14520 mergeDeclAttributes(New: PD, Old: BaseCtor->getParamDecl(i: I));
14521 ParamDecls.push_back(Elt: PD);
14522 ProtoLoc.setParam(i: I, VD: PD);
14523 }
14524
14525 // Set up the new constructor.
14526 assert(!BaseCtor->isDeleted() && "should not use deleted constructor");
14527 DerivedCtor->setAccess(BaseCtor->getAccess());
14528 DerivedCtor->setParams(ParamDecls);
14529 Derived->addDecl(D: DerivedCtor);
14530
14531 if (ShouldDeleteSpecialMember(MD: DerivedCtor,
14532 CSM: CXXSpecialMemberKind::DefaultConstructor, ICI: &ICI))
14533 SetDeclDeleted(dcl: DerivedCtor, DelLoc: UsingLoc);
14534
14535 return DerivedCtor;
14536}
14537
14538void Sema::NoteDeletedInheritingConstructor(CXXConstructorDecl *Ctor) {
14539 InheritedConstructorInfo ICI(*this, Ctor->getLocation(),
14540 Ctor->getInheritedConstructor().getShadowDecl());
14541 ShouldDeleteSpecialMember(MD: Ctor, CSM: CXXSpecialMemberKind::DefaultConstructor,
14542 ICI: &ICI,
14543 /*Diagnose*/ true);
14544}
14545
14546void Sema::DefineInheritingConstructor(SourceLocation CurrentLocation,
14547 CXXConstructorDecl *Constructor) {
14548 CXXRecordDecl *ClassDecl = Constructor->getParent();
14549 assert(Constructor->getInheritedConstructor() &&
14550 !Constructor->doesThisDeclarationHaveABody() &&
14551 !Constructor->isDeleted());
14552 if (Constructor->willHaveBody() || Constructor->isInvalidDecl())
14553 return;
14554
14555 // Initializations are performed "as if by a defaulted default constructor",
14556 // so enter the appropriate scope.
14557 SynthesizedFunctionScope Scope(*this, Constructor);
14558
14559 // The exception specification is needed because we are defining the
14560 // function.
14561 ResolveExceptionSpec(Loc: CurrentLocation,
14562 FPT: Constructor->getType()->castAs<FunctionProtoType>());
14563 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14564
14565 // Add a context note for diagnostics produced after this point.
14566 Scope.addContextNote(UseLoc: CurrentLocation);
14567
14568 ConstructorUsingShadowDecl *Shadow =
14569 Constructor->getInheritedConstructor().getShadowDecl();
14570 CXXConstructorDecl *InheritedCtor =
14571 Constructor->getInheritedConstructor().getConstructor();
14572
14573 // [class.inhctor.init]p1:
14574 // initialization proceeds as if a defaulted default constructor is used to
14575 // initialize the D object and each base class subobject from which the
14576 // constructor was inherited
14577
14578 InheritedConstructorInfo ICI(*this, CurrentLocation, Shadow);
14579 CXXRecordDecl *RD = Shadow->getParent();
14580 SourceLocation InitLoc = Shadow->getLocation();
14581
14582 // Build explicit initializers for all base classes from which the
14583 // constructor was inherited.
14584 SmallVector<CXXCtorInitializer*, 8> Inits;
14585 for (bool VBase : {false, true}) {
14586 for (CXXBaseSpecifier &B : VBase ? RD->vbases() : RD->bases()) {
14587 if (B.isVirtual() != VBase)
14588 continue;
14589
14590 auto *BaseRD = B.getType()->getAsCXXRecordDecl();
14591 if (!BaseRD)
14592 continue;
14593
14594 auto BaseCtor = ICI.findConstructorForBase(Base: BaseRD, Ctor: InheritedCtor);
14595 if (!BaseCtor.first)
14596 continue;
14597
14598 MarkFunctionReferenced(Loc: CurrentLocation, Func: BaseCtor.first);
14599 ExprResult Init = new (Context) CXXInheritedCtorInitExpr(
14600 InitLoc, B.getType(), BaseCtor.first, VBase, BaseCtor.second);
14601
14602 auto *TInfo = Context.getTrivialTypeSourceInfo(T: B.getType(), Loc: InitLoc);
14603 Inits.push_back(Elt: new (Context) CXXCtorInitializer(
14604 Context, TInfo, VBase, InitLoc, Init.get(), InitLoc,
14605 SourceLocation()));
14606 }
14607 }
14608
14609 // We now proceed as if for a defaulted default constructor, with the relevant
14610 // initializers replaced.
14611
14612 if (SetCtorInitializers(Constructor, /*AnyErrors*/false, Initializers: Inits)) {
14613 Constructor->setInvalidDecl();
14614 return;
14615 }
14616
14617 Constructor->setBody(new (Context) CompoundStmt(InitLoc));
14618 Constructor->markUsed(C&: Context);
14619
14620 if (ASTMutationListener *L = getASTMutationListener()) {
14621 L->CompletedImplicitDefinition(D: Constructor);
14622 }
14623
14624 DiagnoseUninitializedFields(SemaRef&: *this, Constructor);
14625
14626 // The synthesized body applies the class's NSDMIs and never reaches the
14627 // normal IssueWarnings path, so run lifetime safety on it here.
14628 AnalysisWarnings.IssueWarningsForImplicitFunction(D: Constructor);
14629}
14630
14631CXXDestructorDecl *Sema::DeclareImplicitDestructor(CXXRecordDecl *ClassDecl) {
14632 // C++ [class.dtor]p2:
14633 // If a class has no user-declared destructor, a destructor is
14634 // declared implicitly. An implicitly-declared destructor is an
14635 // inline public member of its class.
14636 assert(ClassDecl->needsImplicitDestructor());
14637
14638 DeclaringSpecialMember DSM(*this, ClassDecl,
14639 CXXSpecialMemberKind::Destructor);
14640 if (DSM.isAlreadyBeingDeclared())
14641 return nullptr;
14642
14643 bool Constexpr = defaultedSpecialMemberIsConstexpr(
14644 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::Destructor, ConstArg: false);
14645
14646 // Create the actual destructor declaration.
14647 CanQualType ClassType = Context.getCanonicalTagType(TD: ClassDecl);
14648 SourceLocation ClassLoc = ClassDecl->getLocation();
14649 DeclarationName Name
14650 = Context.DeclarationNames.getCXXDestructorName(Ty: ClassType);
14651 DeclarationNameInfo NameInfo(Name, ClassLoc);
14652 CXXDestructorDecl *Destructor = CXXDestructorDecl::Create(
14653 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), TInfo: nullptr,
14654 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
14655 /*isInline=*/true,
14656 /*isImplicitlyDeclared=*/true,
14657 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
14658 : ConstexprSpecKind::Unspecified);
14659 Destructor->setAccess(AS_public);
14660 Destructor->setDefaulted();
14661
14662 setupImplicitSpecialMemberType(SpecialMem: Destructor, ResultTy: Context.VoidTy, Args: {});
14663
14664 if (getLangOpts().CUDA)
14665 CUDA().inferTargetForImplicitSpecialMember(
14666 ClassDecl, CSM: CXXSpecialMemberKind::Destructor, MemberDecl: Destructor,
14667 /* ConstRHS */ false,
14668 /* Diagnose */ false);
14669
14670 // We don't need to use SpecialMemberIsTrivial here; triviality for
14671 // destructors is easy to compute.
14672 Destructor->setTrivial(ClassDecl->hasTrivialDestructor());
14673 Destructor->setTrivialForCall(ClassDecl->hasAttr<TrivialABIAttr>() ||
14674 ClassDecl->hasTrivialDestructorForCall());
14675
14676 // Note that we have declared this destructor.
14677 ++getASTContext().NumImplicitDestructorsDeclared;
14678
14679 Scope *S = getScopeForContext(Ctx: ClassDecl);
14680 CheckImplicitSpecialMemberDeclaration(S, FD: Destructor);
14681
14682 // We can't check whether an implicit destructor is deleted before we complete
14683 // the definition of the class, because its validity depends on the alignment
14684 // of the class. We'll check this from ActOnFields once the class is complete.
14685 if (ClassDecl->isCompleteDefinition() &&
14686 ShouldDeleteSpecialMember(MD: Destructor, CSM: CXXSpecialMemberKind::Destructor))
14687 SetDeclDeleted(dcl: Destructor, DelLoc: ClassLoc);
14688
14689 // Introduce this destructor into its scope.
14690 if (S)
14691 PushOnScopeChains(D: Destructor, S, AddToContext: false);
14692 ClassDecl->addDecl(D: Destructor);
14693
14694 return Destructor;
14695}
14696
14697void Sema::DefineImplicitDestructor(SourceLocation CurrentLocation,
14698 CXXDestructorDecl *Destructor) {
14699 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, Destructor);
14700 assert((Destructor->isDefaulted() &&
14701 !Destructor->doesThisDeclarationHaveABody() &&
14702 !Destructor->isDeleted()) &&
14703 "DefineImplicitDestructor - call it for implicit default dtor");
14704 if (Destructor->willHaveBody() || Destructor->isInvalidDecl())
14705 return;
14706
14707 CXXRecordDecl *ClassDecl = Destructor->getParent();
14708 assert(ClassDecl && "DefineImplicitDestructor - invalid destructor");
14709
14710 SynthesizedFunctionScope Scope(*this, Destructor);
14711
14712 // The exception specification is needed because we are defining the
14713 // function.
14714 ResolveExceptionSpec(Loc: CurrentLocation,
14715 FPT: Destructor->getType()->castAs<FunctionProtoType>());
14716 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
14717
14718 // Add a context note for diagnostics produced after this point.
14719 Scope.addContextNote(UseLoc: CurrentLocation);
14720
14721 MarkBaseAndMemberDestructorsReferenced(Location: Destructor->getLocation(),
14722 ClassDecl: Destructor->getParent());
14723
14724 if (CheckDestructor(Destructor)) {
14725 Destructor->setInvalidDecl();
14726 return;
14727 }
14728
14729 SourceLocation Loc = Destructor->getEndLoc().isValid()
14730 ? Destructor->getEndLoc()
14731 : Destructor->getLocation();
14732 Destructor->setBody(new (Context) CompoundStmt(Loc));
14733 Destructor->markUsed(C&: Context);
14734
14735 if (ASTMutationListener *L = getASTMutationListener()) {
14736 L->CompletedImplicitDefinition(D: Destructor);
14737 }
14738}
14739
14740void Sema::CheckCompleteDestructorVariant(SourceLocation CurrentLocation,
14741 CXXDestructorDecl *Destructor) {
14742 if (Destructor->isInvalidDecl())
14743 return;
14744
14745 CXXRecordDecl *ClassDecl = Destructor->getParent();
14746 assert(Context.getTargetInfo().getCXXABI().isMicrosoft() &&
14747 "implicit complete dtors unneeded outside MS ABI");
14748 assert(ClassDecl->getNumVBases() > 0 &&
14749 "complete dtor only exists for classes with vbases");
14750
14751 SynthesizedFunctionScope Scope(*this, Destructor);
14752
14753 // Add a context note for diagnostics produced after this point.
14754 Scope.addContextNote(UseLoc: CurrentLocation);
14755
14756 MarkVirtualBaseDestructorsReferenced(Location: Destructor->getLocation(), ClassDecl);
14757}
14758
14759void Sema::ActOnFinishCXXMemberDecls() {
14760 // If the context is an invalid C++ class, just suppress these checks.
14761 if (CXXRecordDecl *Record = dyn_cast<CXXRecordDecl>(Val: CurContext)) {
14762 if (Record->isInvalidDecl()) {
14763 DelayedOverridingExceptionSpecChecks.clear();
14764 DelayedEquivalentExceptionSpecChecks.clear();
14765 return;
14766 }
14767 checkForMultipleExportedDefaultConstructors(S&: *this, Class: Record);
14768 }
14769}
14770
14771void Sema::ActOnFinishCXXNonNestedClass() {
14772 referenceDLLExportedClassMethods();
14773
14774 if (!DelayedDllExportMemberFunctions.empty()) {
14775 SmallVector<CXXMethodDecl*, 4> WorkList;
14776 std::swap(LHS&: DelayedDllExportMemberFunctions, RHS&: WorkList);
14777 for (CXXMethodDecl *M : WorkList) {
14778 DefineDefaultedFunction(S&: *this, FD: M, DefaultLoc: M->getLocation());
14779
14780 // Pass the method to the consumer to get emitted. This is not necessary
14781 // for explicit instantiation definitions, as they will get emitted
14782 // anyway.
14783 if (M->getParent()->getTemplateSpecializationKind() !=
14784 TSK_ExplicitInstantiationDefinition)
14785 ActOnFinishInlineFunctionDef(D: M);
14786 }
14787 }
14788}
14789
14790void Sema::referenceDLLExportedClassMethods() {
14791 if (!DelayedDllExportClasses.empty()) {
14792 // Calling ReferenceDllExportedMembers might cause the current function to
14793 // be called again, so use a local copy of DelayedDllExportClasses.
14794 SmallVector<CXXRecordDecl *, 4> WorkList;
14795 std::swap(LHS&: DelayedDllExportClasses, RHS&: WorkList);
14796 for (CXXRecordDecl *Class : WorkList)
14797 ReferenceDllExportedMembers(S&: *this, Class);
14798 }
14799}
14800
14801void Sema::AdjustDestructorExceptionSpec(CXXDestructorDecl *Destructor) {
14802 assert(getLangOpts().CPlusPlus11 &&
14803 "adjusting dtor exception specs was introduced in c++11");
14804
14805 if (Destructor->isDependentContext())
14806 return;
14807
14808 // C++11 [class.dtor]p3:
14809 // A declaration of a destructor that does not have an exception-
14810 // specification is implicitly considered to have the same exception-
14811 // specification as an implicit declaration.
14812 const auto *DtorType = Destructor->getType()->castAs<FunctionProtoType>();
14813 if (DtorType->hasExceptionSpec())
14814 return;
14815
14816 // Replace the destructor's type, building off the existing one. Fortunately,
14817 // the only thing of interest in the destructor type is its extended info.
14818 // The return and arguments are fixed.
14819 FunctionProtoType::ExtProtoInfo EPI = DtorType->getExtProtoInfo();
14820 EPI.ExceptionSpec.Type = EST_Unevaluated;
14821 EPI.ExceptionSpec.SourceDecl = Destructor;
14822 Destructor->setType(Context.getFunctionType(ResultTy: Context.VoidTy, Args: {}, EPI));
14823
14824 // FIXME: If the destructor has a body that could throw, and the newly created
14825 // spec doesn't allow exceptions, we should emit a warning, because this
14826 // change in behavior can break conforming C++03 programs at runtime.
14827 // However, we don't have a body or an exception specification yet, so it
14828 // needs to be done somewhere else.
14829}
14830
14831namespace {
14832/// An abstract base class for all helper classes used in building the
14833// copy/move operators. These classes serve as factory functions and help us
14834// avoid using the same Expr* in the AST twice.
14835class ExprBuilder {
14836 ExprBuilder(const ExprBuilder&) = delete;
14837 ExprBuilder &operator=(const ExprBuilder&) = delete;
14838
14839protected:
14840 static Expr *assertNotNull(Expr *E) {
14841 assert(E && "Expression construction must not fail.");
14842 return E;
14843 }
14844
14845public:
14846 ExprBuilder() {}
14847 virtual ~ExprBuilder() {}
14848
14849 virtual Expr *build(Sema &S, SourceLocation Loc) const = 0;
14850};
14851
14852class RefBuilder: public ExprBuilder {
14853 VarDecl *Var;
14854 QualType VarType;
14855
14856public:
14857 Expr *build(Sema &S, SourceLocation Loc) const override {
14858 return assertNotNull(E: S.BuildDeclRefExpr(D: Var, Ty: VarType, VK: VK_LValue, Loc));
14859 }
14860
14861 RefBuilder(VarDecl *Var, QualType VarType)
14862 : Var(Var), VarType(VarType) {}
14863};
14864
14865class ThisBuilder: public ExprBuilder {
14866public:
14867 Expr *build(Sema &S, SourceLocation Loc) const override {
14868 return assertNotNull(E: S.ActOnCXXThis(Loc).getAs<Expr>());
14869 }
14870};
14871
14872class CastBuilder: public ExprBuilder {
14873 const ExprBuilder &Builder;
14874 QualType Type;
14875 ExprValueKind Kind;
14876 const CXXCastPath &Path;
14877
14878public:
14879 Expr *build(Sema &S, SourceLocation Loc) const override {
14880 return assertNotNull(E: S.ImpCastExprToType(E: Builder.build(S, Loc), Type,
14881 CK: CK_UncheckedDerivedToBase, VK: Kind,
14882 BasePath: &Path).get());
14883 }
14884
14885 CastBuilder(const ExprBuilder &Builder, QualType Type, ExprValueKind Kind,
14886 const CXXCastPath &Path)
14887 : Builder(Builder), Type(Type), Kind(Kind), Path(Path) {}
14888};
14889
14890class DerefBuilder: public ExprBuilder {
14891 const ExprBuilder &Builder;
14892
14893public:
14894 Expr *build(Sema &S, SourceLocation Loc) const override {
14895 return assertNotNull(
14896 E: S.CreateBuiltinUnaryOp(OpLoc: Loc, Opc: UO_Deref, InputExpr: Builder.build(S, Loc)).get());
14897 }
14898
14899 DerefBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14900};
14901
14902class MemberBuilder: public ExprBuilder {
14903 const ExprBuilder &Builder;
14904 QualType Type;
14905 CXXScopeSpec SS;
14906 bool IsArrow;
14907 LookupResult &MemberLookup;
14908
14909public:
14910 Expr *build(Sema &S, SourceLocation Loc) const override {
14911 return assertNotNull(E: S.BuildMemberReferenceExpr(
14912 Base: Builder.build(S, Loc), BaseType: Type, OpLoc: Loc, IsArrow, SS, TemplateKWLoc: SourceLocation(),
14913 FirstQualifierInScope: nullptr, R&: MemberLookup, TemplateArgs: nullptr, S: nullptr).get());
14914 }
14915
14916 MemberBuilder(const ExprBuilder &Builder, QualType Type, bool IsArrow,
14917 LookupResult &MemberLookup)
14918 : Builder(Builder), Type(Type), IsArrow(IsArrow),
14919 MemberLookup(MemberLookup) {}
14920};
14921
14922class MoveCastBuilder: public ExprBuilder {
14923 const ExprBuilder &Builder;
14924
14925public:
14926 Expr *build(Sema &S, SourceLocation Loc) const override {
14927 return assertNotNull(E: CastForMoving(SemaRef&: S, E: Builder.build(S, Loc)));
14928 }
14929
14930 MoveCastBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14931};
14932
14933class LvalueConvBuilder: public ExprBuilder {
14934 const ExprBuilder &Builder;
14935
14936public:
14937 Expr *build(Sema &S, SourceLocation Loc) const override {
14938 return assertNotNull(
14939 E: S.DefaultLvalueConversion(E: Builder.build(S, Loc)).get());
14940 }
14941
14942 LvalueConvBuilder(const ExprBuilder &Builder) : Builder(Builder) {}
14943};
14944
14945class SubscriptBuilder: public ExprBuilder {
14946 const ExprBuilder &Base;
14947 const ExprBuilder &Index;
14948
14949public:
14950 Expr *build(Sema &S, SourceLocation Loc) const override {
14951 return assertNotNull(E: S.CreateBuiltinArraySubscriptExpr(
14952 Base: Base.build(S, Loc), LLoc: Loc, Idx: Index.build(S, Loc), RLoc: Loc).get());
14953 }
14954
14955 SubscriptBuilder(const ExprBuilder &Base, const ExprBuilder &Index)
14956 : Base(Base), Index(Index) {}
14957};
14958
14959} // end anonymous namespace
14960
14961/// When generating a defaulted copy or move assignment operator, if a field
14962/// should be copied with __builtin_memcpy rather than via explicit assignments,
14963/// do so. This optimization only applies for arrays of scalars, and for arrays
14964/// of class type where the selected copy/move-assignment operator is trivial.
14965static StmtResult
14966buildMemcpyForAssignmentOp(Sema &S, SourceLocation Loc, QualType T,
14967 const ExprBuilder &ToB, const ExprBuilder &FromB) {
14968 // Compute the size of the memory buffer to be copied.
14969 QualType SizeType = S.Context.getSizeType();
14970 llvm::APInt Size(S.Context.getTypeSize(T: SizeType),
14971 S.Context.getTypeSizeInChars(T).getQuantity());
14972
14973 // Take the address of the field references for "from" and "to". We
14974 // directly construct UnaryOperators here because semantic analysis
14975 // does not permit us to take the address of an xvalue.
14976 Expr *From = FromB.build(S, Loc);
14977 From = UnaryOperator::Create(
14978 C: S.Context, input: From, opc: UO_AddrOf, type: S.Context.getPointerType(T: From->getType()),
14979 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14980 Expr *To = ToB.build(S, Loc);
14981 To = UnaryOperator::Create(
14982 C: S.Context, input: To, opc: UO_AddrOf, type: S.Context.getPointerType(T: To->getType()),
14983 VK: VK_PRValue, OK: OK_Ordinary, l: Loc, CanOverflow: false, FPFeatures: S.CurFPFeatureOverrides());
14984
14985 bool NeedsCollectableMemCpy = false;
14986 if (auto *RD = T->getBaseElementTypeUnsafe()->getAsRecordDecl())
14987 NeedsCollectableMemCpy = RD->hasObjectMember();
14988
14989 // Create a reference to the __builtin_objc_memmove_collectable function
14990 StringRef MemCpyName = NeedsCollectableMemCpy ?
14991 "__builtin_objc_memmove_collectable" :
14992 "__builtin_memcpy";
14993 LookupResult R(S, &S.Context.Idents.get(Name: MemCpyName), Loc,
14994 Sema::LookupOrdinaryName);
14995 S.LookupName(R, S: S.TUScope, AllowBuiltinCreation: true);
14996
14997 FunctionDecl *MemCpy = R.getAsSingle<FunctionDecl>();
14998 if (!MemCpy)
14999 // Something went horribly wrong earlier, and we will have complained
15000 // about it.
15001 return StmtError();
15002
15003 ExprResult MemCpyRef = S.BuildDeclRefExpr(D: MemCpy, Ty: S.Context.BuiltinFnTy,
15004 VK: VK_PRValue, Loc, SS: nullptr);
15005 assert(MemCpyRef.isUsable() && "Builtin reference cannot fail");
15006
15007 Expr *CallArgs[] = {
15008 To, From, IntegerLiteral::Create(C: S.Context, V: Size, type: SizeType, l: Loc)
15009 };
15010 ExprResult Call = S.BuildCallExpr(/*Scope=*/S: nullptr, Fn: MemCpyRef.get(),
15011 LParenLoc: Loc, ArgExprs: CallArgs, RParenLoc: Loc);
15012
15013 assert(!Call.isInvalid() && "Call to __builtin_memcpy cannot fail!");
15014 return Call.getAs<Stmt>();
15015}
15016
15017/// Builds a statement that copies/moves the given entity from \p From to
15018/// \c To.
15019///
15020/// This routine is used to copy/move the members of a class with an
15021/// implicitly-declared copy/move assignment operator. When the entities being
15022/// copied are arrays, this routine builds for loops to copy them.
15023///
15024/// \param S The Sema object used for type-checking.
15025///
15026/// \param Loc The location where the implicit copy/move is being generated.
15027///
15028/// \param T The type of the expressions being copied/moved. Both expressions
15029/// must have this type.
15030///
15031/// \param To The expression we are copying/moving to.
15032///
15033/// \param From The expression we are copying/moving from.
15034///
15035/// \param CopyingBaseSubobject Whether we're copying/moving a base subobject.
15036/// Otherwise, it's a non-static member subobject.
15037///
15038/// \param Copying Whether we're copying or moving.
15039///
15040/// \param Depth Internal parameter recording the depth of the recursion.
15041///
15042/// \returns A statement or a loop that copies the expressions, or StmtResult(0)
15043/// if a memcpy should be used instead.
15044static StmtResult
15045buildSingleCopyAssignRecursively(Sema &S, SourceLocation Loc, QualType T,
15046 const ExprBuilder &To, const ExprBuilder &From,
15047 bool CopyingBaseSubobject, bool Copying,
15048 unsigned Depth = 0) {
15049 // C++11 [class.copy]p28:
15050 // Each subobject is assigned in the manner appropriate to its type:
15051 //
15052 // - if the subobject is of class type, as if by a call to operator= with
15053 // the subobject as the object expression and the corresponding
15054 // subobject of x as a single function argument (as if by explicit
15055 // qualification; that is, ignoring any possible virtual overriding
15056 // functions in more derived classes);
15057 //
15058 // C++03 [class.copy]p13:
15059 // - if the subobject is of class type, the copy assignment operator for
15060 // the class is used (as if by explicit qualification; that is,
15061 // ignoring any possible virtual overriding functions in more derived
15062 // classes);
15063 if (auto *ClassDecl = T->getAsCXXRecordDecl()) {
15064 // Look for operator=.
15065 DeclarationName Name
15066 = S.Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15067 LookupResult OpLookup(S, Name, Loc, Sema::LookupOrdinaryName);
15068 S.LookupQualifiedName(R&: OpLookup, LookupCtx: ClassDecl, InUnqualifiedLookup: false);
15069
15070 // Prior to C++11, filter out any result that isn't a copy/move-assignment
15071 // operator.
15072 if (!S.getLangOpts().CPlusPlus11) {
15073 LookupResult::Filter F = OpLookup.makeFilter();
15074 while (F.hasNext()) {
15075 NamedDecl *D = F.next();
15076 if (CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(Val: D))
15077 if (Method->isCopyAssignmentOperator() ||
15078 (!Copying && Method->isMoveAssignmentOperator()))
15079 continue;
15080
15081 F.erase();
15082 }
15083 F.done();
15084 }
15085
15086 // Suppress the protected check (C++ [class.protected]) for each of the
15087 // assignment operators we found. This strange dance is required when
15088 // we're assigning via a base classes's copy-assignment operator. To
15089 // ensure that we're getting the right base class subobject (without
15090 // ambiguities), we need to cast "this" to that subobject type; to
15091 // ensure that we don't go through the virtual call mechanism, we need
15092 // to qualify the operator= name with the base class (see below). However,
15093 // this means that if the base class has a protected copy assignment
15094 // operator, the protected member access check will fail. So, we
15095 // rewrite "protected" access to "public" access in this case, since we
15096 // know by construction that we're calling from a derived class.
15097 if (CopyingBaseSubobject) {
15098 for (LookupResult::iterator L = OpLookup.begin(), LEnd = OpLookup.end();
15099 L != LEnd; ++L) {
15100 if (L.getAccess() == AS_protected)
15101 L.setAccess(AS_public);
15102 }
15103 }
15104
15105 // Create the nested-name-specifier that will be used to qualify the
15106 // reference to operator=; this is required to suppress the virtual
15107 // call mechanism.
15108 CXXScopeSpec SS;
15109 // FIXME: Don't canonicalize this.
15110 const Type *CanonicalT = S.Context.getCanonicalType(T: T.getTypePtr());
15111 SS.MakeTrivial(Context&: S.Context, Qualifier: NestedNameSpecifier(CanonicalT), R: Loc);
15112
15113 // Create the reference to operator=.
15114 ExprResult OpEqualRef
15115 = S.BuildMemberReferenceExpr(Base: To.build(S, Loc), BaseType: T, OpLoc: Loc, /*IsArrow=*/false,
15116 SS, /*TemplateKWLoc=*/SourceLocation(),
15117 /*FirstQualifierInScope=*/nullptr,
15118 R&: OpLookup,
15119 /*TemplateArgs=*/nullptr, /*S*/nullptr,
15120 /*SuppressQualifierCheck=*/true);
15121 if (OpEqualRef.isInvalid())
15122 return StmtError();
15123
15124 // Build the call to the assignment operator.
15125
15126 Expr *FromInst = From.build(S, Loc);
15127 ExprResult Call = S.BuildCallToMemberFunction(/*Scope=*/S: nullptr,
15128 MemExpr: OpEqualRef.getAs<Expr>(),
15129 LParenLoc: Loc, Args: FromInst, RParenLoc: Loc);
15130 if (Call.isInvalid())
15131 return StmtError();
15132
15133 // If we built a call to a trivial 'operator=' while copying an array,
15134 // bail out. We'll replace the whole shebang with a memcpy.
15135 CXXMemberCallExpr *CE = dyn_cast<CXXMemberCallExpr>(Val: Call.get());
15136 if (CE && CE->getMethodDecl()->isTrivial() && Depth)
15137 return StmtResult((Stmt*)nullptr);
15138
15139 // Convert to an expression-statement, and clean up any produced
15140 // temporaries.
15141 return S.ActOnExprStmt(Arg: Call);
15142 }
15143
15144 // - if the subobject is of scalar type, the built-in assignment
15145 // operator is used.
15146 const ConstantArrayType *ArrayTy = S.Context.getAsConstantArrayType(T);
15147 if (!ArrayTy) {
15148 ExprResult Assignment = S.CreateBuiltinBinOp(
15149 OpLoc: Loc, Opc: BO_Assign, LHSExpr: To.build(S, Loc), RHSExpr: From.build(S, Loc));
15150 if (Assignment.isInvalid())
15151 return StmtError();
15152 return S.ActOnExprStmt(Arg: Assignment);
15153 }
15154
15155 // - if the subobject is an array, each element is assigned, in the
15156 // manner appropriate to the element type;
15157
15158 // Construct a loop over the array bounds, e.g.,
15159 //
15160 // for (__SIZE_TYPE__ i0 = 0; i0 != array-size; ++i0)
15161 //
15162 // that will copy each of the array elements.
15163 QualType SizeType = S.Context.getSizeType();
15164
15165 // Create the iteration variable.
15166 IdentifierInfo *IterationVarName = nullptr;
15167 {
15168 SmallString<8> Str;
15169 llvm::raw_svector_ostream OS(Str);
15170 OS << "__i" << Depth;
15171 IterationVarName = &S.Context.Idents.get(Name: OS.str());
15172 }
15173 VarDecl *IterationVar = VarDecl::Create(C&: S.Context, DC: S.CurContext, StartLoc: Loc, IdLoc: Loc,
15174 Id: IterationVarName, T: SizeType,
15175 TInfo: S.Context.getTrivialTypeSourceInfo(T: SizeType, Loc),
15176 S: SC_None);
15177
15178 // Initialize the iteration variable to zero.
15179 llvm::APInt Zero(S.Context.getTypeSize(T: SizeType), 0);
15180 IterationVar->setInit(IntegerLiteral::Create(C: S.Context, V: Zero, type: SizeType, l: Loc));
15181
15182 // Creates a reference to the iteration variable.
15183 RefBuilder IterationVarRef(IterationVar, SizeType);
15184 LvalueConvBuilder IterationVarRefRVal(IterationVarRef);
15185
15186 // Create the DeclStmt that holds the iteration variable.
15187 Stmt *InitStmt = new (S.Context) DeclStmt(DeclGroupRef(IterationVar),Loc,Loc);
15188
15189 // Subscript the "from" and "to" expressions with the iteration variable.
15190 SubscriptBuilder FromIndexCopy(From, IterationVarRefRVal);
15191 MoveCastBuilder FromIndexMove(FromIndexCopy);
15192 const ExprBuilder *FromIndex;
15193 if (Copying)
15194 FromIndex = &FromIndexCopy;
15195 else
15196 FromIndex = &FromIndexMove;
15197
15198 SubscriptBuilder ToIndex(To, IterationVarRefRVal);
15199
15200 // Build the copy/move for an individual element of the array.
15201 StmtResult Copy =
15202 buildSingleCopyAssignRecursively(S, Loc, T: ArrayTy->getElementType(),
15203 To: ToIndex, From: *FromIndex, CopyingBaseSubobject,
15204 Copying, Depth: Depth + 1);
15205 // Bail out if copying fails or if we determined that we should use memcpy.
15206 if (Copy.isInvalid() || !Copy.get())
15207 return Copy;
15208
15209 // Create the comparison against the array bound.
15210 llvm::APInt Upper
15211 = ArrayTy->getSize().zextOrTrunc(width: S.Context.getTypeSize(T: SizeType));
15212 Expr *Comparison = BinaryOperator::Create(
15213 C: S.Context, lhs: IterationVarRefRVal.build(S, Loc),
15214 rhs: IntegerLiteral::Create(C: S.Context, V: Upper, type: SizeType, l: Loc), opc: BO_NE,
15215 ResTy: S.Context.BoolTy, VK: VK_PRValue, OK: OK_Ordinary, opLoc: Loc,
15216 FPFeatures: S.CurFPFeatureOverrides());
15217
15218 // Create the pre-increment of the iteration variable. We can determine
15219 // whether the increment will overflow based on the value of the array
15220 // bound.
15221 Expr *Increment = UnaryOperator::Create(
15222 C: S.Context, input: IterationVarRef.build(S, Loc), opc: UO_PreInc, type: SizeType, VK: VK_LValue,
15223 OK: OK_Ordinary, l: Loc, CanOverflow: Upper.isMaxValue(), FPFeatures: S.CurFPFeatureOverrides());
15224
15225 // Construct the loop that copies all elements of this array.
15226 return S.ActOnForStmt(
15227 ForLoc: Loc, LParenLoc: Loc, First: InitStmt,
15228 Second: S.ActOnCondition(S: nullptr, Loc, SubExpr: Comparison, CK: Sema::ConditionKind::Boolean),
15229 Third: S.MakeFullDiscardedValueExpr(Arg: Increment), RParenLoc: Loc, Body: Copy.get());
15230}
15231
15232static StmtResult
15233buildSingleCopyAssign(Sema &S, SourceLocation Loc, QualType T,
15234 const ExprBuilder &To, const ExprBuilder &From,
15235 bool CopyingBaseSubobject, bool Copying) {
15236 // Maybe we should use a memcpy?
15237 if (T->isArrayType() && !T.hasQualifiers() &&
15238 T.isTriviallyCopyableType(Context: S.Context))
15239 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15240
15241 StmtResult Result(buildSingleCopyAssignRecursively(S, Loc, T, To, From,
15242 CopyingBaseSubobject,
15243 Copying, Depth: 0));
15244
15245 // If we ended up picking a trivial assignment operator for an array of a
15246 // non-trivially-copyable class type, just emit a memcpy.
15247 if (!Result.isInvalid() && !Result.get())
15248 return buildMemcpyForAssignmentOp(S, Loc, T, ToB: To, FromB: From);
15249
15250 return Result;
15251}
15252
15253CXXMethodDecl *Sema::DeclareImplicitCopyAssignment(CXXRecordDecl *ClassDecl) {
15254 // Note: The following rules are largely analoguous to the copy
15255 // constructor rules. Note that virtual bases are not taken into account
15256 // for determining the argument type of the operator. Note also that
15257 // operators taking an object instead of a reference are allowed.
15258 assert(ClassDecl->needsImplicitCopyAssignment());
15259
15260 DeclaringSpecialMember DSM(*this, ClassDecl,
15261 CXXSpecialMemberKind::CopyAssignment);
15262 if (DSM.isAlreadyBeingDeclared())
15263 return nullptr;
15264
15265 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15266 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15267 /*OwnsTag=*/false);
15268 LangAS AS = getDefaultCXXMethodAddrSpace();
15269 if (AS != LangAS::Default)
15270 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15271 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15272 bool Const = ClassDecl->implicitCopyAssignmentHasConstParam();
15273 if (Const)
15274 ArgType = ArgType.withConst();
15275
15276 ArgType = Context.getLValueReferenceType(T: ArgType);
15277
15278 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15279 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, ConstArg: Const);
15280
15281 // An implicitly-declared copy assignment operator is an inline public
15282 // member of its class.
15283 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15284 SourceLocation ClassLoc = ClassDecl->getLocation();
15285 DeclarationNameInfo NameInfo(Name, ClassLoc);
15286 CXXMethodDecl *CopyAssignment = CXXMethodDecl::Create(
15287 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15288 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15289 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15290 /*isInline=*/true,
15291 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15292 EndLocation: SourceLocation());
15293 CopyAssignment->setAccess(AS_public);
15294 CopyAssignment->setDefaulted();
15295 CopyAssignment->setImplicit();
15296
15297 setupImplicitSpecialMemberType(SpecialMem: CopyAssignment, ResultTy: RetType, Args: ArgType);
15298
15299 if (getLangOpts().CUDA)
15300 CUDA().inferTargetForImplicitSpecialMember(
15301 ClassDecl, CSM: CXXSpecialMemberKind::CopyAssignment, MemberDecl: CopyAssignment,
15302 /* ConstRHS */ Const,
15303 /* Diagnose */ false);
15304
15305 // Add the parameter to the operator.
15306 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: CopyAssignment,
15307 StartLoc: ClassLoc, IdLoc: ClassLoc,
15308 /*Id=*/nullptr, T: ArgType,
15309 /*TInfo=*/nullptr, S: SC_None,
15310 DefArg: nullptr);
15311 CopyAssignment->setParams(FromParam);
15312
15313 CopyAssignment->setTrivial(
15314 ClassDecl->needsOverloadResolutionForCopyAssignment()
15315 ? SpecialMemberIsTrivial(MD: CopyAssignment,
15316 CSM: CXXSpecialMemberKind::CopyAssignment)
15317 : ClassDecl->hasTrivialCopyAssignment());
15318
15319 // Note that we have added this copy-assignment operator.
15320 ++getASTContext().NumImplicitCopyAssignmentOperatorsDeclared;
15321
15322 Scope *S = getScopeForContext(Ctx: ClassDecl);
15323 CheckImplicitSpecialMemberDeclaration(S, FD: CopyAssignment);
15324
15325 if (ShouldDeleteSpecialMember(MD: CopyAssignment,
15326 CSM: CXXSpecialMemberKind::CopyAssignment)) {
15327 ClassDecl->setImplicitCopyAssignmentIsDeleted();
15328 SetDeclDeleted(dcl: CopyAssignment, DelLoc: ClassLoc);
15329 }
15330
15331 if (S)
15332 PushOnScopeChains(D: CopyAssignment, S, AddToContext: false);
15333 ClassDecl->addDecl(D: CopyAssignment);
15334
15335 return CopyAssignment;
15336}
15337
15338/// Diagnose an implicit copy operation for a class which is odr-used, but
15339/// which is deprecated because the class has a user-declared copy constructor,
15340/// copy assignment operator, or destructor.
15341static void diagnoseDeprecatedCopyOperation(Sema &S, CXXMethodDecl *CopyOp) {
15342 assert(CopyOp->isImplicit());
15343
15344 CXXRecordDecl *RD = CopyOp->getParent();
15345 CXXMethodDecl *UserDeclaredOperation = nullptr;
15346
15347 if (RD->hasUserDeclaredDestructor()) {
15348 UserDeclaredOperation = RD->getDestructor();
15349 } else if (!isa<CXXConstructorDecl>(Val: CopyOp) &&
15350 RD->hasUserDeclaredCopyConstructor()) {
15351 // Find any user-declared copy constructor.
15352 for (auto *I : RD->ctors()) {
15353 if (I->isCopyConstructor()) {
15354 UserDeclaredOperation = I;
15355 break;
15356 }
15357 }
15358 assert(UserDeclaredOperation);
15359 } else if (isa<CXXConstructorDecl>(Val: CopyOp) &&
15360 RD->hasUserDeclaredCopyAssignment()) {
15361 // Find any user-declared move assignment operator.
15362 for (auto *I : RD->methods()) {
15363 if (I->isCopyAssignmentOperator()) {
15364 UserDeclaredOperation = I;
15365 break;
15366 }
15367 }
15368 assert(UserDeclaredOperation);
15369 }
15370
15371 if (UserDeclaredOperation) {
15372 bool UDOIsUserProvided = UserDeclaredOperation->isUserProvided();
15373 bool UDOIsDestructor = isa<CXXDestructorDecl>(Val: UserDeclaredOperation);
15374 bool IsCopyAssignment = !isa<CXXConstructorDecl>(Val: CopyOp);
15375 unsigned DiagID =
15376 (UDOIsUserProvided && UDOIsDestructor)
15377 ? diag::warn_deprecated_copy_with_user_provided_dtor
15378 : (UDOIsUserProvided && !UDOIsDestructor)
15379 ? diag::warn_deprecated_copy_with_user_provided_copy
15380 : (!UDOIsUserProvided && UDOIsDestructor)
15381 ? diag::warn_deprecated_copy_with_dtor
15382 : diag::warn_deprecated_copy;
15383 S.Diag(Loc: UserDeclaredOperation->getLocation(), DiagID)
15384 << RD << IsCopyAssignment;
15385 }
15386}
15387
15388void Sema::DefineImplicitCopyAssignment(SourceLocation CurrentLocation,
15389 CXXMethodDecl *CopyAssignOperator) {
15390 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyAssignOperator);
15391 assert((CopyAssignOperator->isDefaulted() &&
15392 CopyAssignOperator->isOverloadedOperator() &&
15393 CopyAssignOperator->getOverloadedOperator() == OO_Equal &&
15394 !CopyAssignOperator->doesThisDeclarationHaveABody() &&
15395 !CopyAssignOperator->isDeleted()) &&
15396 "DefineImplicitCopyAssignment called for wrong function");
15397 if (CopyAssignOperator->willHaveBody() || CopyAssignOperator->isInvalidDecl())
15398 return;
15399
15400 CXXRecordDecl *ClassDecl = CopyAssignOperator->getParent();
15401 if (ClassDecl->isInvalidDecl()) {
15402 CopyAssignOperator->setInvalidDecl();
15403 return;
15404 }
15405
15406 SynthesizedFunctionScope Scope(*this, CopyAssignOperator);
15407
15408 // The exception specification is needed because we are defining the
15409 // function.
15410 ResolveExceptionSpec(Loc: CurrentLocation,
15411 FPT: CopyAssignOperator->getType()->castAs<FunctionProtoType>());
15412
15413 // Add a context note for diagnostics produced after this point.
15414 Scope.addContextNote(UseLoc: CurrentLocation);
15415
15416 // C++11 [class.copy]p18:
15417 // The [definition of an implicitly declared copy assignment operator] is
15418 // deprecated if the class has a user-declared copy constructor or a
15419 // user-declared destructor.
15420 if (getLangOpts().CPlusPlus11 && CopyAssignOperator->isImplicit())
15421 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyAssignOperator);
15422
15423 // C++0x [class.copy]p30:
15424 // The implicitly-defined or explicitly-defaulted copy assignment operator
15425 // for a non-union class X performs memberwise copy assignment of its
15426 // subobjects. The direct base classes of X are assigned first, in the
15427 // order of their declaration in the base-specifier-list, and then the
15428 // immediate non-static data members of X are assigned, in the order in
15429 // which they were declared in the class definition.
15430
15431 // The statements that form the synthesized function body.
15432 SmallVector<Stmt*, 8> Statements;
15433
15434 // The parameter for the "other" object, which we are copying from.
15435 ParmVarDecl *Other = CopyAssignOperator->getNonObjectParameter(I: 0);
15436 Qualifiers OtherQuals = Other->getType().getQualifiers();
15437 QualType OtherRefType = Other->getType();
15438 if (OtherRefType->isLValueReferenceType()) {
15439 OtherRefType = OtherRefType->getPointeeType();
15440 OtherQuals = OtherRefType.getQualifiers();
15441 }
15442
15443 // Our location for everything implicitly-generated.
15444 SourceLocation Loc = CopyAssignOperator->getEndLoc().isValid()
15445 ? CopyAssignOperator->getEndLoc()
15446 : CopyAssignOperator->getLocation();
15447
15448 // Builds a DeclRefExpr for the "other" object.
15449 RefBuilder OtherRef(Other, OtherRefType);
15450
15451 // Builds the function object parameter.
15452 std::optional<ThisBuilder> This;
15453 std::optional<DerefBuilder> DerefThis;
15454 std::optional<RefBuilder> ExplicitObject;
15455 bool IsArrow = false;
15456 QualType ObjectType;
15457 if (CopyAssignOperator->isExplicitObjectMemberFunction()) {
15458 ObjectType = CopyAssignOperator->getParamDecl(i: 0)->getType();
15459 if (ObjectType->isReferenceType())
15460 ObjectType = ObjectType->getPointeeType();
15461 ExplicitObject.emplace(args: CopyAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15462 } else {
15463 ObjectType = getCurrentThisType();
15464 This.emplace();
15465 DerefThis.emplace(args&: *This);
15466 IsArrow = !LangOpts.HLSL;
15467 }
15468 ExprBuilder &ObjectParameter =
15469 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15470 : static_cast<ExprBuilder &>(*This);
15471
15472 // Assign base classes.
15473 bool Invalid = false;
15474 for (auto &Base : ClassDecl->bases()) {
15475 // Form the assignment:
15476 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&>(other));
15477 QualType BaseType = Base.getType().getUnqualifiedType();
15478 if (!BaseType->isRecordType()) {
15479 Invalid = true;
15480 continue;
15481 }
15482
15483 CXXCastPath BasePath;
15484 BasePath.push_back(Elt: &Base);
15485
15486 // Construct the "from" expression, which is an implicit cast to the
15487 // appropriately-qualified base type.
15488 CastBuilder From(OtherRef, Context.getQualifiedType(T: BaseType, Qs: OtherQuals),
15489 VK_LValue, BasePath);
15490
15491 // Dereference "this".
15492 CastBuilder To(
15493 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15494 : static_cast<ExprBuilder &>(*DerefThis),
15495 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15496 VK_LValue, BasePath);
15497
15498 // Build the copy.
15499 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15500 To, From,
15501 /*CopyingBaseSubobject=*/true,
15502 /*Copying=*/true);
15503 if (Copy.isInvalid()) {
15504 CopyAssignOperator->setInvalidDecl();
15505 return;
15506 }
15507
15508 // Success! Record the copy.
15509 Statements.push_back(Elt: Copy.getAs<Expr>());
15510 }
15511
15512 // A defaulted copy assignment operator for a union copies the object
15513 // representation as if by a memcpy, the same way the defaulted union copy
15514 // constructor does. The memberwise loop below skips union members.
15515 if (ClassDecl->isUnion()) {
15516 ExprBuilder &To = ExplicitObject
15517 ? static_cast<ExprBuilder &>(*ExplicitObject)
15518 : static_cast<ExprBuilder &>(*DerefThis);
15519 // Copying the object representation is correct even for a union that is
15520 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15521 // here. Ignoring warnings rather than casting the arguments to void*
15522 // keeps them typed, which preserves their address space.
15523 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15524 StmtResult Copy = buildMemcpyForAssignmentOp(
15525 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
15526 if (Copy.isInvalid()) {
15527 CopyAssignOperator->setInvalidDecl();
15528 return;
15529 }
15530 Statements.push_back(Elt: Copy.getAs<Stmt>());
15531 }
15532
15533 // Assign non-static members.
15534 for (auto *Field : ClassDecl->fields()) {
15535 // Union members are copied by the whole-object memcpy emitted above.
15536 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15537 continue;
15538
15539 if (Field->isInvalidDecl()) {
15540 Invalid = true;
15541 continue;
15542 }
15543
15544 // Check for members of reference type; we can't copy those.
15545 if (Field->getType()->isReferenceType()) {
15546 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15547 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15548 << Field->getDeclName();
15549 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15550 Invalid = true;
15551 continue;
15552 }
15553
15554 // Check for members of const-qualified, non-class type.
15555 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15556 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15557 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15558 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15559 << Field->getDeclName();
15560 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15561 Invalid = true;
15562 continue;
15563 }
15564
15565 // Suppress assigning zero-width bitfields.
15566 if (Field->isZeroLengthBitField())
15567 continue;
15568
15569 QualType FieldType = Field->getType().getNonReferenceType();
15570 if (FieldType->isIncompleteArrayType()) {
15571 assert(ClassDecl->hasFlexibleArrayMember() &&
15572 "Incomplete array type is not valid");
15573 continue;
15574 }
15575
15576 // Build references to the field in the object we're copying from and to.
15577 CXXScopeSpec SS; // Intentionally empty
15578 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15579 LookupMemberName);
15580 MemberLookup.addDecl(D: Field);
15581 MemberLookup.resolveKind();
15582
15583 MemberBuilder From(OtherRef, OtherRefType, /*IsArrow=*/false, MemberLookup);
15584 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15585 // Build the copy of this field.
15586 StmtResult Copy = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
15587 To, From,
15588 /*CopyingBaseSubobject=*/false,
15589 /*Copying=*/true);
15590 if (Copy.isInvalid()) {
15591 CopyAssignOperator->setInvalidDecl();
15592 return;
15593 }
15594
15595 // Success! Record the copy.
15596 Statements.push_back(Elt: Copy.getAs<Stmt>());
15597 }
15598
15599 if (!Invalid) {
15600 // Add a "return *this;"
15601 Expr *ThisExpr =
15602 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15603 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
15604 : static_cast<ExprBuilder &>(*DerefThis))
15605 .build(S&: *this, Loc);
15606 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
15607 if (Return.isInvalid())
15608 Invalid = true;
15609 else
15610 Statements.push_back(Elt: Return.getAs<Stmt>());
15611 }
15612
15613 if (Invalid) {
15614 CopyAssignOperator->setInvalidDecl();
15615 return;
15616 }
15617
15618 StmtResult Body;
15619 {
15620 CompoundScopeRAII CompoundScope(*this);
15621 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
15622 /*isStmtExpr=*/false);
15623 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
15624 }
15625 CopyAssignOperator->setBody(Body.getAs<Stmt>());
15626 CopyAssignOperator->markUsed(C&: Context);
15627
15628 if (ASTMutationListener *L = getASTMutationListener()) {
15629 L->CompletedImplicitDefinition(D: CopyAssignOperator);
15630 }
15631}
15632
15633CXXMethodDecl *Sema::DeclareImplicitMoveAssignment(CXXRecordDecl *ClassDecl) {
15634 assert(ClassDecl->needsImplicitMoveAssignment());
15635
15636 DeclaringSpecialMember DSM(*this, ClassDecl,
15637 CXXSpecialMemberKind::MoveAssignment);
15638 if (DSM.isAlreadyBeingDeclared())
15639 return nullptr;
15640
15641 // Note: The following rules are largely analoguous to the move
15642 // constructor rules.
15643
15644 QualType ArgType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
15645 /*Qualifier=*/std::nullopt, TD: ClassDecl,
15646 /*OwnsTag=*/false);
15647 LangAS AS = getDefaultCXXMethodAddrSpace();
15648 if (AS != LangAS::Default)
15649 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
15650 QualType RetType = Context.getLValueReferenceType(T: ArgType);
15651 ArgType = Context.getRValueReferenceType(T: ArgType);
15652
15653 bool Constexpr = defaultedSpecialMemberIsConstexpr(
15654 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, ConstArg: false);
15655
15656 // An implicitly-declared move assignment operator is an inline public
15657 // member of its class.
15658 DeclarationName Name = Context.DeclarationNames.getCXXOperatorName(Op: OO_Equal);
15659 SourceLocation ClassLoc = ClassDecl->getLocation();
15660 DeclarationNameInfo NameInfo(Name, ClassLoc);
15661 CXXMethodDecl *MoveAssignment = CXXMethodDecl::Create(
15662 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(),
15663 /*TInfo=*/nullptr, /*StorageClass=*/SC: SC_None,
15664 UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
15665 /*isInline=*/true,
15666 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr : ConstexprSpecKind::Unspecified,
15667 EndLocation: SourceLocation());
15668 MoveAssignment->setAccess(AS_public);
15669 MoveAssignment->setDefaulted();
15670 MoveAssignment->setImplicit();
15671
15672 setupImplicitSpecialMemberType(SpecialMem: MoveAssignment, ResultTy: RetType, Args: ArgType);
15673
15674 if (getLangOpts().CUDA)
15675 CUDA().inferTargetForImplicitSpecialMember(
15676 ClassDecl, CSM: CXXSpecialMemberKind::MoveAssignment, MemberDecl: MoveAssignment,
15677 /* ConstRHS */ false,
15678 /* Diagnose */ false);
15679
15680 // Add the parameter to the operator.
15681 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveAssignment,
15682 StartLoc: ClassLoc, IdLoc: ClassLoc,
15683 /*Id=*/nullptr, T: ArgType,
15684 /*TInfo=*/nullptr, S: SC_None,
15685 DefArg: nullptr);
15686 MoveAssignment->setParams(FromParam);
15687
15688 MoveAssignment->setTrivial(
15689 ClassDecl->needsOverloadResolutionForMoveAssignment()
15690 ? SpecialMemberIsTrivial(MD: MoveAssignment,
15691 CSM: CXXSpecialMemberKind::MoveAssignment)
15692 : ClassDecl->hasTrivialMoveAssignment());
15693
15694 // Note that we have added this copy-assignment operator.
15695 ++getASTContext().NumImplicitMoveAssignmentOperatorsDeclared;
15696
15697 Scope *S = getScopeForContext(Ctx: ClassDecl);
15698 CheckImplicitSpecialMemberDeclaration(S, FD: MoveAssignment);
15699
15700 if (ShouldDeleteSpecialMember(MD: MoveAssignment,
15701 CSM: CXXSpecialMemberKind::MoveAssignment)) {
15702 ClassDecl->setImplicitMoveAssignmentIsDeleted();
15703 SetDeclDeleted(dcl: MoveAssignment, DelLoc: ClassLoc);
15704 }
15705
15706 if (S)
15707 PushOnScopeChains(D: MoveAssignment, S, AddToContext: false);
15708 ClassDecl->addDecl(D: MoveAssignment);
15709
15710 return MoveAssignment;
15711}
15712
15713/// Check if we're implicitly defining a move assignment operator for a class
15714/// with virtual bases. Such a move assignment might move-assign the virtual
15715/// base multiple times.
15716static void checkMoveAssignmentForRepeatedMove(Sema &S, CXXRecordDecl *Class,
15717 SourceLocation CurrentLocation) {
15718 assert(!Class->isDependentContext() && "should not define dependent move");
15719
15720 // Only a virtual base could get implicitly move-assigned multiple times.
15721 // Only a non-trivial move assignment can observe this. We only want to
15722 // diagnose if we implicitly define an assignment operator that assigns
15723 // two base classes, both of which move-assign the same virtual base.
15724 if (Class->getNumVBases() == 0 || Class->hasTrivialMoveAssignment() ||
15725 Class->getNumBases() < 2)
15726 return;
15727
15728 llvm::SmallVector<CXXBaseSpecifier *, 16> Worklist;
15729 typedef llvm::DenseMap<CXXRecordDecl*, CXXBaseSpecifier*> VBaseMap;
15730 VBaseMap VBases;
15731
15732 for (auto &BI : Class->bases()) {
15733 Worklist.push_back(Elt: &BI);
15734 while (!Worklist.empty()) {
15735 CXXBaseSpecifier *BaseSpec = Worklist.pop_back_val();
15736 CXXRecordDecl *Base = BaseSpec->getType()->getAsCXXRecordDecl();
15737
15738 // If the base has no non-trivial move assignment operators,
15739 // we don't care about moves from it.
15740 if (!Base->hasNonTrivialMoveAssignment())
15741 continue;
15742
15743 // If there's nothing virtual here, skip it.
15744 if (!BaseSpec->isVirtual() && !Base->getNumVBases())
15745 continue;
15746
15747 // If we're not actually going to call a move assignment for this base,
15748 // or the selected move assignment is trivial, skip it.
15749 Sema::SpecialMemberOverloadResult SMOR =
15750 S.LookupSpecialMember(D: Base, SM: CXXSpecialMemberKind::MoveAssignment,
15751 /*ConstArg*/ false, /*VolatileArg*/ false,
15752 /*RValueThis*/ true, /*ConstThis*/ false,
15753 /*VolatileThis*/ false);
15754 if (!SMOR.getMethod() || SMOR.getMethod()->isTrivial() ||
15755 !SMOR.getMethod()->isMoveAssignmentOperator())
15756 continue;
15757
15758 if (BaseSpec->isVirtual()) {
15759 // We're going to move-assign this virtual base, and its move
15760 // assignment operator is not trivial. If this can happen for
15761 // multiple distinct direct bases of Class, diagnose it. (If it
15762 // only happens in one base, we'll diagnose it when synthesizing
15763 // that base class's move assignment operator.)
15764 CXXBaseSpecifier *&Existing =
15765 VBases.insert(KV: std::make_pair(x: Base->getCanonicalDecl(), y: &BI))
15766 .first->second;
15767 if (Existing && Existing != &BI) {
15768 S.Diag(Loc: CurrentLocation, DiagID: diag::warn_vbase_moved_multiple_times)
15769 << Class << Base;
15770 S.Diag(Loc: Existing->getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15771 << (Base->getCanonicalDecl() ==
15772 Existing->getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15773 << Base << Existing->getType() << Existing->getSourceRange();
15774 S.Diag(Loc: BI.getBeginLoc(), DiagID: diag::note_vbase_moved_here)
15775 << (Base->getCanonicalDecl() ==
15776 BI.getType()->getAsCXXRecordDecl()->getCanonicalDecl())
15777 << Base << BI.getType() << BaseSpec->getSourceRange();
15778
15779 // Only diagnose each vbase once.
15780 Existing = nullptr;
15781 }
15782 } else {
15783 // Only walk over bases that have defaulted move assignment operators.
15784 // We assume that any user-provided move assignment operator handles
15785 // the multiple-moves-of-vbase case itself somehow.
15786 if (!SMOR.getMethod()->isDefaulted())
15787 continue;
15788
15789 // We're going to move the base classes of Base. Add them to the list.
15790 llvm::append_range(C&: Worklist, R: llvm::make_pointer_range(Range: Base->bases()));
15791 }
15792 }
15793 }
15794}
15795
15796void Sema::DefineImplicitMoveAssignment(SourceLocation CurrentLocation,
15797 CXXMethodDecl *MoveAssignOperator) {
15798 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveAssignOperator);
15799 assert((MoveAssignOperator->isDefaulted() &&
15800 MoveAssignOperator->isOverloadedOperator() &&
15801 MoveAssignOperator->getOverloadedOperator() == OO_Equal &&
15802 !MoveAssignOperator->doesThisDeclarationHaveABody() &&
15803 !MoveAssignOperator->isDeleted()) &&
15804 "DefineImplicitMoveAssignment called for wrong function");
15805 if (MoveAssignOperator->willHaveBody() || MoveAssignOperator->isInvalidDecl())
15806 return;
15807
15808 CXXRecordDecl *ClassDecl = MoveAssignOperator->getParent();
15809 if (ClassDecl->isInvalidDecl()) {
15810 MoveAssignOperator->setInvalidDecl();
15811 return;
15812 }
15813
15814 // C++0x [class.copy]p28:
15815 // The implicitly-defined or move assignment operator for a non-union class
15816 // X performs memberwise move assignment of its subobjects. The direct base
15817 // classes of X are assigned first, in the order of their declaration in the
15818 // base-specifier-list, and then the immediate non-static data members of X
15819 // are assigned, in the order in which they were declared in the class
15820 // definition.
15821
15822 // Issue a warning if our implicit move assignment operator will move
15823 // from a virtual base more than once.
15824 checkMoveAssignmentForRepeatedMove(S&: *this, Class: ClassDecl, CurrentLocation);
15825
15826 SynthesizedFunctionScope Scope(*this, MoveAssignOperator);
15827
15828 // The exception specification is needed because we are defining the
15829 // function.
15830 ResolveExceptionSpec(Loc: CurrentLocation,
15831 FPT: MoveAssignOperator->getType()->castAs<FunctionProtoType>());
15832
15833 // Add a context note for diagnostics produced after this point.
15834 Scope.addContextNote(UseLoc: CurrentLocation);
15835
15836 // The statements that form the synthesized function body.
15837 SmallVector<Stmt*, 8> Statements;
15838
15839 // The parameter for the "other" object, which we are move from.
15840 ParmVarDecl *Other = MoveAssignOperator->getNonObjectParameter(I: 0);
15841 QualType OtherRefType =
15842 Other->getType()->castAs<RValueReferenceType>()->getPointeeType();
15843
15844 // Our location for everything implicitly-generated.
15845 SourceLocation Loc = MoveAssignOperator->getEndLoc().isValid()
15846 ? MoveAssignOperator->getEndLoc()
15847 : MoveAssignOperator->getLocation();
15848
15849 // Builds a reference to the "other" object.
15850 RefBuilder OtherRef(Other, OtherRefType);
15851 // Cast to rvalue.
15852 MoveCastBuilder MoveOther(OtherRef);
15853
15854 // Builds the function object parameter.
15855 std::optional<ThisBuilder> This;
15856 std::optional<DerefBuilder> DerefThis;
15857 std::optional<RefBuilder> ExplicitObject;
15858 QualType ObjectType;
15859 bool IsArrow = false;
15860 if (MoveAssignOperator->isExplicitObjectMemberFunction()) {
15861 ObjectType = MoveAssignOperator->getParamDecl(i: 0)->getType();
15862 if (ObjectType->isReferenceType())
15863 ObjectType = ObjectType->getPointeeType();
15864 ExplicitObject.emplace(args: MoveAssignOperator->getParamDecl(i: 0), args&: ObjectType);
15865 } else {
15866 ObjectType = getCurrentThisType();
15867 This.emplace();
15868 DerefThis.emplace(args&: *This);
15869 IsArrow = !getLangOpts().HLSL;
15870 }
15871 ExprBuilder &ObjectParameter =
15872 ExplicitObject ? *ExplicitObject : static_cast<ExprBuilder &>(*This);
15873
15874 // Assign base classes.
15875 bool Invalid = false;
15876 for (auto &Base : ClassDecl->bases()) {
15877 // C++11 [class.copy]p28:
15878 // It is unspecified whether subobjects representing virtual base classes
15879 // are assigned more than once by the implicitly-defined copy assignment
15880 // operator.
15881 // FIXME: Do not assign to a vbase that will be assigned by some other base
15882 // class. For a move-assignment, this can result in the vbase being moved
15883 // multiple times.
15884
15885 // Form the assignment:
15886 // static_cast<Base*>(this)->Base::operator=(static_cast<Base&&>(other));
15887 QualType BaseType = Base.getType().getUnqualifiedType();
15888 if (!BaseType->isRecordType()) {
15889 Invalid = true;
15890 continue;
15891 }
15892
15893 CXXCastPath BasePath;
15894 BasePath.push_back(Elt: &Base);
15895
15896 // Construct the "from" expression, which is an implicit cast to the
15897 // appropriately-qualified base type.
15898 CastBuilder From(OtherRef, BaseType, VK_XValue, BasePath);
15899
15900 // Implicitly cast "this" to the appropriately-qualified base type.
15901 // Dereference "this".
15902 CastBuilder To(
15903 ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
15904 : static_cast<ExprBuilder &>(*DerefThis),
15905 Context.getQualifiedType(T: BaseType, Qs: ObjectType.getQualifiers()),
15906 VK_LValue, BasePath);
15907
15908 // Build the move.
15909 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: BaseType,
15910 To, From,
15911 /*CopyingBaseSubobject=*/true,
15912 /*Copying=*/false);
15913 if (Move.isInvalid()) {
15914 MoveAssignOperator->setInvalidDecl();
15915 return;
15916 }
15917
15918 // Success! Record the move.
15919 Statements.push_back(Elt: Move.getAs<Expr>());
15920 }
15921
15922 // A defaulted move assignment operator for a union copies the object
15923 // representation as if by a memcpy, the same way the defaulted union copy
15924 // constructor does. The memberwise loop below skips union members.
15925 if (ClassDecl->isUnion()) {
15926 ExprBuilder &To = ExplicitObject
15927 ? static_cast<ExprBuilder &>(*ExplicitObject)
15928 : static_cast<ExprBuilder &>(*DerefThis);
15929 // Copying the object representation is correct even for a union that is
15930 // not trivially copyable, so -Wnontrivial-memcall is a false positive
15931 // here. Ignoring warnings rather than casting the arguments to void*
15932 // keeps them typed, which preserves their address space.
15933 IgnoreAllWarningDiagRAII IgnoreWarnings(Diags);
15934 StmtResult Copy = buildMemcpyForAssignmentOp(
15935 S&: *this, Loc, T: Context.getCanonicalTagType(TD: ClassDecl), ToB: To, FromB: OtherRef);
15936 if (Copy.isInvalid()) {
15937 MoveAssignOperator->setInvalidDecl();
15938 return;
15939 }
15940 Statements.push_back(Elt: Copy.getAs<Stmt>());
15941 }
15942
15943 // Assign non-static members.
15944 for (auto *Field : ClassDecl->fields()) {
15945 // Union members are copied by the whole-object memcpy emitted above.
15946 if (Field->isUnnamedBitField() || Field->getParent()->isUnion())
15947 continue;
15948
15949 if (Field->isInvalidDecl()) {
15950 Invalid = true;
15951 continue;
15952 }
15953
15954 // Check for members of reference type; we can't move those.
15955 if (Field->getType()->isReferenceType()) {
15956 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15957 << Context.getCanonicalTagType(TD: ClassDecl) << 0
15958 << Field->getDeclName();
15959 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15960 Invalid = true;
15961 continue;
15962 }
15963
15964 // Check for members of const-qualified, non-class type.
15965 QualType BaseType = Context.getBaseElementType(QT: Field->getType());
15966 if (!BaseType->isRecordType() && BaseType.isConstQualified()) {
15967 Diag(Loc: ClassDecl->getLocation(), DiagID: diag::err_uninitialized_member_for_assign)
15968 << Context.getCanonicalTagType(TD: ClassDecl) << 1
15969 << Field->getDeclName();
15970 Diag(Loc: Field->getLocation(), DiagID: diag::note_declared_at);
15971 Invalid = true;
15972 continue;
15973 }
15974
15975 // Suppress assigning zero-width bitfields.
15976 if (Field->isZeroLengthBitField())
15977 continue;
15978
15979 QualType FieldType = Field->getType().getNonReferenceType();
15980 if (FieldType->isIncompleteArrayType()) {
15981 assert(ClassDecl->hasFlexibleArrayMember() &&
15982 "Incomplete array type is not valid");
15983 continue;
15984 }
15985
15986 // Build references to the field in the object we're copying from and to.
15987 LookupResult MemberLookup(*this, Field->getDeclName(), Loc,
15988 LookupMemberName);
15989 MemberLookup.addDecl(D: Field);
15990 MemberLookup.resolveKind();
15991 MemberBuilder From(MoveOther, OtherRefType,
15992 /*IsArrow=*/false, MemberLookup);
15993 MemberBuilder To(ObjectParameter, ObjectType, IsArrow, MemberLookup);
15994
15995 assert(!From.build(*this, Loc)->isLValue() && // could be xvalue or prvalue
15996 "Member reference with rvalue base must be rvalue except for reference "
15997 "members, which aren't allowed for move assignment.");
15998
15999 // Build the move of this field.
16000 StmtResult Move = buildSingleCopyAssign(S&: *this, Loc, T: FieldType,
16001 To, From,
16002 /*CopyingBaseSubobject=*/false,
16003 /*Copying=*/false);
16004 if (Move.isInvalid()) {
16005 MoveAssignOperator->setInvalidDecl();
16006 return;
16007 }
16008
16009 // Success! Record the copy.
16010 Statements.push_back(Elt: Move.getAs<Stmt>());
16011 }
16012
16013 if (!Invalid) {
16014 // Add a "return *this;"
16015 Expr *ThisExpr =
16016 (ExplicitObject ? static_cast<ExprBuilder &>(*ExplicitObject)
16017 : LangOpts.HLSL ? static_cast<ExprBuilder &>(*This)
16018 : static_cast<ExprBuilder &>(*DerefThis))
16019 .build(S&: *this, Loc);
16020
16021 StmtResult Return = BuildReturnStmt(ReturnLoc: Loc, RetValExp: ThisExpr);
16022 if (Return.isInvalid())
16023 Invalid = true;
16024 else
16025 Statements.push_back(Elt: Return.getAs<Stmt>());
16026 }
16027
16028 if (Invalid) {
16029 MoveAssignOperator->setInvalidDecl();
16030 return;
16031 }
16032
16033 StmtResult Body;
16034 {
16035 CompoundScopeRAII CompoundScope(*this);
16036 Body = ActOnCompoundStmt(L: Loc, R: Loc, Elts: Statements,
16037 /*isStmtExpr=*/false);
16038 assert(!Body.isInvalid() && "Compound statement creation cannot fail");
16039 }
16040 MoveAssignOperator->setBody(Body.getAs<Stmt>());
16041 MoveAssignOperator->markUsed(C&: Context);
16042
16043 if (ASTMutationListener *L = getASTMutationListener()) {
16044 L->CompletedImplicitDefinition(D: MoveAssignOperator);
16045 }
16046}
16047
16048CXXConstructorDecl *Sema::DeclareImplicitCopyConstructor(
16049 CXXRecordDecl *ClassDecl) {
16050 // C++ [class.copy]p4:
16051 // If the class definition does not explicitly declare a copy
16052 // constructor, one is declared implicitly.
16053 assert(ClassDecl->needsImplicitCopyConstructor());
16054
16055 DeclaringSpecialMember DSM(*this, ClassDecl,
16056 CXXSpecialMemberKind::CopyConstructor);
16057 if (DSM.isAlreadyBeingDeclared())
16058 return nullptr;
16059
16060 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16061 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16062 /*OwnsTag=*/false);
16063 QualType ArgType = ClassType;
16064 bool Const = ClassDecl->implicitCopyConstructorHasConstParam();
16065 if (Const)
16066 ArgType = ArgType.withConst();
16067
16068 LangAS AS = getDefaultCXXMethodAddrSpace();
16069 if (AS != LangAS::Default)
16070 ArgType = Context.getAddrSpaceQualType(T: ArgType, AddressSpace: AS);
16071
16072 ArgType = Context.getLValueReferenceType(T: ArgType);
16073
16074 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16075 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, ConstArg: Const);
16076
16077 DeclarationName Name
16078 = Context.DeclarationNames.getCXXConstructorName(
16079 Ty: Context.getCanonicalType(T: ClassType));
16080 SourceLocation ClassLoc = ClassDecl->getLocation();
16081 DeclarationNameInfo NameInfo(Name, ClassLoc);
16082
16083 // An implicitly-declared copy constructor is an inline public
16084 // member of its class.
16085 CXXConstructorDecl *CopyConstructor = CXXConstructorDecl::Create(
16086 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16087 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16088 /*isInline=*/true,
16089 /*isImplicitlyDeclared=*/true,
16090 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16091 : ConstexprSpecKind::Unspecified);
16092 CopyConstructor->setAccess(AS_public);
16093 CopyConstructor->setDefaulted();
16094
16095 setupImplicitSpecialMemberType(SpecialMem: CopyConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16096
16097 if (getLangOpts().CUDA)
16098 CUDA().inferTargetForImplicitSpecialMember(
16099 ClassDecl, CSM: CXXSpecialMemberKind::CopyConstructor, MemberDecl: CopyConstructor,
16100 /* ConstRHS */ Const,
16101 /* Diagnose */ false);
16102
16103 // During template instantiation of special member functions we need a
16104 // reliable TypeSourceInfo for the parameter types in order to allow functions
16105 // to be substituted.
16106 TypeSourceInfo *TSI = nullptr;
16107 if (inTemplateInstantiation() && ClassDecl->isLambda())
16108 TSI = Context.getTrivialTypeSourceInfo(T: ArgType);
16109
16110 // Add the parameter to the constructor.
16111 ParmVarDecl *FromParam =
16112 ParmVarDecl::Create(C&: Context, DC: CopyConstructor, StartLoc: ClassLoc, IdLoc: ClassLoc,
16113 /*IdentifierInfo=*/Id: nullptr, T: ArgType,
16114 /*TInfo=*/TSI, S: SC_None, DefArg: nullptr);
16115 CopyConstructor->setParams(FromParam);
16116
16117 CopyConstructor->setTrivial(
16118 ClassDecl->needsOverloadResolutionForCopyConstructor()
16119 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16120 CSM: CXXSpecialMemberKind::CopyConstructor)
16121 : ClassDecl->hasTrivialCopyConstructor());
16122
16123 CopyConstructor->setTrivialForCall(
16124 ClassDecl->hasAttr<TrivialABIAttr>() ||
16125 (ClassDecl->needsOverloadResolutionForCopyConstructor()
16126 ? SpecialMemberIsTrivial(MD: CopyConstructor,
16127 CSM: CXXSpecialMemberKind::CopyConstructor,
16128 TAH: TrivialABIHandling::ConsiderTrivialABI)
16129 : ClassDecl->hasTrivialCopyConstructorForCall()));
16130
16131 // Note that we have declared this constructor.
16132 ++getASTContext().NumImplicitCopyConstructorsDeclared;
16133
16134 Scope *S = getScopeForContext(Ctx: ClassDecl);
16135 CheckImplicitSpecialMemberDeclaration(S, FD: CopyConstructor);
16136
16137 if (ShouldDeleteSpecialMember(MD: CopyConstructor,
16138 CSM: CXXSpecialMemberKind::CopyConstructor)) {
16139 ClassDecl->setImplicitCopyConstructorIsDeleted();
16140 SetDeclDeleted(dcl: CopyConstructor, DelLoc: ClassLoc);
16141 }
16142
16143 if (S)
16144 PushOnScopeChains(D: CopyConstructor, S, AddToContext: false);
16145 ClassDecl->addDecl(D: CopyConstructor);
16146
16147 return CopyConstructor;
16148}
16149
16150void Sema::DefineImplicitCopyConstructor(SourceLocation CurrentLocation,
16151 CXXConstructorDecl *CopyConstructor) {
16152 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, CopyConstructor);
16153 assert((CopyConstructor->isDefaulted() &&
16154 CopyConstructor->isCopyConstructor() &&
16155 !CopyConstructor->doesThisDeclarationHaveABody() &&
16156 !CopyConstructor->isDeleted()) &&
16157 "DefineImplicitCopyConstructor - call it for implicit copy ctor");
16158 if (CopyConstructor->willHaveBody() || CopyConstructor->isInvalidDecl())
16159 return;
16160
16161 CXXRecordDecl *ClassDecl = CopyConstructor->getParent();
16162 assert(ClassDecl && "DefineImplicitCopyConstructor - invalid constructor");
16163
16164 SynthesizedFunctionScope Scope(*this, CopyConstructor);
16165
16166 // The exception specification is needed because we are defining the
16167 // function.
16168 ResolveExceptionSpec(Loc: CurrentLocation,
16169 FPT: CopyConstructor->getType()->castAs<FunctionProtoType>());
16170 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16171
16172 // Add a context note for diagnostics produced after this point.
16173 Scope.addContextNote(UseLoc: CurrentLocation);
16174
16175 // C++11 [class.copy]p7:
16176 // The [definition of an implicitly declared copy constructor] is
16177 // deprecated if the class has a user-declared copy assignment operator
16178 // or a user-declared destructor.
16179 if (getLangOpts().CPlusPlus11 && CopyConstructor->isImplicit())
16180 diagnoseDeprecatedCopyOperation(S&: *this, CopyOp: CopyConstructor);
16181
16182 if (SetCtorInitializers(Constructor: CopyConstructor, /*AnyErrors=*/false)) {
16183 CopyConstructor->setInvalidDecl();
16184 } else {
16185 SourceLocation Loc = CopyConstructor->getEndLoc().isValid()
16186 ? CopyConstructor->getEndLoc()
16187 : CopyConstructor->getLocation();
16188 Sema::CompoundScopeRAII CompoundScope(*this);
16189 CopyConstructor->setBody(
16190 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16191 CopyConstructor->markUsed(C&: Context);
16192 }
16193
16194 if (ASTMutationListener *L = getASTMutationListener()) {
16195 L->CompletedImplicitDefinition(D: CopyConstructor);
16196 }
16197}
16198
16199CXXConstructorDecl *Sema::DeclareImplicitMoveConstructor(
16200 CXXRecordDecl *ClassDecl) {
16201 assert(ClassDecl->needsImplicitMoveConstructor());
16202
16203 DeclaringSpecialMember DSM(*this, ClassDecl,
16204 CXXSpecialMemberKind::MoveConstructor);
16205 if (DSM.isAlreadyBeingDeclared())
16206 return nullptr;
16207
16208 QualType ClassType = Context.getTagType(Keyword: ElaboratedTypeKeyword::None,
16209 /*Qualifier=*/std::nullopt, TD: ClassDecl,
16210 /*OwnsTag=*/false);
16211
16212 QualType ArgType = ClassType;
16213 LangAS AS = getDefaultCXXMethodAddrSpace();
16214 if (AS != LangAS::Default)
16215 ArgType = Context.getAddrSpaceQualType(T: ClassType, AddressSpace: AS);
16216 ArgType = Context.getRValueReferenceType(T: ArgType);
16217
16218 bool Constexpr = defaultedSpecialMemberIsConstexpr(
16219 S&: *this, ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, ConstArg: false);
16220
16221 DeclarationName Name
16222 = Context.DeclarationNames.getCXXConstructorName(
16223 Ty: Context.getCanonicalType(T: ClassType));
16224 SourceLocation ClassLoc = ClassDecl->getLocation();
16225 DeclarationNameInfo NameInfo(Name, ClassLoc);
16226
16227 // C++11 [class.copy]p11:
16228 // An implicitly-declared copy/move constructor is an inline public
16229 // member of its class.
16230 CXXConstructorDecl *MoveConstructor = CXXConstructorDecl::Create(
16231 C&: Context, RD: ClassDecl, StartLoc: ClassLoc, NameInfo, T: QualType(), /*TInfo=*/nullptr,
16232 ES: ExplicitSpecifier(), UsesFPIntrin: getCurFPFeatures().isFPConstrained(),
16233 /*isInline=*/true,
16234 /*isImplicitlyDeclared=*/true,
16235 ConstexprKind: Constexpr ? ConstexprSpecKind::Constexpr
16236 : ConstexprSpecKind::Unspecified);
16237 MoveConstructor->setAccess(AS_public);
16238 MoveConstructor->setDefaulted();
16239
16240 setupImplicitSpecialMemberType(SpecialMem: MoveConstructor, ResultTy: Context.VoidTy, Args: ArgType);
16241
16242 if (getLangOpts().CUDA)
16243 CUDA().inferTargetForImplicitSpecialMember(
16244 ClassDecl, CSM: CXXSpecialMemberKind::MoveConstructor, MemberDecl: MoveConstructor,
16245 /* ConstRHS */ false,
16246 /* Diagnose */ false);
16247
16248 // Add the parameter to the constructor.
16249 ParmVarDecl *FromParam = ParmVarDecl::Create(C&: Context, DC: MoveConstructor,
16250 StartLoc: ClassLoc, IdLoc: ClassLoc,
16251 /*IdentifierInfo=*/Id: nullptr,
16252 T: ArgType, /*TInfo=*/nullptr,
16253 S: SC_None, DefArg: nullptr);
16254 MoveConstructor->setParams(FromParam);
16255
16256 MoveConstructor->setTrivial(
16257 ClassDecl->needsOverloadResolutionForMoveConstructor()
16258 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16259 CSM: CXXSpecialMemberKind::MoveConstructor)
16260 : ClassDecl->hasTrivialMoveConstructor());
16261
16262 MoveConstructor->setTrivialForCall(
16263 ClassDecl->hasAttr<TrivialABIAttr>() ||
16264 (ClassDecl->needsOverloadResolutionForMoveConstructor()
16265 ? SpecialMemberIsTrivial(MD: MoveConstructor,
16266 CSM: CXXSpecialMemberKind::MoveConstructor,
16267 TAH: TrivialABIHandling::ConsiderTrivialABI)
16268 : ClassDecl->hasTrivialMoveConstructorForCall()));
16269
16270 // Note that we have declared this constructor.
16271 ++getASTContext().NumImplicitMoveConstructorsDeclared;
16272
16273 Scope *S = getScopeForContext(Ctx: ClassDecl);
16274 CheckImplicitSpecialMemberDeclaration(S, FD: MoveConstructor);
16275
16276 if (ShouldDeleteSpecialMember(MD: MoveConstructor,
16277 CSM: CXXSpecialMemberKind::MoveConstructor)) {
16278 ClassDecl->setImplicitMoveConstructorIsDeleted();
16279 SetDeclDeleted(dcl: MoveConstructor, DelLoc: ClassLoc);
16280 }
16281
16282 if (S)
16283 PushOnScopeChains(D: MoveConstructor, S, AddToContext: false);
16284 ClassDecl->addDecl(D: MoveConstructor);
16285
16286 return MoveConstructor;
16287}
16288
16289void Sema::DefineImplicitMoveConstructor(SourceLocation CurrentLocation,
16290 CXXConstructorDecl *MoveConstructor) {
16291 DefaultedFunctionFPFeaturesRAII RestoreFP(*this, MoveConstructor);
16292 assert((MoveConstructor->isDefaulted() &&
16293 MoveConstructor->isMoveConstructor() &&
16294 !MoveConstructor->doesThisDeclarationHaveABody() &&
16295 !MoveConstructor->isDeleted()) &&
16296 "DefineImplicitMoveConstructor - call it for implicit move ctor");
16297 if (MoveConstructor->willHaveBody() || MoveConstructor->isInvalidDecl())
16298 return;
16299
16300 CXXRecordDecl *ClassDecl = MoveConstructor->getParent();
16301 assert(ClassDecl && "DefineImplicitMoveConstructor - invalid constructor");
16302
16303 SynthesizedFunctionScope Scope(*this, MoveConstructor);
16304
16305 // The exception specification is needed because we are defining the
16306 // function.
16307 ResolveExceptionSpec(Loc: CurrentLocation,
16308 FPT: MoveConstructor->getType()->castAs<FunctionProtoType>());
16309 MarkVTableUsed(Loc: CurrentLocation, Class: ClassDecl);
16310
16311 // Add a context note for diagnostics produced after this point.
16312 Scope.addContextNote(UseLoc: CurrentLocation);
16313
16314 if (SetCtorInitializers(Constructor: MoveConstructor, /*AnyErrors=*/false)) {
16315 MoveConstructor->setInvalidDecl();
16316 } else {
16317 SourceLocation Loc = MoveConstructor->getEndLoc().isValid()
16318 ? MoveConstructor->getEndLoc()
16319 : MoveConstructor->getLocation();
16320 Sema::CompoundScopeRAII CompoundScope(*this);
16321 MoveConstructor->setBody(
16322 ActOnCompoundStmt(L: Loc, R: Loc, Elts: {}, /*isStmtExpr=*/false).getAs<Stmt>());
16323 MoveConstructor->markUsed(C&: Context);
16324 }
16325
16326 if (ASTMutationListener *L = getASTMutationListener()) {
16327 L->CompletedImplicitDefinition(D: MoveConstructor);
16328 }
16329}
16330
16331bool Sema::isImplicitlyDeleted(FunctionDecl *FD) {
16332 return FD->isDeleted() && FD->isDefaulted() && isa<CXXMethodDecl>(Val: FD);
16333}
16334
16335void Sema::DefineImplicitLambdaToFunctionPointerConversion(
16336 SourceLocation CurrentLocation,
16337 CXXConversionDecl *Conv) {
16338 SynthesizedFunctionScope Scope(*this, Conv);
16339 assert(!Conv->getReturnType()->isUndeducedType());
16340
16341 QualType ConvRT = Conv->getType()->castAs<FunctionType>()->getReturnType();
16342 CallingConv CC =
16343 ConvRT->getPointeeType()->castAs<FunctionType>()->getCallConv();
16344
16345 CXXRecordDecl *Lambda = Conv->getParent();
16346 FunctionDecl *CallOp = Lambda->getLambdaCallOperator();
16347 FunctionDecl *Invoker =
16348 CallOp->hasCXXExplicitFunctionObjectParameter() || CallOp->isStatic()
16349 ? CallOp
16350 : Lambda->getLambdaStaticInvoker(CC);
16351
16352 if (auto *TemplateArgs = Conv->getTemplateSpecializationArgs()) {
16353 CallOp = InstantiateFunctionDeclaration(
16354 FTD: CallOp->getDescribedFunctionTemplate(), Args: TemplateArgs, Loc: CurrentLocation);
16355 if (!CallOp)
16356 return;
16357
16358 if (CallOp != Invoker) {
16359 Invoker = InstantiateFunctionDeclaration(
16360 FTD: Invoker->getDescribedFunctionTemplate(), Args: TemplateArgs,
16361 Loc: CurrentLocation);
16362 if (!Invoker)
16363 return;
16364 }
16365 }
16366
16367 if (CallOp->isInvalidDecl())
16368 return;
16369
16370 // Mark the call operator referenced (and add to pending instantiations
16371 // if necessary).
16372 // For both the conversion and static-invoker template specializations
16373 // we construct their body's in this function, so no need to add them
16374 // to the PendingInstantiations.
16375 MarkFunctionReferenced(Loc: CurrentLocation, Func: CallOp);
16376
16377 if (Invoker != CallOp) {
16378 // Fill in the __invoke function with a dummy implementation. IR generation
16379 // will fill in the actual details. Update its type in case it contained
16380 // an 'auto'.
16381 Invoker->markUsed(C&: Context);
16382 Invoker->setReferenced();
16383 Invoker->setType(Conv->getReturnType()->getPointeeType());
16384 Invoker->setBody(new (Context) CompoundStmt(Conv->getLocation()));
16385 }
16386
16387 // Construct the body of the conversion function { return __invoke; }.
16388 Expr *FunctionRef = BuildDeclRefExpr(D: Invoker, Ty: Invoker->getType(), VK: VK_LValue,
16389 Loc: Conv->getLocation());
16390 assert(FunctionRef && "Can't refer to __invoke function?");
16391 Stmt *Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: FunctionRef).get();
16392 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: Return, FPFeatures: FPOptionsOverride(),
16393 LB: Conv->getLocation(), RB: Conv->getLocation()));
16394 Conv->markUsed(C&: Context);
16395 Conv->setReferenced();
16396
16397 if (ASTMutationListener *L = getASTMutationListener()) {
16398 L->CompletedImplicitDefinition(D: Conv);
16399 if (Invoker != CallOp)
16400 L->CompletedImplicitDefinition(D: Invoker);
16401 }
16402}
16403
16404void Sema::DefineImplicitLambdaToBlockPointerConversion(
16405 SourceLocation CurrentLocation, CXXConversionDecl *Conv) {
16406 assert(!Conv->getParent()->isGenericLambda());
16407
16408 SynthesizedFunctionScope Scope(*this, Conv);
16409
16410 // Copy-initialize the lambda object as needed to capture it.
16411 Expr *This = ActOnCXXThis(Loc: CurrentLocation).get();
16412 Expr *DerefThis =CreateBuiltinUnaryOp(OpLoc: CurrentLocation, Opc: UO_Deref, InputExpr: This).get();
16413
16414 ExprResult BuildBlock = BuildBlockForLambdaConversion(CurrentLocation,
16415 ConvLocation: Conv->getLocation(),
16416 Conv, Src: DerefThis);
16417
16418 // If we're not under ARC, make sure we still get the _Block_copy/autorelease
16419 // behavior. Note that only the general conversion function does this
16420 // (since it's unusable otherwise); in the case where we inline the
16421 // block literal, it has block literal lifetime semantics.
16422 if (!BuildBlock.isInvalid() && !getLangOpts().ObjCAutoRefCount)
16423 BuildBlock = ImplicitCastExpr::Create(
16424 Context, T: BuildBlock.get()->getType(), Kind: CK_CopyAndAutoreleaseBlockObject,
16425 Operand: BuildBlock.get(), BasePath: nullptr, Cat: VK_PRValue, FPO: FPOptionsOverride());
16426
16427 if (BuildBlock.isInvalid()) {
16428 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16429 Conv->setInvalidDecl();
16430 return;
16431 }
16432
16433 // Create the return statement that returns the block from the conversion
16434 // function.
16435 StmtResult Return = BuildReturnStmt(ReturnLoc: Conv->getLocation(), RetValExp: BuildBlock.get());
16436 if (Return.isInvalid()) {
16437 Diag(Loc: CurrentLocation, DiagID: diag::note_lambda_to_block_conv);
16438 Conv->setInvalidDecl();
16439 return;
16440 }
16441
16442 // Set the body of the conversion function.
16443 Stmt *ReturnS = Return.get();
16444 Conv->setBody(CompoundStmt::Create(C: Context, Stmts: ReturnS, FPFeatures: FPOptionsOverride(),
16445 LB: Conv->getLocation(), RB: Conv->getLocation()));
16446 Conv->markUsed(C&: Context);
16447
16448 // We're done; notify the mutation listener, if any.
16449 if (ASTMutationListener *L = getASTMutationListener()) {
16450 L->CompletedImplicitDefinition(D: Conv);
16451 }
16452}
16453
16454/// Determine whether the given list arguments contains exactly one
16455/// "real" (non-default) argument.
16456static bool hasOneRealArgument(MultiExprArg Args) {
16457 switch (Args.size()) {
16458 case 0:
16459 return false;
16460
16461 default:
16462 if (!Args[1]->isDefaultArgument())
16463 return false;
16464
16465 [[fallthrough]];
16466 case 1:
16467 return !Args[0]->isDefaultArgument();
16468 }
16469
16470 return false;
16471}
16472
16473ExprResult Sema::BuildCXXConstructExpr(
16474 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16475 CXXConstructorDecl *Constructor, MultiExprArg ExprArgs,
16476 bool HadMultipleCandidates, bool IsListInitialization,
16477 bool IsStdInitListInitialization, bool RequiresZeroInit,
16478 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16479 bool Elidable = false;
16480
16481 // C++0x [class.copy]p34:
16482 // When certain criteria are met, an implementation is allowed to
16483 // omit the copy/move construction of a class object, even if the
16484 // copy/move constructor and/or destructor for the object have
16485 // side effects. [...]
16486 // - when a temporary class object that has not been bound to a
16487 // reference (12.2) would be copied/moved to a class object
16488 // with the same cv-unqualified type, the copy/move operation
16489 // can be omitted by constructing the temporary object
16490 // directly into the target of the omitted copy/move
16491 if (ConstructKind == CXXConstructionKind::Complete && Constructor &&
16492 // FIXME: Converting constructors should also be accepted.
16493 // But to fix this, the logic that digs down into a CXXConstructExpr
16494 // to find the source object needs to handle it.
16495 // Right now it assumes the source object is passed directly as the
16496 // first argument.
16497 Constructor->isCopyOrMoveConstructor() && hasOneRealArgument(Args: ExprArgs)) {
16498 Expr *SubExpr = ExprArgs[0];
16499 // FIXME: Per above, this is also incorrect if we want to accept
16500 // converting constructors, as isTemporaryObject will
16501 // reject temporaries with different type from the
16502 // CXXRecord itself.
16503 Elidable = SubExpr->isTemporaryObject(
16504 Ctx&: Context, TempTy: cast<CXXRecordDecl>(Val: FoundDecl->getDeclContext()));
16505 }
16506
16507 return BuildCXXConstructExpr(ConstructLoc, DeclInitType,
16508 FoundDecl, Constructor,
16509 Elidable, Exprs: ExprArgs, HadMultipleCandidates,
16510 IsListInitialization,
16511 IsStdInitListInitialization, RequiresZeroInit,
16512 ConstructKind, ParenRange);
16513}
16514
16515ExprResult Sema::BuildCXXConstructExpr(
16516 SourceLocation ConstructLoc, QualType DeclInitType, NamedDecl *FoundDecl,
16517 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16518 bool HadMultipleCandidates, bool IsListInitialization,
16519 bool IsStdInitListInitialization, bool RequiresZeroInit,
16520 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16521 if (auto *Shadow = dyn_cast<ConstructorUsingShadowDecl>(Val: FoundDecl)) {
16522 Constructor = findInheritingConstructor(Loc: ConstructLoc, BaseCtor: Constructor, Shadow);
16523 // The only way to get here is if we did overload resolution to find the
16524 // shadow decl, so we don't need to worry about re-checking the trailing
16525 // requires clause.
16526 if (DiagnoseUseOfOverloadedDecl(D: Constructor, Loc: ConstructLoc))
16527 return ExprError();
16528 }
16529
16530 return BuildCXXConstructExpr(
16531 ConstructLoc, DeclInitType, Constructor, Elidable, Exprs: ExprArgs,
16532 HadMultipleCandidates, IsListInitialization, IsStdInitListInitialization,
16533 RequiresZeroInit, ConstructKind, ParenRange);
16534}
16535
16536/// BuildCXXConstructExpr - Creates a complete call to a constructor,
16537/// including handling of its default argument expressions.
16538ExprResult Sema::BuildCXXConstructExpr(
16539 SourceLocation ConstructLoc, QualType DeclInitType,
16540 CXXConstructorDecl *Constructor, bool Elidable, MultiExprArg ExprArgs,
16541 bool HadMultipleCandidates, bool IsListInitialization,
16542 bool IsStdInitListInitialization, bool RequiresZeroInit,
16543 CXXConstructionKind ConstructKind, SourceRange ParenRange) {
16544 assert(declaresSameEntity(
16545 Constructor->getParent(),
16546 DeclInitType->getBaseElementTypeUnsafe()->getAsCXXRecordDecl()) &&
16547 "given constructor for wrong type");
16548 MarkFunctionReferenced(Loc: ConstructLoc, Func: Constructor);
16549 if (getLangOpts().CUDA && !CUDA().CheckCall(Loc: ConstructLoc, Callee: Constructor))
16550 return ExprError();
16551
16552 return CheckForImmediateInvocation(
16553 E: CXXConstructExpr::Create(
16554 Ctx: Context, Ty: DeclInitType, Loc: ConstructLoc, Ctor: Constructor, Elidable, Args: ExprArgs,
16555 HadMultipleCandidates, ListInitialization: IsListInitialization,
16556 StdInitListInitialization: IsStdInitListInitialization, ZeroInitialization: RequiresZeroInit,
16557 ConstructKind: static_cast<CXXConstructionKind>(ConstructKind), ParenOrBraceRange: ParenRange),
16558 Decl: Constructor);
16559}
16560
16561void Sema::FinalizeVarWithDestructor(VarDecl *VD, CXXRecordDecl *ClassDecl) {
16562 if (VD->isInvalidDecl()) return;
16563 // If initializing the variable failed, don't also diagnose problems with
16564 // the destructor, they're likely related.
16565 if (VD->getInit() && VD->getInit()->containsErrors())
16566 return;
16567
16568 ClassDecl = ClassDecl->getDefinitionOrSelf();
16569 if (ClassDecl->isInvalidDecl()) return;
16570 if (ClassDecl->hasIrrelevantDestructor()) return;
16571 if (ClassDecl->isDependentContext()) return;
16572
16573 if (VD->isNoDestroy(getASTContext()))
16574 return;
16575
16576 CXXDestructorDecl *Destructor = LookupDestructor(Class: ClassDecl);
16577 // The result of `LookupDestructor` might be nullptr if the destructor is
16578 // invalid, in which case it is marked as `IneligibleOrNotSelected` and
16579 // will not be selected by `CXXRecordDecl::getDestructor()`.
16580 if (!Destructor)
16581 return;
16582 // If this is an array, we'll require the destructor during initialization, so
16583 // we can skip over this. We still want to emit exit-time destructor warnings
16584 // though.
16585 if (!VD->getType()->isArrayType()) {
16586 MarkFunctionReferenced(Loc: VD->getLocation(), Func: Destructor);
16587 CheckDestructorAccess(Loc: VD->getLocation(), Dtor: Destructor,
16588 PDiag: PDiag(DiagID: diag::err_access_dtor_var)
16589 << VD->getDeclName() << VD->getType());
16590 DiagnoseUseOfDecl(D: Destructor, Locs: VD->getLocation());
16591 }
16592
16593 if (Destructor->isTrivial()) return;
16594
16595 // If the destructor is constexpr, check whether the variable has constant
16596 // destruction now.
16597 if (Destructor->isConstexpr()) {
16598 bool HasConstantInit = false;
16599 if (VD->getInit() && !VD->getInit()->isValueDependent())
16600 HasConstantInit = VD->evaluateValue();
16601 SmallVector<PartialDiagnosticAt, 8> Notes;
16602 if (!VD->evaluateDestruction(Notes) && VD->isConstexpr() &&
16603 HasConstantInit) {
16604 Diag(Loc: VD->getLocation(),
16605 DiagID: diag::err_constexpr_var_requires_const_destruction) << VD;
16606 for (const PartialDiagnosticAt &Note : Notes)
16607 Diag(Loc: Note.first, PD: Note.second);
16608 }
16609 }
16610
16611 if (!VD->hasGlobalStorage() || !VD->needsDestruction(Ctx: Context))
16612 return;
16613
16614 // Emit warning for non-trivial dtor in global scope (a real global,
16615 // class-static, function-static).
16616 if (!VD->hasAttr<AlwaysDestroyAttr>())
16617 Diag(Loc: VD->getLocation(), DiagID: diag::warn_exit_time_destructor);
16618
16619 // TODO: this should be re-enabled for static locals by !CXAAtExit
16620 if (!VD->isStaticLocal())
16621 Diag(Loc: VD->getLocation(), DiagID: diag::warn_global_destructor);
16622}
16623
16624bool Sema::CompleteConstructorCall(CXXConstructorDecl *Constructor,
16625 QualType DeclInitType, MultiExprArg ArgsPtr,
16626 SourceLocation Loc,
16627 SmallVectorImpl<Expr *> &ConvertedArgs,
16628 bool AllowExplicit,
16629 bool IsListInitialization) {
16630 // FIXME: This duplicates a lot of code from Sema::ConvertArgumentsForCall.
16631 unsigned NumArgs = ArgsPtr.size();
16632 Expr **Args = ArgsPtr.data();
16633
16634 const auto *Proto = Constructor->getType()->castAs<FunctionProtoType>();
16635 unsigned NumParams = Proto->getNumParams();
16636
16637 // If too few arguments are available, we'll fill in the rest with defaults.
16638 if (NumArgs < NumParams)
16639 ConvertedArgs.reserve(N: NumParams);
16640 else
16641 ConvertedArgs.reserve(N: NumArgs);
16642
16643 VariadicCallType CallType = Proto->isVariadic()
16644 ? VariadicCallType::Constructor
16645 : VariadicCallType::DoesNotApply;
16646 SmallVector<Expr *, 8> AllArgs;
16647 bool Invalid = GatherArgumentsForCall(
16648 CallLoc: Loc, FDecl: Constructor, Proto, FirstParam: 0, Args: llvm::ArrayRef(Args, NumArgs), AllArgs,
16649 CallType, AllowExplicit, IsListInitialization);
16650 ConvertedArgs.append(in_start: AllArgs.begin(), in_end: AllArgs.end());
16651
16652 DiagnoseSentinelCalls(D: Constructor, Loc, Args: AllArgs);
16653
16654 CheckConstructorCall(FDecl: Constructor, ThisType: DeclInitType, Args: llvm::ArrayRef(AllArgs),
16655 Proto, Loc);
16656
16657 return Invalid;
16658}
16659
16660TypeAwareAllocationMode Sema::ShouldUseTypeAwareOperatorNewOrDelete() const {
16661 bool SeenTypedOperators = Context.hasSeenTypeAwareOperatorNewOrDelete();
16662 return typeAwareAllocationModeFromBool(IsTypeAwareAllocation: SeenTypedOperators);
16663}
16664
16665FunctionDecl *
16666Sema::BuildTypeAwareUsualDelete(FunctionTemplateDecl *FnTemplateDecl,
16667 QualType DeallocType, SourceLocation Loc) {
16668 if (DeallocType.isNull())
16669 return nullptr;
16670
16671 FunctionDecl *FnDecl = FnTemplateDecl->getTemplatedDecl();
16672 if (!FnDecl->isTypeAwareOperatorNewOrDelete())
16673 return nullptr;
16674
16675 if (FnDecl->isVariadic())
16676 return nullptr;
16677
16678 unsigned NumParams = FnDecl->getNumParams();
16679 constexpr unsigned RequiredParameterCount =
16680 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16681 // A usual deallocation function has no placement parameters
16682 if (NumParams != RequiredParameterCount)
16683 return nullptr;
16684
16685 // A type aware allocation is only usual if the only dependent parameter is
16686 // the first parameter.
16687 if (llvm::any_of(Range: FnDecl->parameters().drop_front(),
16688 P: [](const ParmVarDecl *ParamDecl) {
16689 return ParamDecl->getType()->isDependentType();
16690 }))
16691 return nullptr;
16692
16693 QualType SpecializedTypeIdentity = tryBuildStdTypeIdentity(Type: DeallocType, Loc);
16694 if (SpecializedTypeIdentity.isNull())
16695 return nullptr;
16696
16697 SmallVector<QualType, RequiredParameterCount> ArgTypes;
16698 ArgTypes.reserve(N: NumParams);
16699
16700 // The first parameter to a type aware operator delete is by definition the
16701 // type-identity argument, so we explicitly set this to the target
16702 // type-identity type, the remaining usual parameters should then simply match
16703 // the type declared in the function template.
16704 ArgTypes.push_back(Elt: SpecializedTypeIdentity);
16705 for (unsigned ParamIdx = 1; ParamIdx < RequiredParameterCount; ++ParamIdx)
16706 ArgTypes.push_back(Elt: FnDecl->getParamDecl(i: ParamIdx)->getType());
16707
16708 FunctionProtoType::ExtProtoInfo EPI;
16709 QualType ExpectedFunctionType =
16710 Context.getFunctionType(ResultTy: Context.VoidTy, Args: ArgTypes, EPI);
16711 sema::TemplateDeductionInfo Info(Loc);
16712 FunctionDecl *Result;
16713 if (DeduceTemplateArguments(FunctionTemplate: FnTemplateDecl, ExplicitTemplateArgs: nullptr, ArgFunctionType: ExpectedFunctionType,
16714 Specialization&: Result, Info) != TemplateDeductionResult::Success)
16715 return nullptr;
16716 return Result;
16717}
16718
16719static inline bool
16720CheckOperatorNewDeleteDeclarationScope(Sema &SemaRef,
16721 const FunctionDecl *FnDecl) {
16722 const DeclContext *DC = FnDecl->getDeclContext()->getRedeclContext();
16723 if (isa<NamespaceDecl>(Val: DC)) {
16724 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16725 DiagID: diag::err_operator_new_delete_declared_in_namespace)
16726 << FnDecl->getDeclName();
16727 }
16728
16729 if (isa<TranslationUnitDecl>(Val: DC) &&
16730 FnDecl->getStorageClass() == SC_Static) {
16731 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16732 DiagID: diag::err_operator_new_delete_declared_static)
16733 << FnDecl->getDeclName();
16734 }
16735
16736 return false;
16737}
16738
16739static CanQualType RemoveAddressSpaceFromPtr(Sema &SemaRef,
16740 const PointerType *PtrTy) {
16741 auto &Ctx = SemaRef.Context;
16742 Qualifiers PtrQuals = PtrTy->getPointeeType().getQualifiers();
16743 PtrQuals.removeAddressSpace();
16744 return Ctx.getPointerType(T: Ctx.getCanonicalType(T: Ctx.getQualifiedType(
16745 T: PtrTy->getPointeeType().getUnqualifiedType(), Qs: PtrQuals)));
16746}
16747
16748enum class AllocationOperatorKind { New, Delete };
16749
16750static bool IsPotentiallyTypeAwareOperatorNewOrDelete(Sema &SemaRef,
16751 const FunctionDecl *FD,
16752 bool *WasMalformed) {
16753 const Decl *MalformedDecl = nullptr;
16754 if (FD->getNumParams() > 0 &&
16755 SemaRef.isStdTypeIdentity(Ty: FD->getParamDecl(i: 0)->getType(),
16756 /*TypeArgument=*/Element: nullptr, MalformedDecl: &MalformedDecl))
16757 return true;
16758
16759 if (!MalformedDecl)
16760 return false;
16761
16762 if (WasMalformed)
16763 *WasMalformed = true;
16764
16765 return true;
16766}
16767
16768static bool isDestroyingDeleteT(QualType Type) {
16769 auto *RD = Type->getAsCXXRecordDecl();
16770 return RD && RD->isInStdNamespace() && RD->getIdentifier() &&
16771 RD->getIdentifier()->isStr(Str: "destroying_delete_t");
16772}
16773
16774static bool IsPotentiallyDestroyingOperatorDelete(Sema &SemaRef,
16775 const FunctionDecl *FD) {
16776 // C++ P0722:
16777 // Within a class C, a single object deallocation function with signature
16778 // (T, std::destroying_delete_t, <more params>)
16779 // is a destroying operator delete.
16780 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16781 SemaRef, FD, /*WasMalformed=*/nullptr);
16782 unsigned DestroyingDeleteIdx = IsPotentiallyTypeAware + /* address */ 1;
16783 return isa<CXXMethodDecl>(Val: FD) && FD->getOverloadedOperator() == OO_Delete &&
16784 FD->getNumParams() > DestroyingDeleteIdx &&
16785 isDestroyingDeleteT(Type: FD->getParamDecl(i: DestroyingDeleteIdx)->getType());
16786}
16787
16788static inline bool CheckOperatorNewDeleteTypes(
16789 Sema &SemaRef, FunctionDecl *FnDecl, AllocationOperatorKind OperatorKind,
16790 CanQualType ExpectedResultType, CanQualType ExpectedSizeOrAddressParamType,
16791 unsigned DependentParamTypeDiag, unsigned InvalidParamTypeDiag) {
16792 auto NormalizeType = [&SemaRef](QualType T) {
16793 if (SemaRef.getLangOpts().OpenCLCPlusPlus) {
16794 // The operator is valid on any address space for OpenCL.
16795 // Drop address space from actual and expected result types.
16796 if (const auto PtrTy = T->template getAs<PointerType>())
16797 T = RemoveAddressSpaceFromPtr(SemaRef, PtrTy);
16798 }
16799 return SemaRef.Context.getCanonicalType(T);
16800 };
16801
16802 const unsigned NumParams = FnDecl->getNumParams();
16803 unsigned FirstNonTypeParam = 0;
16804 bool MalformedTypeIdentity = false;
16805 bool IsPotentiallyTypeAware = IsPotentiallyTypeAwareOperatorNewOrDelete(
16806 SemaRef, FD: FnDecl, WasMalformed: &MalformedTypeIdentity);
16807 unsigned MinimumMandatoryArgumentCount = 1;
16808 unsigned SizeParameterIndex = 0;
16809 if (IsPotentiallyTypeAware) {
16810 // We don't emit this diagnosis for template instantiations as we will
16811 // have already emitted it for the original template declaration.
16812 if (!FnDecl->isTemplateInstantiation())
16813 SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_ext_type_aware_allocators);
16814
16815 if (OperatorKind == AllocationOperatorKind::New) {
16816 SizeParameterIndex = 1;
16817 MinimumMandatoryArgumentCount =
16818 FunctionDecl::RequiredTypeAwareNewParameterCount;
16819 } else {
16820 SizeParameterIndex = 2;
16821 MinimumMandatoryArgumentCount =
16822 FunctionDecl::RequiredTypeAwareDeleteParameterCount;
16823 }
16824 FirstNonTypeParam = 1;
16825 }
16826
16827 bool IsPotentiallyDestroyingDelete =
16828 IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: FnDecl);
16829
16830 if (IsPotentiallyDestroyingDelete) {
16831 ++MinimumMandatoryArgumentCount;
16832 ++SizeParameterIndex;
16833 }
16834
16835 if (NumParams < MinimumMandatoryArgumentCount)
16836 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16837 DiagID: diag::err_operator_new_delete_too_few_parameters)
16838 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16839 << FnDecl->getDeclName() << MinimumMandatoryArgumentCount;
16840
16841 for (unsigned Idx = 0; Idx < MinimumMandatoryArgumentCount; ++Idx) {
16842 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: Idx);
16843 if (ParamDecl->hasDefaultArg())
16844 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16845 DiagID: diag::err_operator_new_default_arg)
16846 << FnDecl->getDeclName() << Idx << ParamDecl->getDefaultArgRange();
16847 }
16848
16849 auto *FnType = FnDecl->getType()->castAs<FunctionType>();
16850 QualType CanResultType = NormalizeType(FnType->getReturnType());
16851 QualType CanExpectedResultType = NormalizeType(ExpectedResultType);
16852 QualType CanExpectedSizeOrAddressParamType =
16853 NormalizeType(ExpectedSizeOrAddressParamType);
16854
16855 // Check that the result type is what we expect.
16856 if (CanResultType != CanExpectedResultType) {
16857 // Reject even if the type is dependent; an operator delete function is
16858 // required to have a non-dependent result type.
16859 return SemaRef.Diag(
16860 Loc: FnDecl->getLocation(),
16861 DiagID: CanResultType->isDependentType()
16862 ? diag::err_operator_new_delete_dependent_result_type
16863 : diag::err_operator_new_delete_invalid_result_type)
16864 << FnDecl->getDeclName() << ExpectedResultType;
16865 }
16866
16867 // A function template must have at least 2 parameters.
16868 if (FnDecl->getDescribedFunctionTemplate() && NumParams < 2)
16869 return SemaRef.Diag(Loc: FnDecl->getLocation(),
16870 DiagID: diag::err_operator_new_delete_template_too_few_parameters)
16871 << FnDecl->getDeclName();
16872
16873 auto CheckType = [&](unsigned ParamIdx, QualType ExpectedType,
16874 auto FallbackType) -> bool {
16875 const ParmVarDecl *ParamDecl = FnDecl->getParamDecl(i: ParamIdx);
16876 if (ExpectedType.isNull()) {
16877 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: InvalidParamTypeDiag)
16878 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16879 << FnDecl->getDeclName() << (1 + ParamIdx) << FallbackType
16880 << ParamDecl->getSourceRange();
16881 }
16882 CanQualType CanExpectedTy =
16883 NormalizeType(SemaRef.Context.getCanonicalType(T: ExpectedType));
16884 auto ActualParamType =
16885 NormalizeType(ParamDecl->getType().getUnqualifiedType());
16886 if (ActualParamType == CanExpectedTy)
16887 return false;
16888 unsigned Diagnostic = ActualParamType->isDependentType()
16889 ? DependentParamTypeDiag
16890 : InvalidParamTypeDiag;
16891 return SemaRef.Diag(Loc: FnDecl->getLocation(), DiagID: Diagnostic)
16892 << IsPotentiallyTypeAware << IsPotentiallyDestroyingDelete
16893 << FnDecl->getDeclName() << (1 + ParamIdx) << ExpectedType
16894 << FallbackType << ParamDecl->getSourceRange();
16895 };
16896
16897 // Check that the first parameter type is what we expect.
16898 if (CheckType(FirstNonTypeParam, CanExpectedSizeOrAddressParamType, "size_t"))
16899 return true;
16900
16901 FnDecl->setIsDestroyingOperatorDelete(IsPotentiallyDestroyingDelete);
16902
16903 // If the first parameter type is not a type-identity we're done, otherwise
16904 // we need to ensure the size and alignment parameters have the correct type
16905 if (!IsPotentiallyTypeAware)
16906 return false;
16907
16908 if (CheckType(SizeParameterIndex, SemaRef.Context.getSizeType(), "size_t"))
16909 return true;
16910 TagDecl *StdAlignValTDecl = SemaRef.getStdAlignValT();
16911 CanQualType StdAlignValT =
16912 StdAlignValTDecl ? SemaRef.Context.getCanonicalTagType(TD: StdAlignValTDecl)
16913 : CanQualType();
16914 if (CheckType(SizeParameterIndex + 1, StdAlignValT, "std::align_val_t"))
16915 return true;
16916
16917 FnDecl->setIsTypeAwareOperatorNewOrDelete();
16918 return MalformedTypeIdentity;
16919}
16920
16921static bool CheckOperatorNewDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16922 // C++ [basic.stc.dynamic.allocation]p1:
16923 // A program is ill-formed if an allocation function is declared in a
16924 // namespace scope other than global scope or declared static in global
16925 // scope.
16926 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16927 return true;
16928
16929 CanQualType SizeTy =
16930 SemaRef.Context.getCanonicalType(T: SemaRef.Context.getSizeType());
16931
16932 // C++ [basic.stc.dynamic.allocation]p1:
16933 // The return type shall be void*. The first parameter shall have type
16934 // std::size_t.
16935 return CheckOperatorNewDeleteTypes(
16936 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::New, ExpectedResultType: SemaRef.Context.VoidPtrTy,
16937 ExpectedSizeOrAddressParamType: SizeTy, DependentParamTypeDiag: diag::err_operator_new_dependent_param_type,
16938 InvalidParamTypeDiag: diag::err_operator_new_param_type);
16939}
16940
16941static bool
16942CheckOperatorDeleteDeclaration(Sema &SemaRef, FunctionDecl *FnDecl) {
16943 // C++ [basic.stc.dynamic.deallocation]p1:
16944 // A program is ill-formed if deallocation functions are declared in a
16945 // namespace scope other than global scope or declared static in global
16946 // scope.
16947 if (CheckOperatorNewDeleteDeclarationScope(SemaRef, FnDecl))
16948 return true;
16949
16950 auto *MD = dyn_cast<CXXMethodDecl>(Val: FnDecl);
16951 auto ConstructDestroyingDeleteAddressType = [&]() {
16952 assert(MD);
16953 return SemaRef.Context.getPointerType(
16954 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()));
16955 };
16956
16957 // C++ P2719: A destroying operator delete cannot be type aware
16958 // so for QoL we actually check for this explicitly by considering
16959 // an destroying-delete appropriate address type and the presence of
16960 // any parameter of type destroying_delete_t as an erroneous attempt
16961 // to declare a type aware destroying delete, rather than emitting a
16962 // pile of incorrect parameter type errors.
16963 if (MD && IsPotentiallyTypeAwareOperatorNewOrDelete(
16964 SemaRef, FD: MD, /*WasMalformed=*/nullptr)) {
16965 QualType AddressParamType =
16966 SemaRef.Context.getCanonicalType(T: MD->getParamDecl(i: 1)->getType());
16967 if (AddressParamType != SemaRef.Context.VoidPtrTy &&
16968 AddressParamType == ConstructDestroyingDeleteAddressType()) {
16969 // The address parameter type implies an author trying to construct a
16970 // type aware destroying delete, so we'll see if we can find a parameter
16971 // of type `std::destroying_delete_t`, and if we find it we'll report
16972 // this as being an attempt at a type aware destroying delete just stop
16973 // here. If we don't do this, the resulting incorrect parameter ordering
16974 // results in a pile mismatched argument type errors that don't explain
16975 // the core problem.
16976 for (auto Param : MD->parameters()) {
16977 if (isDestroyingDeleteT(Type: Param->getType())) {
16978 SemaRef.Diag(Loc: MD->getLocation(),
16979 DiagID: diag::err_type_aware_destroying_operator_delete)
16980 << Param->getSourceRange();
16981 return true;
16982 }
16983 }
16984 }
16985 }
16986
16987 // C++ P0722:
16988 // Within a class C, the first parameter of a destroying operator delete
16989 // shall be of type C *. The first parameter of any other deallocation
16990 // function shall be of type void *.
16991 CanQualType ExpectedAddressParamType =
16992 MD && IsPotentiallyDestroyingOperatorDelete(SemaRef, FD: MD)
16993 ? SemaRef.Context.getPointerType(
16994 T: SemaRef.Context.getCanonicalTagType(TD: MD->getParent()))
16995 : SemaRef.Context.VoidPtrTy;
16996
16997 // C++ [basic.stc.dynamic.deallocation]p2:
16998 // Each deallocation function shall return void
16999 if (CheckOperatorNewDeleteTypes(
17000 SemaRef, FnDecl, OperatorKind: AllocationOperatorKind::Delete,
17001 ExpectedResultType: SemaRef.Context.VoidTy, ExpectedSizeOrAddressParamType: ExpectedAddressParamType,
17002 DependentParamTypeDiag: diag::err_operator_delete_dependent_param_type,
17003 InvalidParamTypeDiag: diag::err_operator_delete_param_type))
17004 return true;
17005
17006 // C++ P0722:
17007 // A destroying operator delete shall be a usual deallocation function.
17008 if (MD && !MD->getParent()->isDependentContext() &&
17009 MD->isDestroyingOperatorDelete()) {
17010 if (!SemaRef.isUsualDeallocationFunction(FD: MD)) {
17011 SemaRef.Diag(Loc: MD->getLocation(),
17012 DiagID: diag::err_destroying_operator_delete_not_usual);
17013 return true;
17014 }
17015 }
17016
17017 return false;
17018}
17019
17020bool Sema::CheckOverloadedOperatorDeclaration(FunctionDecl *FnDecl) {
17021 assert(FnDecl && FnDecl->isOverloadedOperator() &&
17022 "Expected an overloaded operator declaration");
17023
17024 OverloadedOperatorKind Op = FnDecl->getOverloadedOperator();
17025
17026 // C++ [over.oper]p5:
17027 // The allocation and deallocation functions, operator new,
17028 // operator new[], operator delete and operator delete[], are
17029 // described completely in 3.7.3. The attributes and restrictions
17030 // found in the rest of this subclause do not apply to them unless
17031 // explicitly stated in 3.7.3.
17032 if (Op == OO_Delete || Op == OO_Array_Delete)
17033 return CheckOperatorDeleteDeclaration(SemaRef&: *this, FnDecl);
17034
17035 if (Op == OO_New || Op == OO_Array_New)
17036 return CheckOperatorNewDeclaration(SemaRef&: *this, FnDecl);
17037
17038 // C++ [over.oper]p7:
17039 // An operator function shall either be a member function or
17040 // be a non-member function and have at least one parameter
17041 // whose type is a class, a reference to a class, an enumeration,
17042 // or a reference to an enumeration.
17043 // Note: Before C++23, a member function could not be static. The only member
17044 // function allowed to be static is the call operator function.
17045 if (CXXMethodDecl *MethodDecl = dyn_cast<CXXMethodDecl>(Val: FnDecl)) {
17046 if (MethodDecl->isStatic()) {
17047 if (Op == OO_Call || Op == OO_Subscript)
17048 DiagCompat(Loc: FnDecl->getLocation(), CompatDiagId: diag_compat::operator_overload_static)
17049 << FnDecl;
17050 else
17051 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_static)
17052 << FnDecl;
17053 }
17054 } else {
17055 bool ClassOrEnumParam = false;
17056 for (auto *Param : FnDecl->parameters()) {
17057 QualType ParamType = Param->getType().getNonReferenceType();
17058 if (ParamType->isDependentType() || ParamType->isRecordType() ||
17059 ParamType->isEnumeralType()) {
17060 ClassOrEnumParam = true;
17061 break;
17062 }
17063 }
17064
17065 if (!ClassOrEnumParam)
17066 return Diag(Loc: FnDecl->getLocation(),
17067 DiagID: diag::err_operator_overload_needs_class_or_enum)
17068 << FnDecl->getDeclName();
17069 }
17070
17071 // C++ [over.oper]p8:
17072 // An operator function cannot have default arguments (8.3.6),
17073 // except where explicitly stated below.
17074 //
17075 // Only the function-call operator (C++ [over.call]p1) and the subscript
17076 // operator (CWG2507) allow default arguments.
17077 if (Op != OO_Call) {
17078 ParmVarDecl *FirstDefaultedParam = nullptr;
17079 for (auto *Param : FnDecl->parameters()) {
17080 if (Param->hasDefaultArg()) {
17081 FirstDefaultedParam = Param;
17082 break;
17083 }
17084 }
17085 if (FirstDefaultedParam) {
17086 if (Op == OO_Subscript) {
17087 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17088 ? diag::ext_subscript_overload
17089 : diag::error_subscript_overload)
17090 << FnDecl->getDeclName() << 1
17091 << FirstDefaultedParam->getDefaultArgRange();
17092 } else {
17093 return Diag(Loc: FirstDefaultedParam->getLocation(),
17094 DiagID: diag::err_operator_overload_default_arg)
17095 << FnDecl->getDeclName()
17096 << FirstDefaultedParam->getDefaultArgRange();
17097 }
17098 }
17099 }
17100
17101 static const bool OperatorUses[NUM_OVERLOADED_OPERATORS][3] = {
17102 { false, false, false }
17103#define OVERLOADED_OPERATOR(Name,Spelling,Token,Unary,Binary,MemberOnly) \
17104 , { Unary, Binary, MemberOnly }
17105#include "clang/Basic/OperatorKinds.def"
17106 };
17107
17108 bool CanBeUnaryOperator = OperatorUses[Op][0];
17109 bool CanBeBinaryOperator = OperatorUses[Op][1];
17110 bool MustBeMemberOperator = OperatorUses[Op][2];
17111
17112 // C++ [over.oper]p8:
17113 // [...] Operator functions cannot have more or fewer parameters
17114 // than the number required for the corresponding operator, as
17115 // described in the rest of this subclause.
17116 unsigned NumParams = FnDecl->getNumParams() +
17117 (isa<CXXMethodDecl>(Val: FnDecl) &&
17118 !FnDecl->hasCXXExplicitFunctionObjectParameter()
17119 ? 1
17120 : 0);
17121 if (Op != OO_Call && Op != OO_Subscript &&
17122 ((NumParams == 1 && !CanBeUnaryOperator) ||
17123 (NumParams == 2 && !CanBeBinaryOperator) || (NumParams < 1) ||
17124 (NumParams > 2))) {
17125 // We have the wrong number of parameters.
17126 unsigned ErrorKind;
17127 if (CanBeUnaryOperator && CanBeBinaryOperator) {
17128 ErrorKind = 2; // 2 -> unary or binary.
17129 } else if (CanBeUnaryOperator) {
17130 ErrorKind = 0; // 0 -> unary
17131 } else {
17132 assert(CanBeBinaryOperator &&
17133 "All non-call overloaded operators are unary or binary!");
17134 ErrorKind = 1; // 1 -> binary
17135 }
17136 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_must_be)
17137 << FnDecl->getDeclName() << NumParams << ErrorKind;
17138 }
17139
17140 if (Op == OO_Subscript && NumParams != 2) {
17141 Diag(Loc: FnDecl->getLocation(), DiagID: LangOpts.CPlusPlus23
17142 ? diag::ext_subscript_overload
17143 : diag::error_subscript_overload)
17144 << FnDecl->getDeclName() << (NumParams == 1 ? 0 : 2);
17145 }
17146
17147 // Overloaded operators other than operator() and operator[] cannot be
17148 // variadic.
17149 if (Op != OO_Call &&
17150 FnDecl->getType()->castAs<FunctionProtoType>()->isVariadic()) {
17151 return Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_operator_overload_variadic)
17152 << FnDecl->getDeclName();
17153 }
17154
17155 // Some operators must be member functions.
17156 if (MustBeMemberOperator && !isa<CXXMethodDecl>(Val: FnDecl)) {
17157 return Diag(Loc: FnDecl->getLocation(),
17158 DiagID: diag::err_operator_overload_must_be_member)
17159 << FnDecl->getDeclName();
17160 }
17161
17162 // C++ [over.inc]p1:
17163 // The user-defined function called operator++ implements the
17164 // prefix and postfix ++ operator. If this function is a member
17165 // function with no parameters, or a non-member function with one
17166 // parameter of class or enumeration type, it defines the prefix
17167 // increment operator ++ for objects of that type. If the function
17168 // is a member function with one parameter (which shall be of type
17169 // int) or a non-member function with two parameters (the second
17170 // of which shall be of type int), it defines the postfix
17171 // increment operator ++ for objects of that type.
17172 if ((Op == OO_PlusPlus || Op == OO_MinusMinus) && NumParams == 2) {
17173 ParmVarDecl *LastParam = FnDecl->getParamDecl(i: FnDecl->getNumParams() - 1);
17174 QualType ParamType = LastParam->getType();
17175
17176 if (!ParamType->isSpecificBuiltinType(K: BuiltinType::Int) &&
17177 !ParamType->isDependentType())
17178 return Diag(Loc: LastParam->getLocation(),
17179 DiagID: diag::err_operator_overload_post_incdec_must_be_int)
17180 << LastParam->getType() << (Op == OO_MinusMinus);
17181 }
17182
17183 return false;
17184}
17185
17186static bool
17187checkLiteralOperatorTemplateParameterList(Sema &SemaRef,
17188 FunctionTemplateDecl *TpDecl) {
17189 TemplateParameterList *TemplateParams = TpDecl->getTemplateParameters();
17190
17191 // Must have one or two template parameters.
17192 if (TemplateParams->size() == 1) {
17193 NonTypeTemplateParmDecl *PmDecl =
17194 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17195
17196 // The template parameter must be a char parameter pack.
17197 if (PmDecl && PmDecl->isTemplateParameterPack() &&
17198 SemaRef.Context.hasSameType(T1: PmDecl->getType(), T2: SemaRef.Context.CharTy))
17199 return false;
17200
17201 // C++20 [over.literal]p5:
17202 // A string literal operator template is a literal operator template
17203 // whose template-parameter-list comprises a single non-type
17204 // template-parameter of class type.
17205 //
17206 // As a DR resolution, we also allow placeholders for deduced class
17207 // template specializations.
17208 if (SemaRef.getLangOpts().CPlusPlus20 && PmDecl &&
17209 !PmDecl->isTemplateParameterPack() &&
17210 (PmDecl->getType()->isRecordType() ||
17211 PmDecl->getType()->getAs<DeducedTemplateSpecializationType>()))
17212 return false;
17213 } else if (TemplateParams->size() == 2) {
17214 TemplateTypeParmDecl *PmType =
17215 dyn_cast<TemplateTypeParmDecl>(Val: TemplateParams->getParam(Idx: 0));
17216 NonTypeTemplateParmDecl *PmArgs =
17217 dyn_cast<NonTypeTemplateParmDecl>(Val: TemplateParams->getParam(Idx: 1));
17218
17219 // The second template parameter must be a parameter pack with the
17220 // first template parameter as its type.
17221 if (PmType && PmArgs && !PmType->isTemplateParameterPack() &&
17222 PmArgs->isTemplateParameterPack()) {
17223 if (const auto *TArgs =
17224 PmArgs->getType()->getAsCanonical<TemplateTypeParmType>();
17225 TArgs && TArgs->getDepth() == PmType->getDepth() &&
17226 TArgs->getIndex() == PmType->getIndex()) {
17227 if (!SemaRef.inTemplateInstantiation())
17228 SemaRef.Diag(Loc: TpDecl->getLocation(),
17229 DiagID: diag::ext_string_literal_operator_template);
17230 return false;
17231 }
17232 }
17233 }
17234
17235 SemaRef.Diag(Loc: TpDecl->getTemplateParameters()->getSourceRange().getBegin(),
17236 DiagID: diag::err_literal_operator_template)
17237 << TpDecl->getTemplateParameters()->getSourceRange();
17238 return true;
17239}
17240
17241bool Sema::CheckLiteralOperatorDeclaration(FunctionDecl *FnDecl) {
17242 if (isa<CXXMethodDecl>(Val: FnDecl)) {
17243 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_outside_namespace)
17244 << FnDecl->getDeclName();
17245 return true;
17246 }
17247
17248 if (FnDecl->isExternC()) {
17249 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_extern_c);
17250 if (const LinkageSpecDecl *LSD =
17251 FnDecl->getDeclContext()->getExternCContext())
17252 Diag(Loc: LSD->getExternLoc(), DiagID: diag::note_extern_c_begins_here);
17253 return true;
17254 }
17255
17256 // This might be the definition of a literal operator template.
17257 FunctionTemplateDecl *TpDecl = FnDecl->getDescribedFunctionTemplate();
17258
17259 // This might be a specialization of a literal operator template.
17260 if (!TpDecl)
17261 TpDecl = FnDecl->getPrimaryTemplate();
17262
17263 // template <char...> type operator "" name() and
17264 // template <class T, T...> type operator "" name() are the only valid
17265 // template signatures, and the only valid signatures with no parameters.
17266 //
17267 // C++20 also allows template <SomeClass T> type operator "" name().
17268 if (TpDecl) {
17269 if (FnDecl->param_size() != 0) {
17270 Diag(Loc: FnDecl->getLocation(),
17271 DiagID: diag::err_literal_operator_template_with_params);
17272 return true;
17273 }
17274
17275 if (checkLiteralOperatorTemplateParameterList(SemaRef&: *this, TpDecl))
17276 return true;
17277
17278 } else if (FnDecl->param_size() == 1) {
17279 const ParmVarDecl *Param = FnDecl->getParamDecl(i: 0);
17280
17281 QualType ParamType = Param->getType().getUnqualifiedType();
17282
17283 // Only unsigned long long int, long double, any character type, and const
17284 // char * are allowed as the only parameters.
17285 if (ParamType->isSpecificBuiltinType(K: BuiltinType::ULongLong) ||
17286 ParamType->isSpecificBuiltinType(K: BuiltinType::LongDouble) ||
17287 Context.hasSameType(T1: ParamType, T2: Context.CharTy) ||
17288 Context.hasSameType(T1: ParamType, T2: Context.WideCharTy) ||
17289 Context.hasSameType(T1: ParamType, T2: Context.Char8Ty) ||
17290 Context.hasSameType(T1: ParamType, T2: Context.Char16Ty) ||
17291 Context.hasSameType(T1: ParamType, T2: Context.Char32Ty)) {
17292 } else if (const PointerType *Ptr = ParamType->getAs<PointerType>()) {
17293 QualType InnerType = Ptr->getPointeeType();
17294
17295 // Pointer parameter must be a const char *.
17296 if (!(Context.hasSameType(T1: InnerType.getUnqualifiedType(),
17297 T2: Context.CharTy) &&
17298 InnerType.isConstQualified() && !InnerType.isVolatileQualified())) {
17299 Diag(Loc: Param->getSourceRange().getBegin(),
17300 DiagID: diag::err_literal_operator_param)
17301 << ParamType << "'const char *'" << Param->getSourceRange();
17302 return true;
17303 }
17304
17305 } else if (ParamType->isRealFloatingType()) {
17306 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17307 << ParamType << Context.LongDoubleTy << Param->getSourceRange();
17308 return true;
17309
17310 } else if (ParamType->isIntegerType()) {
17311 Diag(Loc: Param->getSourceRange().getBegin(), DiagID: diag::err_literal_operator_param)
17312 << ParamType << Context.UnsignedLongLongTy << Param->getSourceRange();
17313 return true;
17314
17315 } else {
17316 Diag(Loc: Param->getSourceRange().getBegin(),
17317 DiagID: diag::err_literal_operator_invalid_param)
17318 << ParamType << Param->getSourceRange();
17319 return true;
17320 }
17321
17322 } else if (FnDecl->param_size() == 2) {
17323 FunctionDecl::param_iterator Param = FnDecl->param_begin();
17324
17325 // First, verify that the first parameter is correct.
17326
17327 QualType FirstParamType = (*Param)->getType().getUnqualifiedType();
17328
17329 // Two parameter function must have a pointer to const as a
17330 // first parameter; let's strip those qualifiers.
17331 const PointerType *PT = FirstParamType->getAs<PointerType>();
17332
17333 if (!PT) {
17334 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17335 DiagID: diag::err_literal_operator_param)
17336 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17337 return true;
17338 }
17339
17340 QualType PointeeType = PT->getPointeeType();
17341 // First parameter must be const
17342 if (!PointeeType.isConstQualified() || PointeeType.isVolatileQualified()) {
17343 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17344 DiagID: diag::err_literal_operator_param)
17345 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17346 return true;
17347 }
17348
17349 QualType InnerType = PointeeType.getUnqualifiedType();
17350 // Only const char *, const wchar_t*, const char8_t*, const char16_t*, and
17351 // const char32_t* are allowed as the first parameter to a two-parameter
17352 // function
17353 if (!(Context.hasSameType(T1: InnerType, T2: Context.CharTy) ||
17354 Context.hasSameType(T1: InnerType, T2: Context.WideCharTy) ||
17355 Context.hasSameType(T1: InnerType, T2: Context.Char8Ty) ||
17356 Context.hasSameType(T1: InnerType, T2: Context.Char16Ty) ||
17357 Context.hasSameType(T1: InnerType, T2: Context.Char32Ty))) {
17358 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17359 DiagID: diag::err_literal_operator_param)
17360 << FirstParamType << "'const char *'" << (*Param)->getSourceRange();
17361 return true;
17362 }
17363
17364 // Move on to the second and final parameter.
17365 ++Param;
17366
17367 // The second parameter must be a std::size_t.
17368 QualType SecondParamType = (*Param)->getType().getUnqualifiedType();
17369 if (!Context.hasSameType(T1: SecondParamType, T2: Context.getSizeType())) {
17370 Diag(Loc: (*Param)->getSourceRange().getBegin(),
17371 DiagID: diag::err_literal_operator_param)
17372 << SecondParamType << Context.getSizeType()
17373 << (*Param)->getSourceRange();
17374 return true;
17375 }
17376 } else {
17377 Diag(Loc: FnDecl->getLocation(), DiagID: diag::err_literal_operator_bad_param_count);
17378 return true;
17379 }
17380
17381 // Parameters are good.
17382
17383 // A parameter-declaration-clause containing a default argument is not
17384 // equivalent to any of the permitted forms.
17385 for (auto *Param : FnDecl->parameters()) {
17386 if (Param->hasDefaultArg()) {
17387 Diag(Loc: Param->getDefaultArgRange().getBegin(),
17388 DiagID: diag::err_literal_operator_default_argument)
17389 << Param->getDefaultArgRange();
17390 break;
17391 }
17392 }
17393
17394 const IdentifierInfo *II = FnDecl->getDeclName().getCXXLiteralIdentifier();
17395 ReservedLiteralSuffixIdStatus Status = II->isReservedLiteralSuffixId();
17396 if (Status != ReservedLiteralSuffixIdStatus::NotReserved &&
17397 !getSourceManager().isInSystemHeader(Loc: FnDecl->getLocation())) {
17398 // C++23 [usrlit.suffix]p1:
17399 // Literal suffix identifiers that do not start with an underscore are
17400 // reserved for future standardization. Literal suffix identifiers that
17401 // contain a double underscore __ are reserved for use by C++
17402 // implementations.
17403 Diag(Loc: FnDecl->getLocation(), DiagID: diag::warn_user_literal_reserved)
17404 << static_cast<int>(Status)
17405 << StringLiteralParser::isValidUDSuffix(LangOpts: getLangOpts(), Suffix: II->getName());
17406 }
17407
17408 return false;
17409}
17410
17411Decl *Sema::ActOnStartLinkageSpecification(Scope *S, SourceLocation ExternLoc,
17412 Expr *LangStr,
17413 SourceLocation LBraceLoc) {
17414 StringLiteral *Lit = cast<StringLiteral>(Val: LangStr);
17415 assert(Lit->isUnevaluated() && "Unexpected string literal kind");
17416
17417 StringRef Lang = Lit->getString();
17418 LinkageSpecLanguageIDs Language;
17419 if (Lang == "C")
17420 Language = LinkageSpecLanguageIDs::C;
17421 else if (Lang == "C++")
17422 Language = LinkageSpecLanguageIDs::CXX;
17423 else {
17424 Diag(Loc: LangStr->getExprLoc(), DiagID: diag::err_language_linkage_spec_unknown)
17425 << LangStr->getSourceRange();
17426 return nullptr;
17427 }
17428
17429 // FIXME: Add all the various semantics of linkage specifications
17430
17431 LinkageSpecDecl *D = LinkageSpecDecl::Create(C&: Context, DC: CurContext, ExternLoc,
17432 LangLoc: LangStr->getExprLoc(), Lang: Language,
17433 HasBraces: LBraceLoc.isValid());
17434
17435 /// C++ [module.unit]p7.2.3
17436 /// - Otherwise, if the declaration
17437 /// - ...
17438 /// - ...
17439 /// - appears within a linkage-specification,
17440 /// it is attached to the global module.
17441 ///
17442 /// If the declaration is already in global module fragment, we don't
17443 /// need to attach it again.
17444 if (getLangOpts().CPlusPlusModules && isCurrentModulePurview()) {
17445 Module *GlobalModule = PushImplicitGlobalModuleFragment(BeginLoc: ExternLoc);
17446 D->setLocalOwningModule(GlobalModule);
17447 }
17448
17449 CurContext->addDecl(D);
17450 PushDeclContext(S, DC: D);
17451 return D;
17452}
17453
17454Decl *Sema::ActOnFinishLinkageSpecification(Scope *S,
17455 Decl *LinkageSpec,
17456 SourceLocation RBraceLoc) {
17457 if (RBraceLoc.isValid()) {
17458 LinkageSpecDecl* LSDecl = cast<LinkageSpecDecl>(Val: LinkageSpec);
17459 LSDecl->setRBraceLoc(RBraceLoc);
17460 }
17461
17462 // If the current module doesn't has Parent, it implies that the
17463 // LinkageSpec isn't in the module created by itself. So we don't
17464 // need to pop it.
17465 if (getLangOpts().CPlusPlusModules && getCurrentModule() &&
17466 getCurrentModule()->isImplicitGlobalModule() &&
17467 getCurrentModule()->Parent)
17468 PopImplicitGlobalModuleFragment();
17469
17470 PopDeclContext();
17471 return LinkageSpec;
17472}
17473
17474Decl *Sema::ActOnEmptyDeclaration(Scope *S,
17475 const ParsedAttributesView &AttrList,
17476 SourceLocation SemiLoc) {
17477 Decl *ED = EmptyDecl::Create(C&: Context, DC: CurContext, L: SemiLoc);
17478 // Attribute declarations appertain to empty declaration so we handle
17479 // them here.
17480 ProcessDeclAttributeList(S, D: ED, AttrList);
17481
17482 CurContext->addDecl(D: ED);
17483 return ED;
17484}
17485
17486VarDecl *Sema::BuildExceptionDeclaration(Scope *S, TypeSourceInfo *TInfo,
17487 SourceLocation StartLoc,
17488 SourceLocation Loc,
17489 const IdentifierInfo *Name) {
17490 bool Invalid = false;
17491 QualType ExDeclType = TInfo->getType();
17492
17493 // Arrays and functions decay.
17494 if (ExDeclType->isArrayType())
17495 ExDeclType = Context.getArrayDecayedType(T: ExDeclType);
17496 else if (ExDeclType->isFunctionType())
17497 ExDeclType = Context.getPointerType(T: ExDeclType);
17498
17499 // C++ 15.3p1: The exception-declaration shall not denote an incomplete type.
17500 // The exception-declaration shall not denote a pointer or reference to an
17501 // incomplete type, other than [cv] void*.
17502 // N2844 forbids rvalue references.
17503 if (!ExDeclType->isDependentType() && ExDeclType->isRValueReferenceType()) {
17504 Diag(Loc, DiagID: diag::err_catch_rvalue_ref);
17505 Invalid = true;
17506 }
17507
17508 if (ExDeclType->isVariablyModifiedType()) {
17509 Diag(Loc, DiagID: diag::err_catch_variably_modified) << ExDeclType;
17510 Invalid = true;
17511 }
17512
17513 QualType BaseType = ExDeclType;
17514 int Mode = 0; // 0 for direct type, 1 for pointer, 2 for reference
17515 unsigned DK = diag::err_catch_incomplete;
17516 if (const PointerType *Ptr = BaseType->getAs<PointerType>()) {
17517 BaseType = Ptr->getPointeeType();
17518 Mode = 1;
17519 DK = diag::err_catch_incomplete_ptr;
17520 } else if (const ReferenceType *Ref = BaseType->getAs<ReferenceType>()) {
17521 // For the purpose of error recovery, we treat rvalue refs like lvalue refs.
17522 BaseType = Ref->getPointeeType();
17523 Mode = 2;
17524 DK = diag::err_catch_incomplete_ref;
17525 }
17526 if (!Invalid && (Mode == 0 || !BaseType->isVoidType()) &&
17527 !BaseType->isDependentType() && RequireCompleteType(Loc, T: BaseType, DiagID: DK))
17528 Invalid = true;
17529
17530 if (!Invalid && BaseType.isWebAssemblyReferenceType()) {
17531 Diag(Loc, DiagID: diag::err_wasm_reftype_tc) << 1;
17532 Invalid = true;
17533 }
17534
17535 // Reject catch types that need a cross-AS conversion.
17536 // cause runtimes don't yet support cross-address-
17537 // space conversions
17538 if (Mode == 1) {
17539 if (ExDeclType.getAddressSpace() != LangAS::Default ||
17540 BaseType.getAddressSpace() != LangAS::Default) {
17541 Diag(Loc, DiagID: diag::err_throw_or_catch_address_space_qualified_ptr)
17542 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
17543 Invalid = true;
17544 }
17545 } else if (Mode == 2) {
17546 if (const PointerType *PT = BaseType->getAs<PointerType>();
17547 PT && (BaseType.getAddressSpace() != LangAS::Default ||
17548 PT->getPointeeType().getAddressSpace() != LangAS::Default)) {
17549 Diag(Loc, DiagID: diag::err_throw_or_catch_address_space_qualified_ptr)
17550 << /*IsCatch=*/1 << /*IsRef=*/0 << ExDeclType;
17551 Invalid = true;
17552 } else if (BaseType.getAddressSpace() != LangAS::Default) {
17553 Diag(Loc, DiagID: diag::err_throw_or_catch_address_space_qualified_ptr)
17554 << /*IsCatch=*/1 << /*IsRef=*/1 << ExDeclType;
17555 Invalid = true;
17556 }
17557 }
17558
17559 if (!Invalid && Mode != 1 && BaseType->isSizelessType()) {
17560 Diag(Loc, DiagID: diag::err_catch_sizeless) << (Mode == 2 ? 1 : 0) << BaseType;
17561 Invalid = true;
17562 }
17563
17564 if (!Invalid && !ExDeclType->isDependentType() &&
17565 RequireNonAbstractType(Loc, T: ExDeclType,
17566 DiagID: diag::err_abstract_type_in_decl,
17567 Args: AbstractVariableType))
17568 Invalid = true;
17569
17570 // Only the non-fragile NeXT runtime currently supports C++ catches
17571 // of ObjC types, and no runtime supports catching ObjC types by value.
17572 if (!Invalid && getLangOpts().ObjC) {
17573 QualType T = ExDeclType;
17574 if (const ReferenceType *RT = T->getAs<ReferenceType>())
17575 T = RT->getPointeeType();
17576
17577 if (T->isObjCObjectType()) {
17578 Diag(Loc, DiagID: diag::err_objc_object_catch);
17579 Invalid = true;
17580 } else if (T->isObjCObjectPointerType()) {
17581 // FIXME: should this be a test for macosx-fragile specifically?
17582 if (getLangOpts().ObjCRuntime.isFragile())
17583 Diag(Loc, DiagID: diag::warn_objc_pointer_cxx_catch_fragile);
17584 }
17585 }
17586
17587 VarDecl *ExDecl = VarDecl::Create(C&: Context, DC: CurContext, StartLoc, IdLoc: Loc, Id: Name,
17588 T: ExDeclType, TInfo, S: SC_None);
17589 ExDecl->setExceptionVariable(true);
17590
17591 // In ARC, infer 'retaining' for variables of retainable type.
17592 if (getLangOpts().ObjCAutoRefCount && ObjC().inferObjCARCLifetime(decl: ExDecl))
17593 Invalid = true;
17594
17595 if (!Invalid && !ExDeclType->isDependentType()) {
17596 if (auto *ClassDecl = ExDeclType->getAsCXXRecordDecl()) {
17597 // Insulate this from anything else we might currently be parsing.
17598 EnterExpressionEvaluationContext scope(
17599 *this, ExpressionEvaluationContext::PotentiallyEvaluated);
17600
17601 // C++ [except.handle]p16:
17602 // The object declared in an exception-declaration or, if the
17603 // exception-declaration does not specify a name, a temporary (12.2) is
17604 // copy-initialized (8.5) from the exception object. [...]
17605 // The object is destroyed when the handler exits, after the destruction
17606 // of any automatic objects initialized within the handler.
17607 //
17608 // We just pretend to initialize the object with itself, then make sure
17609 // it can be destroyed later.
17610 QualType initType = Context.getExceptionObjectType(T: ExDeclType);
17611
17612 InitializedEntity entity =
17613 InitializedEntity::InitializeVariable(Var: ExDecl);
17614 InitializationKind initKind =
17615 InitializationKind::CreateCopy(InitLoc: Loc, EqualLoc: SourceLocation());
17616
17617 Expr *opaqueValue =
17618 new (Context) OpaqueValueExpr(Loc, initType, VK_LValue, OK_Ordinary);
17619 InitializationSequence sequence(*this, entity, initKind, opaqueValue);
17620 ExprResult result = sequence.Perform(S&: *this, Entity: entity, Kind: initKind, Args: opaqueValue);
17621 if (result.isInvalid())
17622 Invalid = true;
17623 else {
17624 // If the constructor used was non-trivial, set this as the
17625 // "initializer".
17626 CXXConstructExpr *construct = result.getAs<CXXConstructExpr>();
17627 if (!construct->getConstructor()->isTrivial()) {
17628 Expr *init = MaybeCreateExprWithCleanups(SubExpr: construct);
17629 ExDecl->setInit(init);
17630 }
17631
17632 // And make sure it's destructable.
17633 FinalizeVarWithDestructor(VD: ExDecl, ClassDecl);
17634 }
17635 }
17636 }
17637
17638 if (Invalid)
17639 ExDecl->setInvalidDecl();
17640
17641 return ExDecl;
17642}
17643
17644Decl *Sema::ActOnExceptionDeclarator(Scope *S, Declarator &D) {
17645 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
17646 bool Invalid = D.isInvalidType();
17647
17648 // Check for unexpanded parameter packs.
17649 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
17650 UPPC: UPPC_ExceptionType)) {
17651 TInfo = Context.getTrivialTypeSourceInfo(T: Context.IntTy,
17652 Loc: D.getIdentifierLoc());
17653 Invalid = true;
17654 }
17655
17656 const IdentifierInfo *II = D.getIdentifier();
17657 if (NamedDecl *PrevDecl =
17658 LookupSingleName(S, Name: II, Loc: D.getIdentifierLoc(), NameKind: LookupOrdinaryName,
17659 Redecl: RedeclarationKind::ForVisibleRedeclaration)) {
17660 // The scope should be freshly made just for us. There is just no way
17661 // it contains any previous declaration, except for function parameters in
17662 // a function-try-block's catch statement.
17663 assert(!S->isDeclScope(PrevDecl));
17664 if (isDeclInScope(D: PrevDecl, Ctx: CurContext, S)) {
17665 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_redefinition)
17666 << D.getIdentifier();
17667 Diag(Loc: PrevDecl->getLocation(), DiagID: diag::note_previous_definition);
17668 Invalid = true;
17669 } else if (PrevDecl->isTemplateParameter())
17670 // Maybe we will complain about the shadowed template parameter.
17671 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
17672 }
17673
17674 if (D.getCXXScopeSpec().isSet() && !Invalid) {
17675 Diag(Loc: D.getIdentifierLoc(), DiagID: diag::err_qualified_catch_declarator)
17676 << D.getCXXScopeSpec().getRange();
17677 Invalid = true;
17678 }
17679
17680 VarDecl *ExDecl = BuildExceptionDeclaration(
17681 S, TInfo, StartLoc: D.getBeginLoc(), Loc: D.getIdentifierLoc(), Name: D.getIdentifier());
17682 if (Invalid)
17683 ExDecl->setInvalidDecl();
17684
17685 // Add the exception declaration into this scope.
17686 if (II)
17687 PushOnScopeChains(D: ExDecl, S);
17688 else
17689 CurContext->addDecl(D: ExDecl);
17690
17691 ProcessDeclAttributes(S, D: ExDecl, PD: D);
17692 return ExDecl;
17693}
17694
17695Decl *Sema::ActOnStaticAssertDeclaration(SourceLocation StaticAssertLoc,
17696 Expr *AssertExpr,
17697 Expr *AssertMessageExpr,
17698 SourceLocation RParenLoc) {
17699 if (DiagnoseUnexpandedParameterPack(E: AssertExpr, UPPC: UPPC_StaticAssertExpression))
17700 return nullptr;
17701
17702 return BuildStaticAssertDeclaration(StaticAssertLoc, AssertExpr,
17703 AssertMessageExpr, RParenLoc, Failed: false);
17704}
17705
17706static void WriteCharTypePrefix(BuiltinType::Kind BTK, llvm::raw_ostream &OS) {
17707 switch (BTK) {
17708 case BuiltinType::Char_S:
17709 case BuiltinType::Char_U:
17710 break;
17711 case BuiltinType::Char8:
17712 OS << "u8";
17713 break;
17714 case BuiltinType::Char16:
17715 OS << 'u';
17716 break;
17717 case BuiltinType::Char32:
17718 OS << 'U';
17719 break;
17720 case BuiltinType::WChar_S:
17721 case BuiltinType::WChar_U:
17722 OS << 'L';
17723 break;
17724 default:
17725 llvm_unreachable("Non-character type");
17726 }
17727}
17728
17729/// Convert character's value, interpreted as a code unit, to a string.
17730/// The value needs to be zero-extended to 32-bits.
17731/// FIXME: This assumes Unicode literal encodings
17732static void WriteCharValueForDiagnostic(uint32_t Value, const BuiltinType *BTy,
17733 unsigned TyWidth,
17734 SmallVectorImpl<char> &Str) {
17735 char Arr[UNI_MAX_UTF8_BYTES_PER_CODE_POINT];
17736 char *Ptr = Arr;
17737 BuiltinType::Kind K = BTy->getKind();
17738 llvm::raw_svector_ostream OS(Str);
17739
17740 // This should catch Char_S, Char_U, Char8, and use of escaped characters in
17741 // other types.
17742 if (K == BuiltinType::Char_S || K == BuiltinType::Char_U ||
17743 K == BuiltinType::Char8 || Value <= 0x7F) {
17744 StringRef Escaped = escapeCStyle<EscapeChar::Single>(Ch: Value);
17745 if (!Escaped.empty())
17746 EscapeStringForDiagnostic(Str: Escaped, OutStr&: Str);
17747 else
17748 OS << static_cast<char>(Value);
17749 return;
17750 }
17751
17752 switch (K) {
17753 case BuiltinType::Char16:
17754 case BuiltinType::Char32:
17755 case BuiltinType::WChar_S:
17756 case BuiltinType::WChar_U: {
17757 if (llvm::ConvertCodePointToUTF8(Source: Value, ResultPtr&: Ptr))
17758 EscapeStringForDiagnostic(Str: StringRef(Arr, Ptr - Arr), OutStr&: Str);
17759 else
17760 OS << "\\x"
17761 << llvm::format_hex_no_prefix(N: Value, Width: TyWidth / 4, /*Upper=*/true);
17762 break;
17763 }
17764 default:
17765 llvm_unreachable("Non-character type is passed");
17766 }
17767}
17768
17769/// Convert \V to a string we can present to the user in a diagnostic
17770/// \T is the type of the expression that has been evaluated into \V
17771static bool ConvertAPValueToString(const APValue &V, QualType T,
17772 SmallVectorImpl<char> &Str,
17773 ASTContext &Context) {
17774 if (!V.hasValue())
17775 return false;
17776
17777 switch (V.getKind()) {
17778 case APValue::ValueKind::Int:
17779 if (T->isBooleanType()) {
17780 // Bools are reduced to ints during evaluation, but for
17781 // diagnostic purposes we want to print them as
17782 // true or false.
17783 int64_t BoolValue = V.getInt().getExtValue();
17784 assert((BoolValue == 0 || BoolValue == 1) &&
17785 "Bool type, but value is not 0 or 1");
17786 llvm::raw_svector_ostream OS(Str);
17787 OS << (BoolValue ? "true" : "false");
17788 } else {
17789 llvm::raw_svector_ostream OS(Str);
17790 // Same is true for chars.
17791 // We want to print the character representation for textual types
17792 const auto *BTy = T->getAs<BuiltinType>();
17793 if (BTy) {
17794 switch (BTy->getKind()) {
17795 case BuiltinType::Char_S:
17796 case BuiltinType::Char_U:
17797 case BuiltinType::Char8:
17798 case BuiltinType::Char16:
17799 case BuiltinType::Char32:
17800 case BuiltinType::WChar_S:
17801 case BuiltinType::WChar_U: {
17802 unsigned TyWidth = Context.getIntWidth(T);
17803 assert(8 <= TyWidth && TyWidth <= 32 && "Unexpected integer width");
17804 uint32_t CodeUnit = static_cast<uint32_t>(V.getInt().getZExtValue());
17805 WriteCharTypePrefix(BTK: BTy->getKind(), OS);
17806 OS << '\'';
17807 WriteCharValueForDiagnostic(Value: CodeUnit, BTy, TyWidth, Str);
17808 OS << "' (0x"
17809 << llvm::format_hex_no_prefix(N: CodeUnit, /*Width=*/2,
17810 /*Upper=*/true)
17811 << ", " << V.getInt() << ')';
17812 return true;
17813 }
17814 default:
17815 break;
17816 }
17817 }
17818 V.getInt().toString(Str);
17819 }
17820
17821 break;
17822
17823 case APValue::ValueKind::Float:
17824 V.getFloat().toString(Str);
17825 break;
17826
17827 case APValue::ValueKind::LValue:
17828 if (V.isNullPointer()) {
17829 llvm::raw_svector_ostream OS(Str);
17830 OS << "nullptr";
17831 } else
17832 return false;
17833 break;
17834
17835 case APValue::ValueKind::ComplexFloat: {
17836 llvm::raw_svector_ostream OS(Str);
17837 OS << '(';
17838 V.getComplexFloatReal().toString(Str);
17839 OS << " + ";
17840 V.getComplexFloatImag().toString(Str);
17841 OS << "i)";
17842 } break;
17843
17844 case APValue::ValueKind::ComplexInt: {
17845 llvm::raw_svector_ostream OS(Str);
17846 OS << '(';
17847 V.getComplexIntReal().toString(Str);
17848 OS << " + ";
17849 V.getComplexIntImag().toString(Str);
17850 OS << "i)";
17851 } break;
17852
17853 default:
17854 return false;
17855 }
17856
17857 return true;
17858}
17859
17860/// Some Expression types are not useful to print notes about,
17861/// e.g. literals and values that have already been expanded
17862/// before such as int-valued template parameters.
17863static bool UsefulToPrintExpr(const Expr *E) {
17864 E = E->IgnoreParenImpCasts();
17865 // Literals are pretty easy for humans to understand.
17866 if (isa<IntegerLiteral, FloatingLiteral, CharacterLiteral, CXXBoolLiteralExpr,
17867 CXXNullPtrLiteralExpr, FixedPointLiteral, ImaginaryLiteral>(Val: E))
17868 return false;
17869
17870 // These have been substituted from template parameters
17871 // and appear as literals in the static assert error.
17872 if (isa<SubstNonTypeTemplateParmExpr>(Val: E))
17873 return false;
17874
17875 // -5 is also simple to understand.
17876 if (const auto *UnaryOp = dyn_cast<UnaryOperator>(Val: E))
17877 return UsefulToPrintExpr(E: UnaryOp->getSubExpr());
17878
17879 // Only print nested arithmetic operators.
17880 if (const auto *BO = dyn_cast<BinaryOperator>(Val: E))
17881 return (BO->isShiftOp() || BO->isAdditiveOp() || BO->isMultiplicativeOp() ||
17882 BO->isBitwiseOp());
17883
17884 return true;
17885}
17886
17887void Sema::DiagnoseStaticAssertDetails(const Expr *E) {
17888 // FIXME: Should we also ignore explicit casts?
17889 E = E->IgnoreParenImpCasts();
17890 if (const auto *Op = dyn_cast<BinaryOperator>(Val: E);
17891 Op && Op->getOpcode() != BO_LOr) {
17892 const Expr *LHS = Op->getLHS()->IgnoreParenImpCasts();
17893 const Expr *RHS = Op->getRHS()->IgnoreParenImpCasts();
17894
17895 // Ignore comparisons of boolean expressions with a boolean literal.
17896 if ((isa<CXXBoolLiteralExpr>(Val: LHS) && RHS->getType()->isBooleanType()) ||
17897 (isa<CXXBoolLiteralExpr>(Val: RHS) && LHS->getType()->isBooleanType()))
17898 return;
17899
17900 // Don't print obvious expressions.
17901 if (!UsefulToPrintExpr(E: LHS) && !UsefulToPrintExpr(E: RHS))
17902 return;
17903
17904 struct {
17905 const clang::Expr *Cond;
17906 Expr::EvalResult Result;
17907 SmallString<12> ValueString;
17908 bool Print;
17909 } DiagSides[2] = {{.Cond: LHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false},
17910 {.Cond: RHS, .Result: Expr::EvalResult(), .ValueString: {}, .Print: false}};
17911 for (auto &DiagSide : DiagSides) {
17912 const Expr *Side = DiagSide.Cond;
17913
17914 Side->EvaluateAsRValue(Result&: DiagSide.Result, Ctx: Context, InConstantContext: true);
17915
17916 DiagSide.Print = ConvertAPValueToString(
17917 V: DiagSide.Result.Val, T: Side->getType(), Str&: DiagSide.ValueString, Context);
17918 }
17919 if (DiagSides[0].Print && DiagSides[1].Print) {
17920 Diag(Loc: Op->getExprLoc(), DiagID: diag::note_expr_evaluates_to)
17921 << DiagSides[0].ValueString << Op->getOpcodeStr()
17922 << DiagSides[1].ValueString << Op->getSourceRange();
17923 }
17924 } else if (const auto *RE = dyn_cast<RequiresExpr>(Val: E)) {
17925 DiagnoseUnsatisfiedRequiresExpr(RequiresExpr: RE);
17926 } else {
17927 DiagnoseTypeTraitDetails(E);
17928 }
17929}
17930
17931template <typename ResultType>
17932static bool EvaluateAsStringImpl(Sema &SemaRef, Expr *Message,
17933 ResultType &Result, ASTContext &Ctx,
17934 Sema::StringEvaluationContext EvalContext,
17935 bool ErrorOnInvalidMessage) {
17936
17937 assert(Message);
17938 assert(!Message->isTypeDependent() && !Message->isValueDependent() &&
17939 "can't evaluate a dependant static assert message");
17940
17941 if (const auto *SL = dyn_cast<StringLiteral>(Val: Message)) {
17942 assert(SL->isUnevaluated() && "expected an unevaluated string");
17943 if constexpr (std::is_same_v<APValue, ResultType>) {
17944 Result =
17945 APValue(APValue::UninitArray{}, SL->getLength(), SL->getLength());
17946 const ConstantArrayType *CAT =
17947 SemaRef.getASTContext().getAsConstantArrayType(T: SL->getType());
17948 assert(CAT && "string literal isn't an array");
17949 QualType CharType = CAT->getElementType();
17950 llvm::APSInt Value(SemaRef.getASTContext().getTypeSize(T: CharType),
17951 CharType->isUnsignedIntegerType());
17952 for (unsigned I = 0; I < SL->getLength(); I++) {
17953 Value = SL->getCodeUnit(I);
17954 Result.getArrayInitializedElt(I) = APValue(Value);
17955 }
17956 } else {
17957 Result.assign(SL->getString().begin(), SL->getString().end());
17958 }
17959 return true;
17960 }
17961
17962 SourceLocation Loc = Message->getBeginLoc();
17963 QualType T = Message->getType().getNonReferenceType();
17964 auto *RD = T->getAsCXXRecordDecl();
17965 if (!RD) {
17966 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid) << EvalContext;
17967 return false;
17968 }
17969
17970 auto FindMember = [&](StringRef Member) -> std::optional<LookupResult> {
17971 DeclarationName DN = SemaRef.PP.getIdentifierInfo(Name: Member);
17972 LookupResult MemberLookup(SemaRef, DN, Loc, Sema::LookupMemberName);
17973 SemaRef.LookupQualifiedName(R&: MemberLookup, LookupCtx: RD);
17974 OverloadCandidateSet Candidates(MemberLookup.getNameLoc(),
17975 OverloadCandidateSet::CSK_Normal);
17976 if (MemberLookup.empty())
17977 return std::nullopt;
17978 return std::move(MemberLookup);
17979 };
17980
17981 std::optional<LookupResult> SizeMember = FindMember("size");
17982 std::optional<LookupResult> DataMember = FindMember("data");
17983 if (!SizeMember || !DataMember) {
17984 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_missing_member_function)
17985 << EvalContext
17986 << ((!SizeMember && !DataMember) ? 2
17987 : !SizeMember ? 0
17988 : 1);
17989 return false;
17990 }
17991
17992 auto BuildExpr = [&](LookupResult &LR) {
17993 ExprResult Res = SemaRef.BuildMemberReferenceExpr(
17994 Base: Message, BaseType: Message->getType(), OpLoc: Message->getBeginLoc(), IsArrow: false,
17995 SS: CXXScopeSpec(), TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: LR, TemplateArgs: nullptr, S: nullptr);
17996 if (Res.isInvalid())
17997 return ExprError();
17998 Res = SemaRef.BuildCallExpr(S: nullptr, Fn: Res.get(), LParenLoc: Loc, ArgExprs: {}, RParenLoc: Loc, ExecConfig: nullptr,
17999 IsExecConfig: false, AllowRecovery: true);
18000 if (Res.isInvalid())
18001 return ExprError();
18002 if (Res.get()->isTypeDependent() || Res.get()->isValueDependent())
18003 return ExprError();
18004 return SemaRef.TemporaryMaterializationConversion(E: Res.get());
18005 };
18006
18007 ExprResult SizeE = BuildExpr(*SizeMember);
18008 ExprResult DataE = BuildExpr(*DataMember);
18009
18010 QualType SizeT = SemaRef.Context.getSizeType();
18011 QualType ConstCharPtr = SemaRef.Context.getPointerType(
18012 T: SemaRef.Context.getConstType(T: SemaRef.Context.CharTy));
18013
18014 ExprResult EvaluatedSize =
18015 SizeE.isInvalid()
18016 ? ExprError()
18017 : SemaRef.BuildConvertedConstantExpression(
18018 From: SizeE.get(), T: SizeT, CCE: CCEKind::StaticAssertMessageSize);
18019 if (EvaluatedSize.isInvalid()) {
18020 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18021 << EvalContext << /*size*/ 0;
18022 return false;
18023 }
18024
18025 ExprResult EvaluatedData =
18026 DataE.isInvalid()
18027 ? ExprError()
18028 : SemaRef.BuildConvertedConstantExpression(
18029 From: DataE.get(), T: ConstCharPtr, CCE: CCEKind::StaticAssertMessageData);
18030 if (EvaluatedData.isInvalid()) {
18031 SemaRef.Diag(Loc, DiagID: diag::err_user_defined_msg_invalid_mem_fn_ret_ty)
18032 << EvalContext << /*data*/ 1;
18033 return false;
18034 }
18035
18036 if (!ErrorOnInvalidMessage &&
18037 SemaRef.Diags.isIgnored(DiagID: diag::warn_user_defined_msg_constexpr, Loc))
18038 return true;
18039
18040 Expr::EvalResult Status;
18041 SmallVector<PartialDiagnosticAt, 8> Notes;
18042 Status.Diag = &Notes;
18043 if (!Message->EvaluateCharRangeAsString(Result, EvaluatedSize.get(),
18044 EvaluatedData.get(), Ctx, Status) ||
18045 !Notes.empty()) {
18046 SemaRef.Diag(Loc: Message->getBeginLoc(),
18047 DiagID: ErrorOnInvalidMessage ? diag::err_user_defined_msg_constexpr
18048 : diag::warn_user_defined_msg_constexpr)
18049 << EvalContext;
18050 for (const auto &Note : Notes)
18051 SemaRef.Diag(Loc: Note.first, PD: Note.second);
18052 return !ErrorOnInvalidMessage;
18053 }
18054 return true;
18055}
18056
18057bool Sema::EvaluateAsString(Expr *Message, APValue &Result, ASTContext &Ctx,
18058 StringEvaluationContext EvalContext,
18059 bool ErrorOnInvalidMessage) {
18060 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18061 ErrorOnInvalidMessage);
18062}
18063
18064bool Sema::EvaluateAsString(Expr *Message, std::string &Result, ASTContext &Ctx,
18065 StringEvaluationContext EvalContext,
18066 bool ErrorOnInvalidMessage) {
18067 return EvaluateAsStringImpl(SemaRef&: *this, Message, Result, Ctx, EvalContext,
18068 ErrorOnInvalidMessage);
18069}
18070
18071Decl *Sema::BuildStaticAssertDeclaration(SourceLocation StaticAssertLoc,
18072 Expr *AssertExpr, Expr *AssertMessage,
18073 SourceLocation RParenLoc,
18074 bool Failed) {
18075 assert(AssertExpr != nullptr && "Expected non-null condition");
18076 if (!AssertExpr->isTypeDependent() && !AssertExpr->isValueDependent() &&
18077 (!AssertMessage || (!AssertMessage->isTypeDependent() &&
18078 !AssertMessage->isValueDependent())) &&
18079 !Failed) {
18080 // In a static_assert-declaration, the constant-expression shall be a
18081 // constant expression that can be contextually converted to bool.
18082 ExprResult Converted = PerformContextuallyConvertToBool(From: AssertExpr);
18083 if (Converted.isInvalid())
18084 Failed = true;
18085
18086 ExprResult FullAssertExpr =
18087 ActOnFinishFullExpr(Expr: Converted.get(), CC: StaticAssertLoc,
18088 /*DiscardedValue*/ false,
18089 /*IsConstexpr*/ true);
18090 if (FullAssertExpr.isInvalid())
18091 Failed = true;
18092 else
18093 AssertExpr = FullAssertExpr.get();
18094
18095 llvm::APSInt Cond;
18096 Expr *BaseExpr = AssertExpr;
18097 AllowFoldKind FoldKind = AllowFoldKind::No;
18098
18099 if (!getLangOpts().CPlusPlus) {
18100 // In C mode, allow folding as an extension for better compatibility with
18101 // C++ in terms of expressions like static_assert("test") or
18102 // static_assert(nullptr).
18103 FoldKind = AllowFoldKind::Allow;
18104 }
18105
18106 if (!Failed && VerifyIntegerConstantExpression(
18107 E: BaseExpr, Result: &Cond,
18108 DiagID: diag::err_static_assert_expression_is_not_constant,
18109 CanFold: FoldKind).isInvalid())
18110 Failed = true;
18111
18112 // If the static_assert passes, only verify that
18113 // the message is grammatically valid without evaluating it.
18114 if (!Failed && AssertMessage && Cond.getBoolValue()) {
18115 std::string Str;
18116 EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18117 EvalContext: StringEvaluationContext::StaticAssert,
18118 /*ErrorOnInvalidMessage=*/false);
18119 }
18120
18121 // CWG2518
18122 // [dcl.pre]/p10 If [...] the expression is evaluated in the context of a
18123 // template definition, the declaration has no effect.
18124 bool InTemplateDefinition =
18125 getLangOpts().CPlusPlus && CurContext->isDependentContext();
18126
18127 if (!Failed && !Cond && !InTemplateDefinition) {
18128 SmallString<256> MsgBuffer;
18129 llvm::raw_svector_ostream Msg(MsgBuffer);
18130 bool HasMessage = AssertMessage;
18131 if (AssertMessage) {
18132 std::string Str;
18133 HasMessage = EvaluateAsString(Message: AssertMessage, Result&: Str, Ctx&: Context,
18134 EvalContext: StringEvaluationContext::StaticAssert,
18135 /*ErrorOnInvalidMessage=*/true) ||
18136 !Str.empty();
18137 Msg << Str;
18138 }
18139 Expr *InnerCond = nullptr;
18140 std::string InnerCondDescription;
18141 std::tie(args&: InnerCond, args&: InnerCondDescription) =
18142 findFailedBooleanCondition(Cond: Converted.get());
18143 if (const auto *ConceptIDExpr =
18144 dyn_cast_or_null<ConceptSpecializationExpr>(Val: InnerCond)) {
18145 const ASTConstraintSatisfaction &Satisfaction =
18146 ConceptIDExpr->getSatisfaction();
18147 if (!Satisfaction.ContainsErrors || Satisfaction.NumRecords) {
18148 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18149 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18150 // Drill down into concept specialization expressions to see why they
18151 // weren't satisfied.
18152 DiagnoseUnsatisfiedConstraint(ConstraintExpr: ConceptIDExpr);
18153 }
18154 } else if (InnerCond && !isa<CXXBoolLiteralExpr>(Val: InnerCond) &&
18155 !isa<IntegerLiteral>(Val: InnerCond)) {
18156 Diag(Loc: InnerCond->getBeginLoc(),
18157 DiagID: diag::err_static_assert_requirement_failed)
18158 << InnerCondDescription << !HasMessage << Msg.str()
18159 << InnerCond->getSourceRange();
18160 DiagnoseStaticAssertDetails(E: InnerCond);
18161 } else {
18162 Diag(Loc: AssertExpr->getBeginLoc(), DiagID: diag::err_static_assert_failed)
18163 << !HasMessage << Msg.str() << AssertExpr->getSourceRange();
18164 PrintContextStack();
18165 }
18166 Failed = true;
18167 }
18168 } else {
18169 ExprResult FullAssertExpr = ActOnFinishFullExpr(Expr: AssertExpr, CC: StaticAssertLoc,
18170 /*DiscardedValue*/false,
18171 /*IsConstexpr*/true);
18172 if (FullAssertExpr.isInvalid())
18173 Failed = true;
18174 else
18175 AssertExpr = FullAssertExpr.get();
18176 }
18177
18178 Decl *Decl = StaticAssertDecl::Create(C&: Context, DC: CurContext, StaticAssertLoc,
18179 AssertExpr, Message: AssertMessage, RParenLoc,
18180 Failed);
18181
18182 CurContext->addDecl(D: Decl);
18183 return Decl;
18184}
18185
18186static QualType IgnorePackIndexing(QualType T) {
18187 if (const auto *PIT = dyn_cast<PackIndexingType>(Val&: T))
18188 return PIT->getPattern();
18189 return T;
18190}
18191
18192static const TemplateSpecializationType *
18193GetClassTemplateSpecializationType(ASTContext &Context, QualType T) {
18194 T = IgnorePackIndexing(T);
18195 if (const auto *ICNT = dyn_cast<InjectedClassNameType>(Val&: T))
18196 T = ICNT->getDecl()->getCanonicalTemplateSpecializationType(Ctx: Context);
18197
18198 const auto *TST = dyn_cast<TemplateSpecializationType>(Val&: T);
18199 if (!TST)
18200 return nullptr;
18201
18202 TemplateDecl *TD = TST->getTemplateName().getAsTemplateDecl();
18203 if (!TD || isa<ClassTemplateDecl>(Val: TD))
18204 return TST;
18205 return nullptr;
18206}
18207
18208bool Sema::DiagnosePackIndexingInFriendNNS(SourceLocation Loc,
18209 NestedNameSpecifierLoc NNSLoc) {
18210 for (TypeLoc TL = NNSLoc.getAsTypeLoc(); TL;
18211 TL = TL.getPrefix().getAsTypeLoc()) {
18212 if (TL.getTypeLocClass() != TypeLoc::PackIndexing)
18213 continue;
18214
18215 Diag(Loc, DiagID: diag::err_pack_indexing_in_friend) << TL.getSourceRange();
18216 return true;
18217 }
18218 return false;
18219}
18220
18221static void DiagnoseDependentFriendNotMember(Sema &S, SourceLocation Loc,
18222 NestedNameSpecifier NNS) {
18223 QualType T(NNS.getAsType(), 0);
18224 if (const auto *TST =
18225 dyn_cast<TemplateSpecializationType>(Val: IgnorePackIndexing(T))) {
18226 if (isa_and_nonnull<TypeAliasTemplateDecl>(
18227 Val: TST->getTemplateName().getAsTemplateDecl())) {
18228 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec)
18229 << NNS;
18230 return;
18231 }
18232 }
18233
18234 if (NNS.getAsRecordDecl()) {
18235 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member_of_template_spec) << NNS;
18236 } else {
18237 S.Diag(Loc, DiagID: diag::err_dependent_friend_not_member);
18238 }
18239}
18240
18241bool Sema::CheckDependentFriend(SourceLocation Loc,
18242 NestedNameSpecifierLoc NNSLoc,
18243 ArrayRef<TemplateParameterList *> TPLs,
18244 bool IsInstantiation) {
18245 NestedNameSpecifier NNS = NNSLoc.getNestedNameSpecifier();
18246 if (!NNS.isDependent() && !IsInstantiation)
18247 return false;
18248
18249 assert(NNS.getKind() == NestedNameSpecifier::Kind::Type &&
18250 "nested-name-specifier of dependent friend must be a type");
18251
18252 QualType T(NNS.getAsType(), 0);
18253 if (DiagnosePackIndexingInFriendNNS(Loc, NNSLoc))
18254 return true;
18255
18256 const TemplateSpecializationType *TST =
18257 GetClassTemplateSpecializationType(Context, T);
18258 if (!TST) {
18259 DiagnoseDependentFriendNotMember(S&: *this, Loc, NNS);
18260 return true;
18261 }
18262
18263 if (TPLs.empty())
18264 return false;
18265
18266 SmallVector<NamedDecl *, 4> UndeducedParameters;
18267 for (TemplateParameterList *Params : TPLs) {
18268 llvm::SmallBitVector UsedParameters(Params->size());
18269 MarkUsedTemplateParameters(TemplateArgs: TST->template_arguments(),
18270 /*OnlyDeduced=*/true, Depth: Params->getDepth(),
18271 Used&: UsedParameters);
18272
18273 for (unsigned I = 0, N = UsedParameters.size(); I != N; ++I)
18274 if (!UsedParameters[I])
18275 UndeducedParameters.push_back(Elt: Params->getParam(Idx: I));
18276 }
18277
18278 if (UndeducedParameters.empty())
18279 return false;
18280
18281 Diag(Loc, DiagID: diag::err_dependent_friend_undeduced_params)
18282 << (UndeducedParameters.size() > 1) << QualType(TST, 0);
18283
18284 for (NamedDecl *Param : UndeducedParameters) {
18285 if (Param->getDeclName())
18286 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18287 << Param->getDeclName();
18288 else
18289 Diag(Loc: Param->getLocation(), DiagID: diag::note_non_deducible_parameter)
18290 << "(anonymous)";
18291 }
18292
18293 return true;
18294}
18295
18296DeclResult Sema::ActOnTemplatedFriendTag(
18297 Scope *S, SourceLocation FriendLoc, unsigned TagSpec, SourceLocation TagLoc,
18298 CXXScopeSpec &SS, IdentifierInfo *Name, SourceLocation NameLoc,
18299 SourceLocation EllipsisLoc, const ParsedAttributesView &Attr,
18300 MultiTemplateParamsArg TempParamLists, TemplateIdAnnotation *TemplateId) {
18301 TagTypeKind Kind = TypeWithKeyword::getTagTypeKindForTypeSpec(TypeSpec: TagSpec);
18302
18303 bool IsMemberSpecialization = false;
18304 bool Invalid = false;
18305
18306 TemplateParameterList *TemplateParams =
18307 MatchTemplateParametersToScopeSpecifier(DeclStartLoc: TagLoc, DeclLoc: NameLoc, SS, TemplateId,
18308 ParamLists: TempParamLists, /*friend*/ IsFriend: true,
18309 IsMemberSpecialization, Invalid);
18310 if (TemplateId) {
18311 if (Invalid)
18312 return true;
18313
18314 if (TemplateParams) {
18315 Diag(Loc: NameLoc, DiagID: diag::err_not_class_template_specialization) << 0;
18316 return true;
18317 }
18318 }
18319
18320 if (TemplateParams) {
18321 if (TemplateParams->size() > 0) {
18322 if (Invalid)
18323 return true;
18324
18325 if (SS.isEmpty() || !SS.getScopeRep().isDependent()) {
18326 DeclResult Result = CheckClassTemplate(
18327 S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc, Attr,
18328 TemplateParams, AS: AS_public, /*ModulePrivateLoc=*/SourceLocation(),
18329 FriendLoc, NumOuterTemplateParamLists: TempParamLists.size() - 1, OuterTemplateParamLists: TempParamLists.data(),
18330 IsMemberSpecialization);
18331 return Result.get();
18332 }
18333 } else {
18334 // The "template<>" header is extraneous.
18335 Diag(Loc: TemplateParams->getTemplateLoc(), DiagID: diag::err_template_tag_noparams)
18336 << TypeWithKeyword::getTagTypeKindName(Kind) << Name;
18337 }
18338 }
18339
18340 if (Invalid)
18341 return true;
18342
18343 bool IsAllExplicitSpecializations =
18344 llvm::all_of(Range&: TempParamLists, P: [](const TemplateParameterList *List) {
18345 return List->size() == 0;
18346 });
18347
18348 // FIXME: don't ignore attributes.
18349
18350 // If it's explicit specializations all the way down, just forget
18351 // about the template header and build an appropriate non-templated
18352 // friend. TODO: for source fidelity, remember the headers.
18353 NestedNameSpecifierLoc QualifierLoc = SS.getWithLocInContext(Context);
18354 if (!TemplateId && IsAllExplicitSpecializations) {
18355 if (SS.isEmpty()) {
18356 bool Owned = false;
18357 bool IsDependent = false;
18358 return ActOnTag(S, TagSpec, TUK: TagUseKind::Friend, KWLoc: TagLoc, SS, Name, NameLoc,
18359 Attr, AS: AS_public,
18360 /*ModulePrivateLoc=*/SourceLocation(),
18361 TemplateParameterLists: MultiTemplateParamsArg(), OwnedDecl&: Owned, IsDependent,
18362 /*ScopedEnumKWLoc=*/SourceLocation(),
18363 /*ScopedEnumUsesClassTag=*/false,
18364 /*UnderlyingType=*/TypeResult(),
18365 /*IsTypeSpecifier=*/false,
18366 /*IsTemplateParamOrArg=*/false,
18367 /*OOK=*/OffsetOfKind::Outside);
18368 }
18369
18370 TypeSourceInfo *TSI = nullptr;
18371 ElaboratedTypeKeyword Keyword =
18372 TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18373 QualType T = CheckTypenameType(Keyword, KeywordLoc: TagLoc, QualifierLoc, II: *Name,
18374 IILoc: NameLoc, TSI: &TSI, /*DeducedTSTContext=*/true);
18375 if (T.isNull())
18376 return true;
18377
18378 FriendDecl *Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI,
18379 FriendL: FriendLoc, EllipsisLoc);
18380 Friend->setAccess(AS_public);
18381 CurContext->addDecl(D: Friend);
18382 return Friend;
18383 }
18384
18385 assert(SS.isNotEmpty() && "valid templated tag with no SS and no direct?");
18386
18387 ArrayRef<TemplateParameterList *> TPLs = TempParamLists;
18388 if (TemplateParams)
18389 TPLs = TPLs.drop_back();
18390 if (CheckDependentFriend(Loc: TagLoc, NNSLoc: QualifierLoc, TPLs,
18391 /*IsInstantiation=*/false))
18392 return true;
18393
18394 TypeSourceInfo *TSI = nullptr;
18395 if (TemplateId) {
18396 ASTTemplateArgsPtr ParsedArgs(TemplateId->getTemplateArgs(),
18397 TemplateId->NumArgs);
18398 TypeResult ParsedType = ActOnTagTemplateIdType(
18399 TUK: TagUseKind::Friend, TagSpec: static_cast<TypeSpecifierType>(TagSpec), TagLoc, SS,
18400 TemplateKWLoc: TemplateId->TemplateKWLoc, TemplateD: TemplateId->Template, TemplateLoc: NameLoc,
18401 LAngleLoc: TemplateId->LAngleLoc, TemplateArgsIn: ParsedArgs, RAngleLoc: TemplateId->RAngleLoc);
18402 if (ParsedType.isInvalid())
18403 return true;
18404
18405 GetTypeFromParser(Ty: ParsedType.get(), TInfo: &TSI);
18406 } else {
18407 ElaboratedTypeKeyword ETK = TypeWithKeyword::getKeywordForTagTypeKind(Tag: Kind);
18408 QualType T = Context.getDependentNameType(Keyword: ETK, NNS: SS.getScopeRep(), Name);
18409 TSI = Context.CreateTypeSourceInfo(T);
18410
18411 DependentNameTypeLoc TL = TSI->getTypeLoc().castAs<DependentNameTypeLoc>();
18412 TL.setElaboratedKeywordLoc(TagLoc);
18413 TL.setQualifierLoc(QualifierLoc);
18414 TL.setNameLoc(NameLoc);
18415 }
18416
18417 SmallVector<UnexpandedParameterPack, 1> Unexpanded;
18418 collectUnexpandedParameterPacks(TL: TSI->getTypeLoc(), Unexpanded);
18419 if (EllipsisLoc.isInvalid()) {
18420 if (DiagnoseUnexpandedParameterPack(Loc: TagLoc, T: TSI, UPPC: UPPC_FriendDeclaration))
18421 return true;
18422 } else if (Unexpanded.empty()) {
18423 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18424 << TSI->getTypeLoc().getSourceRange();
18425 return true;
18426 } else {
18427 // CWG 2917: a pack expanded by a friend-type-specifier cannot have been
18428 // introduced by the template-declaration containing that specifier.
18429 if (!TempParamLists.empty()) {
18430 unsigned FriendDeclDepth = TempParamLists.front()->getDepth();
18431 for (UnexpandedParameterPack &U : Unexpanded) {
18432 if (std::optional<std::pair<unsigned, unsigned>> DI =
18433 getDepthAndIndex(UPP: U);
18434 DI && DI->first >= FriendDeclDepth) {
18435 auto *ND = dyn_cast<NamedDecl *>(Val&: U.first);
18436 if (!ND)
18437 ND = cast<const TemplateTypeParmType *>(Val&: U.first)->getDecl();
18438 Diag(Loc: U.second, DiagID: diag::friend_template_decl_malformed_pack_expansion)
18439 << ND->getDeclName()
18440 << SourceRange(TSI->getTypeLoc().getBeginLoc(), EllipsisLoc);
18441 return true;
18442 }
18443 }
18444 }
18445 }
18446
18447 FriendDecl *Friend;
18448 if (TempParamLists.empty())
18449 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: NameLoc, Friend: TSI, FriendL: FriendLoc,
18450 EllipsisLoc);
18451 else {
18452 if (CheckTemplateDeclScope(S, TemplateParams: TempParamLists.back()))
18453 return true;
18454
18455 TemplateName FriendTemplate;
18456 if (TemplateParams)
18457 FriendTemplate = Context.getDependentTemplateName(
18458 Name: {SS.getScopeRep(), Name, /*HasTemplateKeyword=*/false});
18459 Friend =
18460 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: NameLoc, Friend: TSI, FriendLoc,
18461 FriendTPLists: TempParamLists, EllipsisLoc, Template: FriendTemplate);
18462 }
18463
18464 Friend->setAccess(AS_public);
18465 CurContext->addDecl(D: Friend);
18466
18467 return Friend;
18468}
18469
18470Decl *Sema::ActOnFriendTypeDecl(Scope *S, const DeclSpec &DS,
18471 MultiTemplateParamsArg TempParams,
18472 SourceLocation EllipsisLoc) {
18473 SourceLocation Loc = DS.getBeginLoc();
18474 SourceLocation FriendLoc = DS.getFriendSpecLoc();
18475
18476 assert(DS.isFriendSpecified());
18477 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18478
18479 // C++ [class.friend]p3:
18480 // A friend declaration that does not declare a function shall have one of
18481 // the following forms:
18482 // friend elaborated-type-specifier ;
18483 // friend simple-type-specifier ;
18484 // friend typename-specifier ;
18485 //
18486 // If the friend keyword isn't first, or if the declarations has any type
18487 // qualifiers, then the declaration doesn't have that form.
18488 if (getLangOpts().CPlusPlus11 && !DS.isFriendSpecifiedFirst())
18489 Diag(Loc: FriendLoc, DiagID: diag::err_friend_not_first_in_declaration);
18490 if (DS.getTypeQualifiers()) {
18491 if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
18492 Diag(Loc: DS.getConstSpecLoc(), DiagID: diag::err_friend_decl_spec) << "const";
18493 if (DS.getTypeQualifiers() & DeclSpec::TQ_volatile)
18494 Diag(Loc: DS.getVolatileSpecLoc(), DiagID: diag::err_friend_decl_spec) << "volatile";
18495 if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
18496 Diag(Loc: DS.getRestrictSpecLoc(), DiagID: diag::err_friend_decl_spec) << "restrict";
18497 if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
18498 Diag(Loc: DS.getAtomicSpecLoc(), DiagID: diag::err_friend_decl_spec) << "_Atomic";
18499 if (DS.getTypeQualifiers() & DeclSpec::TQ_unaligned)
18500 Diag(Loc: DS.getUnalignedSpecLoc(), DiagID: diag::err_friend_decl_spec) << "__unaligned";
18501 }
18502
18503 // Try to convert the decl specifier to a type. This works for
18504 // friend templates because ActOnTag never produces a ClassTemplateDecl
18505 // for a TagUseKind::Friend.
18506 Declarator TheDeclarator(DS, ParsedAttributesView::none(),
18507 DeclaratorContext::Member);
18508 TypeSourceInfo *TSI = GetTypeForDeclarator(D&: TheDeclarator);
18509 QualType T = TSI->getType();
18510 if (TheDeclarator.isInvalidType())
18511 return nullptr;
18512
18513 // If '...' is present, the type must contain an unexpanded parameter
18514 // pack, and vice versa.
18515 bool Invalid = false;
18516 if (EllipsisLoc.isInvalid() &&
18517 DiagnoseUnexpandedParameterPack(Loc, T: TSI, UPPC: UPPC_FriendDeclaration))
18518 return nullptr;
18519 if (EllipsisLoc.isValid() &&
18520 !TSI->getType()->containsUnexpandedParameterPack()) {
18521 Diag(Loc: EllipsisLoc, DiagID: diag::err_pack_expansion_without_parameter_packs)
18522 << TSI->getTypeLoc().getSourceRange();
18523 Invalid = true;
18524 }
18525
18526 if (!T->isElaboratedTypeSpecifier()) {
18527 if (TempParams.size()) {
18528 // C++23 [dcl.pre]p5:
18529 // In a simple-declaration, the optional init-declarator-list can be
18530 // omitted only when declaring a class or enumeration, that is, when
18531 // the decl-specifier-seq contains either a class-specifier, an
18532 // elaborated-type-specifier with a class-key, or an enum-specifier.
18533 //
18534 // The declaration of a template-declaration or explicit-specialization
18535 // is never a member-declaration, so this must be a simple-declaration
18536 // with no init-declarator-list. Therefore, this is ill-formed.
18537 Diag(Loc, DiagID: diag::err_tagless_friend_type_template) << DS.getSourceRange();
18538 return nullptr;
18539 } else if (const RecordDecl *RD = T->getAsRecordDecl()) {
18540 SmallString<16> InsertionText(" ");
18541 InsertionText += RD->getKindName();
18542
18543 Diag(Loc, DiagID: getLangOpts().CPlusPlus11
18544 ? diag::warn_cxx98_compat_unelaborated_friend_type
18545 : diag::ext_unelaborated_friend_type)
18546 << (unsigned)RD->getTagKind() << T
18547 << FixItHint::CreateInsertion(InsertionLoc: getLocForEndOfToken(Loc: FriendLoc),
18548 Code: InsertionText);
18549 } else {
18550 DiagCompat(Loc: FriendLoc, CompatDiagId: diag_compat::nonclass_type_friend)
18551 << T << DS.getSourceRange();
18552 }
18553 }
18554
18555 // C++98 [class.friend]p1: A friend of a class is a function
18556 // or class that is not a member of the class . . .
18557 // This is fixed in DR77, which just barely didn't make the C++03
18558 // deadline. It's also a very silly restriction that seriously
18559 // affects inner classes and which nobody else seems to implement;
18560 // thus we never diagnose it, not even in -pedantic.
18561 //
18562 // But note that we could warn about it: it's always useless to
18563 // friend one of your own members (it's not, however, worthless to
18564 // friend a member of an arbitrary specialization of your template).
18565
18566 Decl *D;
18567 if (!TempParams.empty()) {
18568 if (CheckTemplateDeclScope(S, TemplateParams: TempParams.back()))
18569 return nullptr;
18570
18571 // TODO: Support variadic friend template decls?
18572 D = FriendTemplateDecl::Create(Context, DC: CurContext, Loc, Friend: TSI, FriendLoc,
18573 FriendTPLists: TempParams, EllipsisLoc);
18574 } else
18575 D = FriendDecl::Create(C&: Context, DC: CurContext, L: TSI->getTypeLoc().getBeginLoc(),
18576 Friend: TSI, FriendL: FriendLoc, EllipsisLoc);
18577
18578 if (!D)
18579 return nullptr;
18580
18581 D->setAccess(AS_public);
18582 CurContext->addDecl(D);
18583
18584 if (Invalid)
18585 D->setInvalidDecl();
18586
18587 return D;
18588}
18589
18590NamedDecl *Sema::ActOnFriendFunctionDecl(Scope *S, Declarator &D,
18591 MultiTemplateParamsArg TemplateParams) {
18592 const DeclSpec &DS = D.getDeclSpec();
18593
18594 assert(DS.isFriendSpecified());
18595 assert(DS.getStorageClassSpec() == DeclSpec::SCS_unspecified);
18596
18597 SourceLocation Loc = D.getIdentifierLoc();
18598 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
18599
18600 // C++ [class.friend]p1
18601 // A friend of a class is a function or class....
18602 // Note that this sees through typedefs, which is intended.
18603 // It *doesn't* see through dependent types, which is correct
18604 // according to [temp.arg.type]p3:
18605 // If a declaration acquires a function type through a
18606 // type dependent on a template-parameter and this causes
18607 // a declaration that does not use the syntactic form of a
18608 // function declarator to have a function type, the program
18609 // is ill-formed.
18610 if (!TInfo->getType()->isFunctionType()) {
18611 Diag(Loc, DiagID: diag::err_unexpected_friend);
18612
18613 // It might be worthwhile to try to recover by creating an
18614 // appropriate declaration.
18615 return nullptr;
18616 }
18617
18618 // C++ [namespace.memdef]p3
18619 // - If a friend declaration in a non-local class first declares a
18620 // class or function, the friend class or function is a member
18621 // of the innermost enclosing namespace.
18622 // - The name of the friend is not found by simple name lookup
18623 // until a matching declaration is provided in that namespace
18624 // scope (either before or after the class declaration granting
18625 // friendship).
18626 // - If a friend function is called, its name may be found by the
18627 // name lookup that considers functions from namespaces and
18628 // classes associated with the types of the function arguments.
18629 // - When looking for a prior declaration of a class or a function
18630 // declared as a friend, scopes outside the innermost enclosing
18631 // namespace scope are not considered.
18632
18633 CXXScopeSpec &SS = D.getCXXScopeSpec();
18634 DeclarationNameInfo NameInfo = GetNameForDeclarator(D);
18635 assert(NameInfo.getName());
18636
18637 if (SS.isValid() && DiagnosePackIndexingInFriendNNS(
18638 Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context)))
18639 return nullptr;
18640
18641 // Check for unexpanded parameter packs.
18642 if (DiagnoseUnexpandedParameterPack(Loc, T: TInfo, UPPC: UPPC_FriendDeclaration) ||
18643 DiagnoseUnexpandedParameterPack(NameInfo, UPPC: UPPC_FriendDeclaration) ||
18644 DiagnoseUnexpandedParameterPack(SS, UPPC: UPPC_FriendDeclaration))
18645 return nullptr;
18646
18647 bool isTemplateId = D.getName().getKind() == UnqualifiedIdKind::IK_TemplateId;
18648
18649 if (D.isFunctionDefinition() && SS.isNotEmpty() && !isTemplateId) {
18650 auto Kind = SS.getScopeRep().getKind();
18651 bool IsNamespaceOrGlobal = Kind == NestedNameSpecifier::Kind::Global ||
18652 Kind == NestedNameSpecifier::Kind::Namespace;
18653 if (IsNamespaceOrGlobal) {
18654 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def)
18655 << SS.getScopeRep();
18656 SS.clear();
18657 }
18658 }
18659
18660 // The context we found the declaration in, or in which we should
18661 // create the declaration.
18662 DeclContext *DC;
18663 Scope *DCScope = S;
18664 LookupResult Previous(*this, NameInfo, LookupOrdinaryName,
18665 RedeclarationKind::ForExternalRedeclaration);
18666
18667 // There are five cases here.
18668 // - There's no scope specifier and we're in a local class. Only look
18669 // for functions declared in the immediately-enclosing block scope.
18670 // We recover from invalid scope qualifiers as if they just weren't there.
18671 FunctionDecl *FunctionContainingLocalClass = nullptr;
18672 if ((SS.isInvalid() || !SS.isSet()) &&
18673 (FunctionContainingLocalClass =
18674 cast<CXXRecordDecl>(Val: CurContext)->isLocalClass())) {
18675 // C++11 [class.friend]p11:
18676 // If a friend declaration appears in a local class and the name
18677 // specified is an unqualified name, a prior declaration is
18678 // looked up without considering scopes that are outside the
18679 // innermost enclosing non-class scope. For a friend function
18680 // declaration, if there is no prior declaration, the program is
18681 // ill-formed.
18682
18683 // Find the innermost enclosing non-class scope. This is the block
18684 // scope containing the local class definition (or for a nested class,
18685 // the outer local class).
18686 DCScope = S->getFnParent();
18687
18688 // Look up the function name in the scope.
18689 Previous.clear(Kind: LookupLocalFriendName);
18690 LookupName(R&: Previous, S, /*AllowBuiltinCreation*/false);
18691
18692 if (!Previous.empty()) {
18693 // All possible previous declarations must have the same context:
18694 // either they were declared at block scope or they are members of
18695 // one of the enclosing local classes.
18696 DC = Previous.getRepresentativeDecl()->getDeclContext();
18697 } else {
18698 // This is ill-formed, but provide the context that we would have
18699 // declared the function in, if we were permitted to, for error recovery.
18700 DC = FunctionContainingLocalClass;
18701 }
18702 adjustContextForLocalExternDecl(DC);
18703
18704 // - There's no scope specifier, in which case we just go to the
18705 // appropriate scope and look for a function or function template
18706 // there as appropriate.
18707 } else if (SS.isInvalid() || !SS.isSet()) {
18708 // C++11 [namespace.memdef]p3:
18709 // If the name in a friend declaration is neither qualified nor
18710 // a template-id and the declaration is a function or an
18711 // elaborated-type-specifier, the lookup to determine whether
18712 // the entity has been previously declared shall not consider
18713 // any scopes outside the innermost enclosing namespace.
18714
18715 // Find the appropriate context according to the above.
18716 DC = CurContext;
18717
18718 // Skip class contexts. If someone can cite chapter and verse
18719 // for this behavior, that would be nice --- it's what GCC and
18720 // EDG do, and it seems like a reasonable intent, but the spec
18721 // really only says that checks for unqualified existing
18722 // declarations should stop at the nearest enclosing namespace,
18723 // not that they should only consider the nearest enclosing
18724 // namespace.
18725 while (DC->isRecord())
18726 DC = DC->getParent();
18727
18728 DeclContext *LookupDC = DC->getNonTransparentContext();
18729 while (true) {
18730 LookupQualifiedName(R&: Previous, LookupCtx: LookupDC);
18731
18732 if (!Previous.empty()) {
18733 DC = LookupDC;
18734 break;
18735 }
18736
18737 if (isTemplateId) {
18738 if (isa<TranslationUnitDecl>(Val: LookupDC)) break;
18739 } else {
18740 if (LookupDC->isFileContext()) break;
18741 }
18742 LookupDC = LookupDC->getParent();
18743 }
18744
18745 DCScope = getScopeForDeclContext(S, DC);
18746
18747 // - There's a non-dependent scope specifier, in which case we
18748 // compute it and do a previous lookup there for a function
18749 // or function template.
18750 } else if (!SS.getScopeRep().isDependent()) {
18751 DC = computeDeclContext(SS);
18752 if (!DC) return nullptr;
18753
18754 if (RequireCompleteDeclContext(SS, DC)) return nullptr;
18755
18756 LookupQualifiedName(R&: Previous, LookupCtx: DC);
18757
18758 // C++ [class.friend]p1: A friend of a class is a function or
18759 // class that is not a member of the class . . .
18760 if (DC->Equals(DC: CurContext))
18761 Diag(Loc: DS.getFriendSpecLoc(),
18762 DiagID: getLangOpts().CPlusPlus11 ?
18763 diag::warn_cxx98_compat_friend_is_member :
18764 diag::err_friend_is_member);
18765
18766 // - There's a dependent scope specifier, in which case we use an
18767 // arbitrary context and wait for instantiation.
18768 } else {
18769 DC = CurContext;
18770 assert(isa<CXXRecordDecl>(DC) && "friend declaration not in class?");
18771 }
18772
18773 if (!DC->isRecord()) {
18774 int DiagArg = -1;
18775 switch (D.getName().getKind()) {
18776 case UnqualifiedIdKind::IK_ConstructorTemplateId:
18777 case UnqualifiedIdKind::IK_ConstructorName:
18778 DiagArg = 0;
18779 break;
18780 case UnqualifiedIdKind::IK_DestructorName:
18781 DiagArg = 1;
18782 break;
18783 case UnqualifiedIdKind::IK_ConversionFunctionId:
18784 DiagArg = 2;
18785 break;
18786 case UnqualifiedIdKind::IK_DeductionGuideName:
18787 DiagArg = 3;
18788 break;
18789 case UnqualifiedIdKind::IK_Identifier:
18790 case UnqualifiedIdKind::IK_ImplicitSelfParam:
18791 case UnqualifiedIdKind::IK_LiteralOperatorId:
18792 case UnqualifiedIdKind::IK_OperatorFunctionId:
18793 case UnqualifiedIdKind::IK_TemplateId:
18794 break;
18795 }
18796 // This implies that it has to be an operator or function.
18797 if (DiagArg >= 0) {
18798 Diag(Loc, DiagID: diag::err_introducing_special_friend) << DiagArg;
18799 return nullptr;
18800 }
18801 } else {
18802 CXXRecordDecl *RC = dyn_cast<CXXRecordDecl>(Val: DC);
18803 if (RC->isLambda()) {
18804 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_lambda_decl);
18805 }
18806 }
18807
18808 // FIXME: This is an egregious hack to cope with cases where the scope stack
18809 // does not contain the declaration context, i.e., in an out-of-line
18810 // definition of a class.
18811 Scope FakeDCScope(S, Scope::DeclScope, Diags);
18812 if (!DCScope) {
18813 FakeDCScope.setEntity(DC);
18814 DCScope = &FakeDCScope;
18815 }
18816
18817 bool AddToScope = true;
18818 NamedDecl *ND = ActOnFunctionDeclarator(S: DCScope, D, DC, TInfo, Previous,
18819 TemplateParamLists: TemplateParams, AddToScope);
18820 if (!ND) return nullptr;
18821
18822 assert(ND->getLexicalDeclContext() == CurContext);
18823
18824 // If we performed typo correction, we might have added a scope specifier
18825 // and changed the decl context.
18826 DC = ND->getDeclContext();
18827
18828 // Add the function declaration to the appropriate lookup tables,
18829 // adjusting the redeclarations list as necessary. We don't
18830 // want to do this yet if the friending class is dependent.
18831 //
18832 // Also update the scope-based lookup if the target context's
18833 // lookup context is in lexical scope.
18834 if (!CurContext->isDependentContext()) {
18835 DC = DC->getRedeclContext();
18836 DC->makeDeclVisibleInContext(D: ND);
18837 if (Scope *EnclosingScope = getScopeForDeclContext(S, DC))
18838 PushOnScopeChains(D: ND, S: EnclosingScope, /*AddToContext=*/ false);
18839 }
18840
18841 warnOnReservedIdentifier(D: ND);
18842
18843 if (ND->isInvalidDecl()) {
18844 FriendDecl *Friend = FriendDecl::Create(
18845 C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND, FriendL: DS.getFriendSpecLoc());
18846 Friend->setAccess(AS_public);
18847 Friend->setInvalidDecl();
18848 CurContext->addDecl(D: Friend);
18849 return ND;
18850 }
18851
18852 FunctionDecl *FD = ND->getAsFunction();
18853 assert(FD && "Expected a function declaration!");
18854
18855 ArrayRef<TemplateParameterList *> TPLs = FD->getTemplateParameterLists();
18856 if (!TPLs.empty() && SS.isValid() && CheckTemplateDeclScope(S, TemplateParams: TPLs.back()))
18857 return nullptr;
18858
18859 FriendDecl *Friend;
18860 if (!TPLs.empty() && SS.isValid())
18861 Friend =
18862 FriendTemplateDecl::Create(Context, DC: CurContext, Loc: D.getIdentifierLoc(),
18863 Friend: ND, FriendLoc: DS.getFriendSpecLoc(), FriendTPLists: TPLs);
18864 else
18865 Friend = FriendDecl::Create(C&: Context, DC: CurContext, L: D.getIdentifierLoc(), Friend: ND,
18866 FriendL: DS.getFriendSpecLoc());
18867
18868 Friend->setAccess(AS_public);
18869 CurContext->addDecl(D: Friend);
18870
18871 if (DC->isRecord())
18872 CheckFriendAccess(D: ND);
18873
18874 if (!TemplateParams.empty() && SS.isValid() &&
18875 CheckDependentFriend(Loc: NameInfo.getLoc(), NNSLoc: SS.getWithLocInContext(Context),
18876 TPLs: FD->getTemplateParameterLists(),
18877 /*IsInstantiation=*/false))
18878 return ND;
18879
18880 // C++ [class.friend]p6:
18881 // A function may be defined in a friend declaration of a class if and
18882 // only if the class is a non-local class, and the function name is
18883 // unqualified.
18884 if (D.isFunctionDefinition()) {
18885 // Qualified friend function definition.
18886 if (SS.isNotEmpty()) {
18887 SemaDiagnosticBuilder DB =
18888 Diag(Loc: SS.getRange().getBegin(), DiagID: diag::err_qualified_friend_def);
18889
18890 DB << SS.getScopeRep();
18891
18892 // Friend function defined in a local class.
18893 } else if (FunctionContainingLocalClass) {
18894 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_def_in_local_class);
18895
18896 // Per [basic.pre]p4, a template-id is not a name. Therefore, if we have
18897 // a template-id, the function name is not unqualified because these is
18898 // no name. While the wording requires some reading in-between the
18899 // lines, GCC, MSVC, and EDG all consider a friend function
18900 // specialization definitions to be de facto explicit specialization
18901 // and diagnose them as such.
18902 } else if (isTemplateId) {
18903 Diag(Loc: NameInfo.getBeginLoc(), DiagID: diag::err_friend_specialization_def);
18904 }
18905 }
18906
18907 // C++11 [dcl.fct.default]p4: If a friend declaration specifies a
18908 // default argument expression, that declaration shall be a definition
18909 // and shall be the only declaration of the function or function
18910 // template in the translation unit.
18911 if (functionDeclHasDefaultArgument(FD)) {
18912 // We can't look at FD->getPreviousDecl() because it may not have been set
18913 // if we're in a dependent context. If the function is known to be a
18914 // redeclaration, we will have narrowed Previous down to the right decl.
18915 if (D.isRedeclaration()) {
18916 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_redeclared);
18917 Diag(Loc: Previous.getRepresentativeDecl()->getLocation(),
18918 DiagID: diag::note_previous_declaration);
18919 } else if (!D.isFunctionDefinition())
18920 Diag(Loc: FD->getLocation(), DiagID: diag::err_friend_decl_with_def_arg_must_be_def);
18921 }
18922
18923 return ND;
18924}
18925
18926void Sema::SetDeclDeleted(Decl *Dcl, SourceLocation DelLoc,
18927 StringLiteral *Message) {
18928 AdjustDeclIfTemplate(Decl&: Dcl);
18929
18930 FunctionDecl *Fn = dyn_cast_or_null<FunctionDecl>(Val: Dcl);
18931 if (!Fn) {
18932 Diag(Loc: DelLoc, DiagID: diag::err_deleted_non_function);
18933 return;
18934 }
18935
18936 // Deleted function does not have a body.
18937 Fn->setWillHaveBody(false);
18938
18939 if (const FunctionDecl *Prev = Fn->getPreviousDecl()) {
18940 // Don't consider the implicit declaration we generate for explicit
18941 // specializations. FIXME: Do not generate these implicit declarations.
18942 if ((Prev->getTemplateSpecializationKind() != TSK_ExplicitSpecialization ||
18943 Prev->getPreviousDecl()) &&
18944 !Prev->isDefined()) {
18945 Diag(Loc: DelLoc, DiagID: diag::err_deleted_decl_not_first);
18946 Diag(Loc: Prev->getLocation().isInvalid() ? DelLoc : Prev->getLocation(),
18947 DiagID: Prev->isImplicit() ? diag::note_previous_implicit_declaration
18948 : diag::note_previous_declaration);
18949 // We can't recover from this; the declaration might have already
18950 // been used.
18951 Fn->setInvalidDecl();
18952 return;
18953 }
18954
18955 // To maintain the invariant that functions are only deleted on their first
18956 // declaration, mark the implicitly-instantiated declaration of the
18957 // explicitly-specialized function as deleted instead of marking the
18958 // instantiated redeclaration.
18959 Fn = Fn->getCanonicalDecl();
18960 }
18961
18962 // dllimport/dllexport cannot be deleted.
18963 if (const InheritableAttr *DLLAttr = getDLLAttr(D: Fn)) {
18964 Diag(Loc: Fn->getLocation(), DiagID: diag::err_attribute_dll_deleted) << DLLAttr;
18965 Fn->setInvalidDecl();
18966 }
18967
18968 // C++11 [basic.start.main]p3:
18969 // A program that defines main as deleted [...] is ill-formed.
18970 if (Fn->isMain())
18971 Diag(Loc: DelLoc, DiagID: diag::err_deleted_main);
18972
18973 // C++11 [dcl.fct.def.delete]p4:
18974 // A deleted function is implicitly inline.
18975 Fn->setImplicitlyInline();
18976 Fn->setDeletedAsWritten(D: true, Message);
18977}
18978
18979void Sema::SetDeclDefaulted(Decl *Dcl, SourceLocation DefaultLoc) {
18980 if (!Dcl || Dcl->isInvalidDecl())
18981 return;
18982
18983 auto *FD = dyn_cast<FunctionDecl>(Val: Dcl);
18984 if (!FD) {
18985 if (auto *FTD = dyn_cast<FunctionTemplateDecl>(Val: Dcl)) {
18986 if (FTD->getTemplatedDecl()->getDefaultedFunctionKind().isComparison()) {
18987 Diag(Loc: DefaultLoc, DiagID: diag::err_defaulted_comparison_template);
18988 return;
18989 }
18990 }
18991
18992 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
18993 << getLangOpts().CPlusPlus20;
18994 return;
18995 }
18996
18997 // Reject if this can't possibly be a defaultable function.
18998 FunctionDecl::DefaultedFunctionKind DefKind = FD->getDefaultedFunctionKind();
18999 if (!DefKind &&
19000 // A dependent function that doesn't locally look defaultable can
19001 // still instantiate to a defaultable function if it's a constructor
19002 // or assignment operator.
19003 (!FD->isDependentContext() ||
19004 (!isa<CXXConstructorDecl>(Val: FD) &&
19005 FD->getDeclName().getCXXOverloadedOperator() != OO_Equal))) {
19006 Diag(Loc: DefaultLoc, DiagID: diag::err_default_special_members)
19007 << getLangOpts().CPlusPlus20;
19008 return;
19009 }
19010
19011 // Issue compatibility warning. We already warned if the operator is
19012 // 'operator<=>' when parsing the '<=>' token.
19013 if (DefKind.isComparison() &&
19014 DefKind.asComparison() != DefaultedComparisonKind::ThreeWay) {
19015 DiagCompat(Loc: DefaultLoc, CompatDiagId: diag_compat::defaulted_comparison);
19016 }
19017
19018 FD->setDefaulted();
19019 FD->setExplicitlyDefaulted();
19020 FD->setDefaultLoc(DefaultLoc);
19021
19022 // Defer checking functions that are defaulted in a dependent context.
19023 if (FD->isDependentContext())
19024 return;
19025
19026 // Unset that we will have a body for this function. We might not,
19027 // if it turns out to be trivial, and we don't need this marking now
19028 // that we've marked it as defaulted.
19029 FD->setWillHaveBody(false);
19030
19031 if (DefKind.isComparison()) {
19032 // If this comparison's defaulting occurs within the definition of its
19033 // lexical class context, we have to do the checking when complete.
19034 if (auto const *RD = dyn_cast<CXXRecordDecl>(Val: FD->getLexicalDeclContext()))
19035 if (!RD->isCompleteDefinition())
19036 return;
19037 }
19038
19039 // If this member fn was defaulted on its first declaration, we will have
19040 // already performed the checking in CheckCompletedCXXClass. Such a
19041 // declaration doesn't trigger an implicit definition.
19042 if (isa<CXXMethodDecl>(Val: FD)) {
19043 const FunctionDecl *Primary = FD;
19044 if (const FunctionDecl *Pattern = FD->getTemplateInstantiationPattern())
19045 // Ask the template instantiation pattern that actually had the
19046 // '= default' on it.
19047 Primary = Pattern;
19048 if (Primary->getCanonicalDecl()->isDefaulted())
19049 return;
19050 }
19051
19052 // Only allocate DefaultedOrDeletedFunctionInfo if we actually have
19053 // non-default FP features to stash. This avoids memory overhead for
19054 // the vast majority of defaulted functions.
19055 if (!FD->getDefaultedOrDeletedInfo() &&
19056 CurFPFeatureOverrides().requiresTrailingStorage()) {
19057 FD->setDefaultedOrDeletedInfo(
19058 FunctionDecl::DefaultedOrDeletedFunctionInfo::Create(
19059 Context, /*Lookups=*/{}, FPFeatures: CurFPFeatureOverrides()));
19060 }
19061
19062 if (DefKind.isComparison()) {
19063 if (CheckExplicitlyDefaultedComparison(S: nullptr, FD, DCK: DefKind.asComparison()))
19064 FD->setInvalidDecl();
19065 else
19066 DefineDefaultedComparison(UseLoc: DefaultLoc, FD, DCK: DefKind.asComparison());
19067 } else {
19068 auto *MD = cast<CXXMethodDecl>(Val: FD);
19069
19070 if (CheckExplicitlyDefaultedSpecialMember(MD, CSM: DefKind.asSpecialMember(),
19071 DefaultLoc))
19072 MD->setInvalidDecl();
19073 else
19074 DefineDefaultedFunction(S&: *this, FD: MD, DefaultLoc);
19075 }
19076}
19077
19078static void SearchForReturnInStmt(Sema &Self, Stmt *S) {
19079 for (Stmt *SubStmt : S->children()) {
19080 if (!SubStmt)
19081 continue;
19082 if (isa<ReturnStmt>(Val: SubStmt))
19083 Self.Diag(Loc: SubStmt->getBeginLoc(),
19084 DiagID: diag::err_return_in_constructor_handler);
19085 if (!isa<Expr>(Val: SubStmt))
19086 SearchForReturnInStmt(Self, S: SubStmt);
19087 }
19088}
19089
19090void Sema::DiagnoseReturnInConstructorExceptionHandler(CXXTryStmt *TryBlock) {
19091 for (unsigned I = 0, E = TryBlock->getNumHandlers(); I != E; ++I) {
19092 CXXCatchStmt *Handler = TryBlock->getHandler(i: I);
19093 SearchForReturnInStmt(Self&: *this, S: Handler);
19094 }
19095}
19096
19097void Sema::SetFunctionBodyKind(Decl *D, SourceLocation Loc, FnBodyKind BodyKind,
19098 StringLiteral *DeletedMessage) {
19099 switch (BodyKind) {
19100 case FnBodyKind::Delete:
19101 SetDeclDeleted(Dcl: D, DelLoc: Loc, Message: DeletedMessage);
19102 break;
19103 case FnBodyKind::Default:
19104 SetDeclDefaulted(Dcl: D, DefaultLoc: Loc);
19105 break;
19106 case FnBodyKind::Other:
19107 llvm_unreachable(
19108 "Parsed function body should be '= delete;' or '= default;'");
19109 }
19110}
19111
19112bool Sema::CheckOverridingFunctionAttributes(CXXMethodDecl *New,
19113 const CXXMethodDecl *Old) {
19114 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19115 const auto *OldFT = Old->getType()->castAs<FunctionProtoType>();
19116
19117 if (OldFT->hasExtParameterInfos()) {
19118 for (unsigned I = 0, E = OldFT->getNumParams(); I != E; ++I)
19119 // A parameter of the overriding method should be annotated with noescape
19120 // if the corresponding parameter of the overridden method is annotated.
19121 if (OldFT->getExtParameterInfo(I).isNoEscape() &&
19122 !NewFT->getExtParameterInfo(I).isNoEscape()) {
19123 Diag(Loc: New->getParamDecl(i: I)->getLocation(),
19124 DiagID: diag::warn_overriding_method_missing_noescape);
19125 Diag(Loc: Old->getParamDecl(i: I)->getLocation(),
19126 DiagID: diag::note_overridden_marked_noescape);
19127 }
19128 }
19129
19130 // SME attributes must match when overriding a function declaration.
19131 if (IsInvalidSMECallConversion(FromType: Old->getType(), ToType: New->getType())) {
19132 Diag(Loc: New->getLocation(), DiagID: diag::err_conflicting_overriding_attributes)
19133 << New << New->getType() << Old->getType();
19134 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19135 return true;
19136 }
19137
19138 // Virtual overrides must have the same code_seg.
19139 const auto *OldCSA = Old->getAttr<CodeSegAttr>();
19140 const auto *NewCSA = New->getAttr<CodeSegAttr>();
19141 if ((NewCSA || OldCSA) &&
19142 (!OldCSA || !NewCSA || NewCSA->getName() != OldCSA->getName())) {
19143 Diag(Loc: New->getLocation(), DiagID: diag::err_mismatched_code_seg_override);
19144 Diag(Loc: Old->getLocation(), DiagID: diag::note_previous_declaration);
19145 return true;
19146 }
19147
19148 // Virtual overrides: check for matching effects.
19149 if (Context.hasAnyFunctionEffects()) {
19150 const auto OldFX = Old->getFunctionEffects();
19151 const auto NewFXOrig = New->getFunctionEffects();
19152
19153 if (OldFX != NewFXOrig) {
19154 FunctionEffectSet NewFX(NewFXOrig);
19155 const auto Diffs = FunctionEffectDiffVector(OldFX, NewFX);
19156 FunctionEffectSet::Conflicts Errs;
19157 for (const auto &Diff : Diffs) {
19158 switch (Diff.shouldDiagnoseMethodOverride(OldMethod: *Old, OldFX, NewMethod: *New, NewFX)) {
19159 case FunctionEffectDiff::OverrideResult::NoAction:
19160 break;
19161 case FunctionEffectDiff::OverrideResult::Warn:
19162 Diag(Loc: New->getLocation(), DiagID: diag::warn_conflicting_func_effect_override)
19163 << Diff.effectName();
19164 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19165 << Old->getReturnTypeSourceRange();
19166 break;
19167 case FunctionEffectDiff::OverrideResult::Merge: {
19168 NewFX.insert(NewEC: Diff.Old.value(), Errs);
19169 const auto *NewFT = New->getType()->castAs<FunctionProtoType>();
19170 FunctionProtoType::ExtProtoInfo EPI = NewFT->getExtProtoInfo();
19171 EPI.FunctionEffects = FunctionEffectsRef(NewFX);
19172 QualType ModQT = Context.getFunctionType(ResultTy: NewFT->getReturnType(),
19173 Args: NewFT->getParamTypes(), EPI);
19174 New->setType(ModQT);
19175 if (Errs.empty()) {
19176 // A warning here is somewhat pedantic. Skip this if there was
19177 // already a merge conflict, which is more serious.
19178 Diag(Loc: New->getLocation(), DiagID: diag::warn_mismatched_func_effect_override)
19179 << Diff.effectName();
19180 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19181 << Old->getReturnTypeSourceRange();
19182 }
19183 break;
19184 }
19185 }
19186 }
19187 if (!Errs.empty())
19188 diagnoseFunctionEffectMergeConflicts(Errs, NewLoc: New->getLocation(),
19189 OldLoc: Old->getLocation());
19190 }
19191 }
19192
19193 CallingConv NewCC = NewFT->getCallConv(), OldCC = OldFT->getCallConv();
19194
19195 // If the calling conventions match, everything is fine
19196 if (NewCC == OldCC)
19197 return false;
19198
19199 // If the calling conventions mismatch because the new function is static,
19200 // suppress the calling convention mismatch error; the error about static
19201 // function override (err_static_overrides_virtual from
19202 // Sema::CheckFunctionDeclaration) is more clear.
19203 if (New->getStorageClass() == SC_Static)
19204 return false;
19205
19206 Diag(Loc: New->getLocation(),
19207 DiagID: diag::err_conflicting_overriding_cc_attributes)
19208 << New->getDeclName() << New->getType() << Old->getType();
19209 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19210 return true;
19211}
19212
19213bool Sema::CheckExplicitObjectOverride(CXXMethodDecl *New,
19214 const CXXMethodDecl *Old) {
19215 // CWG2553
19216 // A virtual function shall not be an explicit object member function.
19217 if (!New->isExplicitObjectMemberFunction())
19218 return true;
19219 Diag(Loc: New->getParamDecl(i: 0)->getBeginLoc(),
19220 DiagID: diag::err_explicit_object_parameter_nonmember)
19221 << New->getSourceRange() << /*virtual*/ 1 << /*IsLambda*/ false;
19222 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function);
19223 New->setInvalidDecl();
19224 return false;
19225}
19226
19227bool Sema::CheckOverridingFunctionReturnType(const CXXMethodDecl *New,
19228 const CXXMethodDecl *Old) {
19229 QualType NewTy = New->getType()->castAs<FunctionType>()->getReturnType();
19230 QualType OldTy = Old->getType()->castAs<FunctionType>()->getReturnType();
19231
19232 if (Context.hasSameType(T1: NewTy, T2: OldTy) ||
19233 NewTy->isDependentType() || OldTy->isDependentType())
19234 return false;
19235
19236 // Check if the return types are covariant
19237 QualType NewClassTy, OldClassTy;
19238
19239 /// Both types must be pointers or references to classes.
19240 if (const PointerType *NewPT = NewTy->getAs<PointerType>()) {
19241 if (const PointerType *OldPT = OldTy->getAs<PointerType>()) {
19242 NewClassTy = NewPT->getPointeeType();
19243 OldClassTy = OldPT->getPointeeType();
19244 }
19245 } else if (const ReferenceType *NewRT = NewTy->getAs<ReferenceType>()) {
19246 if (const ReferenceType *OldRT = OldTy->getAs<ReferenceType>()) {
19247 if (NewRT->getTypeClass() == OldRT->getTypeClass()) {
19248 NewClassTy = NewRT->getPointeeType();
19249 OldClassTy = OldRT->getPointeeType();
19250 }
19251 }
19252 }
19253
19254 // The return types aren't either both pointers or references to a class type.
19255 if (NewClassTy.isNull() || !NewClassTy->isStructureOrClassType()) {
19256 Diag(Loc: New->getLocation(),
19257 DiagID: diag::err_different_return_type_for_overriding_virtual_function)
19258 << New->getDeclName() << NewTy << OldTy
19259 << New->getReturnTypeSourceRange();
19260 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19261 << Old->getReturnTypeSourceRange();
19262
19263 return true;
19264 }
19265
19266 if (!Context.hasSameUnqualifiedType(T1: NewClassTy, T2: OldClassTy)) {
19267 // C++14 [class.virtual]p8:
19268 // If the class type in the covariant return type of D::f differs from
19269 // that of B::f, the class type in the return type of D::f shall be
19270 // complete at the point of declaration of D::f or shall be the class
19271 // type D.
19272 if (const auto *RD = NewClassTy->getAsCXXRecordDecl()) {
19273 if (!RD->isBeingDefined() &&
19274 RequireCompleteType(Loc: New->getLocation(), T: NewClassTy,
19275 DiagID: diag::err_covariant_return_incomplete,
19276 Args: New->getDeclName()))
19277 return true;
19278 }
19279
19280 // Check if the new class derives from the old class.
19281 if (!IsDerivedFrom(Loc: New->getLocation(), Derived: NewClassTy, Base: OldClassTy)) {
19282 Diag(Loc: New->getLocation(), DiagID: diag::err_covariant_return_not_derived)
19283 << New->getDeclName() << NewTy << OldTy
19284 << New->getReturnTypeSourceRange();
19285 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19286 << Old->getReturnTypeSourceRange();
19287 return true;
19288 }
19289
19290 // Check if we the conversion from derived to base is valid.
19291 if (CheckDerivedToBaseConversion(
19292 Derived: NewClassTy, Base: OldClassTy,
19293 InaccessibleBaseID: diag::err_covariant_return_inaccessible_base,
19294 AmbiguousBaseConvID: diag::err_covariant_return_ambiguous_derived_to_base_conv,
19295 Loc: New->getLocation(), Range: New->getReturnTypeSourceRange(),
19296 Name: New->getDeclName(), BasePath: nullptr)) {
19297 // FIXME: this note won't trigger for delayed access control
19298 // diagnostics, and it's impossible to get an undelayed error
19299 // here from access control during the original parse because
19300 // the ParsingDeclSpec/ParsingDeclarator are still in scope.
19301 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19302 << Old->getReturnTypeSourceRange();
19303 return true;
19304 }
19305 }
19306
19307 // The qualifiers of the return types must be the same.
19308 if (NewTy.getLocalCVRQualifiers() != OldTy.getLocalCVRQualifiers()) {
19309 Diag(Loc: New->getLocation(),
19310 DiagID: diag::err_covariant_return_type_different_qualifications)
19311 << New->getDeclName() << NewTy << OldTy
19312 << New->getReturnTypeSourceRange();
19313 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19314 << Old->getReturnTypeSourceRange();
19315 return true;
19316 }
19317
19318
19319 // The new class type must have the same or less qualifiers as the old type.
19320 if (!OldClassTy.isAtLeastAsQualifiedAs(other: NewClassTy, Ctx: getASTContext())) {
19321 Diag(Loc: New->getLocation(),
19322 DiagID: diag::err_covariant_return_type_class_type_not_same_or_less_qualified)
19323 << New->getDeclName() << NewTy << OldTy
19324 << New->getReturnTypeSourceRange();
19325 Diag(Loc: Old->getLocation(), DiagID: diag::note_overridden_virtual_function)
19326 << Old->getReturnTypeSourceRange();
19327 return true;
19328 }
19329
19330 return false;
19331}
19332
19333bool Sema::CheckPureMethod(CXXMethodDecl *Method, SourceRange InitRange) {
19334 SourceLocation EndLoc = InitRange.getEnd();
19335 if (EndLoc.isValid())
19336 Method->setRangeEnd(EndLoc);
19337
19338 if (Method->isVirtual() || Method->getParent()->isDependentContext()) {
19339 Method->setIsPureVirtual();
19340 return false;
19341 }
19342
19343 if (!Method->isInvalidDecl())
19344 Diag(Loc: Method->getLocation(), DiagID: diag::err_non_virtual_pure)
19345 << Method->getDeclName() << InitRange;
19346 return true;
19347}
19348
19349void Sema::ActOnPureSpecifier(Decl *D, SourceLocation ZeroLoc) {
19350 if (D->getFriendObjectKind())
19351 Diag(Loc: D->getLocation(), DiagID: diag::err_pure_friend);
19352 else if (auto *M = dyn_cast<CXXMethodDecl>(Val: D))
19353 CheckPureMethod(Method: M, InitRange: ZeroLoc);
19354 else
19355 Diag(Loc: D->getLocation(), DiagID: diag::err_illegal_initializer);
19356}
19357
19358/// Invoked when we are about to parse an initializer for the declaration
19359/// 'Dcl'.
19360///
19361/// After this method is called, according to [C++ 3.4.1p13], if 'Dcl' is a
19362/// static data member of class X, names should be looked up in the scope of
19363/// class X. If the declaration had a scope specifier, a scope will have
19364/// been created and passed in for this purpose. Otherwise, S will be null.
19365void Sema::ActOnCXXEnterDeclInitializer(Scope *S, Decl *D) {
19366 assert(D && !D->isInvalidDecl());
19367
19368 // We will always have a nested name specifier here, but this declaration
19369 // might not be out of line if the specifier names the current namespace:
19370 // extern int n;
19371 // int ::n = 0;
19372 if (S && D->isOutOfLine())
19373 EnterDeclaratorContext(S, DC: D->getDeclContext());
19374
19375 PushExpressionEvaluationContext(
19376 NewContext: ExpressionEvaluationContext::PotentiallyEvaluated, LambdaContextDecl: D,
19377 Type: ExpressionEvaluationContextRecord::EK_VariableInit);
19378}
19379
19380void Sema::ActOnCXXExitDeclInitializer(Scope *S, Decl *D) {
19381 assert(D);
19382
19383 if (S && D->isOutOfLine())
19384 ExitDeclaratorContext(S);
19385
19386 PopExpressionEvaluationContext();
19387}
19388
19389DeclResult Sema::ActOnCXXConditionDeclaration(Scope *S, Declarator &D) {
19390 // C++ 6.4p2:
19391 // The declarator shall not specify a function or an array.
19392 // The type-specifier-seq shall not contain typedef and shall not declare a
19393 // new class or enumeration.
19394 assert(D.getDeclSpec().getStorageClassSpec() != DeclSpec::SCS_typedef &&
19395 "Parser allowed 'typedef' as storage class of condition decl.");
19396
19397 Decl *Dcl = ActOnDeclarator(S, D);
19398 if (!Dcl)
19399 return true;
19400
19401 if (isa<FunctionDecl>(Val: Dcl)) { // The declarator shall not specify a function.
19402 Diag(Loc: Dcl->getLocation(), DiagID: diag::err_invalid_use_of_function_type)
19403 << D.getSourceRange();
19404 return true;
19405 }
19406
19407 if (auto *VD = dyn_cast<VarDecl>(Val: Dcl))
19408 VD->setCXXCondDecl();
19409
19410 return Dcl;
19411}
19412
19413void Sema::LoadExternalVTableUses() {
19414 if (!ExternalSource)
19415 return;
19416
19417 SmallVector<ExternalVTableUse, 4> VTables;
19418 ExternalSource->ReadUsedVTables(VTables);
19419 SmallVector<VTableUse, 4> NewUses;
19420 for (const ExternalVTableUse &VTable : VTables) {
19421 llvm::DenseMap<CXXRecordDecl *, bool>::iterator Pos =
19422 VTablesUsed.find(Val: VTable.Record);
19423 // Even if a definition wasn't required before, it may be required now.
19424 if (Pos != VTablesUsed.end()) {
19425 if (!Pos->second && VTable.DefinitionRequired)
19426 Pos->second = true;
19427 continue;
19428 }
19429
19430 VTablesUsed[VTable.Record] = VTable.DefinitionRequired;
19431 NewUses.push_back(Elt: VTableUse(VTable.Record, VTable.Location));
19432 }
19433
19434 VTableUses.insert(I: VTableUses.begin(), From: NewUses.begin(), To: NewUses.end());
19435}
19436
19437void Sema::MarkVTableUsed(SourceLocation Loc, CXXRecordDecl *Class,
19438 bool DefinitionRequired) {
19439 // Ignore any vtable uses in unevaluated operands or for classes that do
19440 // not have a vtable.
19441 if (!Class->isDynamicClass() || Class->isDependentContext() ||
19442 CurContext->isDependentContext() || isUnevaluatedContext())
19443 return;
19444 // Do not mark as used if compiling for the device outside of the target
19445 // region.
19446 if (TUKind != TU_Prefix && LangOpts.OpenMP && LangOpts.OpenMPIsTargetDevice &&
19447 !OpenMP().isInOpenMPDeclareTargetContext() &&
19448 !OpenMP().isInOpenMPTargetExecutionDirective()) {
19449 if (!DefinitionRequired)
19450 MarkVirtualMembersReferenced(Loc, RD: Class);
19451 return;
19452 }
19453
19454 // Try to insert this class into the map.
19455 LoadExternalVTableUses();
19456 Class = Class->getCanonicalDecl();
19457 std::pair<llvm::DenseMap<CXXRecordDecl *, bool>::iterator, bool>
19458 Pos = VTablesUsed.insert(KV: std::make_pair(x&: Class, y&: DefinitionRequired));
19459 if (!Pos.second) {
19460 // If we already had an entry, check to see if we are promoting this vtable
19461 // to require a definition. If so, we need to reappend to the VTableUses
19462 // list, since we may have already processed the first entry.
19463 if (DefinitionRequired && !Pos.first->second) {
19464 Pos.first->second = true;
19465 } else {
19466 // Otherwise, we can early exit.
19467 return;
19468 }
19469 } else {
19470 // The Microsoft ABI requires that we perform the destructor body
19471 // checks (i.e. operator delete() lookup) when the vtable is marked used, as
19472 // the deleting destructor is emitted with the vtable, not with the
19473 // destructor definition as in the Itanium ABI.
19474 if (Context.getTargetInfo().getCXXABI().isMicrosoft()) {
19475 CXXDestructorDecl *DD = Class->getDestructor();
19476 if (DD && DD->isVirtual() && !DD->isDeleted()) {
19477 if (Class->hasUserDeclaredDestructor() && !DD->isDefined()) {
19478 // If this is an out-of-line declaration, marking it referenced will
19479 // not do anything. Manually call CheckDestructor to look up operator
19480 // delete().
19481 ContextRAII SavedContext(*this, DD);
19482 CheckDestructor(Destructor: DD);
19483 if (!DD->getOperatorDelete())
19484 DD->setInvalidDecl();
19485 } else {
19486 MarkFunctionReferenced(Loc, Func: Class->getDestructor());
19487 }
19488 }
19489 }
19490 }
19491
19492 // Local classes need to have their virtual members marked
19493 // immediately. For all other classes, we mark their virtual members
19494 // at the end of the translation unit.
19495 if (Class->isLocalClass())
19496 MarkVirtualMembersReferenced(Loc, RD: Class->getDefinition());
19497 else
19498 VTableUses.push_back(Elt: std::make_pair(x&: Class, y&: Loc));
19499}
19500
19501bool Sema::DefineUsedVTables() {
19502 LoadExternalVTableUses();
19503 if (VTableUses.empty())
19504 return false;
19505
19506 // Note: The VTableUses vector could grow as a result of marking
19507 // the members of a class as "used", so we check the size each
19508 // time through the loop and prefer indices (which are stable) to
19509 // iterators (which are not).
19510 bool DefinedAnything = false;
19511 for (unsigned I = 0; I != VTableUses.size(); ++I) {
19512 CXXRecordDecl *Class = VTableUses[I].first->getDefinition();
19513 if (!Class)
19514 continue;
19515 TemplateSpecializationKind ClassTSK =
19516 Class->getTemplateSpecializationKind();
19517
19518 SourceLocation Loc = VTableUses[I].second;
19519
19520 bool DefineVTable = true;
19521
19522 const CXXMethodDecl *KeyFunction = Context.getCurrentKeyFunction(RD: Class);
19523 // V-tables for non-template classes with an owning module are always
19524 // uniquely emitted in that module.
19525 if (Class->isInCurrentModuleUnit()) {
19526 DefineVTable = true;
19527 } else if (KeyFunction && !KeyFunction->hasBody()) {
19528 // If this class has a key function, but that key function is
19529 // defined in another translation unit, we don't need to emit the
19530 // vtable even though we're using it.
19531 // The key function is in another translation unit.
19532 DefineVTable = false;
19533 TemplateSpecializationKind TSK =
19534 KeyFunction->getTemplateSpecializationKind();
19535 assert(TSK != TSK_ExplicitInstantiationDefinition &&
19536 TSK != TSK_ImplicitInstantiation &&
19537 "Instantiations don't have key functions");
19538 (void)TSK;
19539 } else if (!KeyFunction) {
19540 // If we have a class with no key function that is the subject
19541 // of an explicit instantiation declaration, suppress the
19542 // vtable; it will live with the explicit instantiation
19543 // definition.
19544 bool IsExplicitInstantiationDeclaration =
19545 ClassTSK == TSK_ExplicitInstantiationDeclaration;
19546 for (auto *R : Class->redecls()) {
19547 TemplateSpecializationKind TSK
19548 = cast<CXXRecordDecl>(Val: R)->getTemplateSpecializationKind();
19549 if (TSK == TSK_ExplicitInstantiationDeclaration)
19550 IsExplicitInstantiationDeclaration = true;
19551 else if (TSK == TSK_ExplicitInstantiationDefinition) {
19552 IsExplicitInstantiationDeclaration = false;
19553 break;
19554 }
19555 }
19556
19557 if (IsExplicitInstantiationDeclaration) {
19558 const bool HasExcludeFromExplicitInstantiation =
19559 llvm::any_of(Range: Class->methods(), P: [](CXXMethodDecl *method) {
19560 // If the class has a member function declared with
19561 // `__attribute__((exclude_from_explicit_instantiation))`, the
19562 // explicit instantiation declaration should not suppress emitting
19563 // the vtable, since the corresponding explicit instantiation
19564 // definition might not emit the vtable if a triggering method is
19565 // excluded.
19566 return method->hasAttr<ExcludeFromExplicitInstantiationAttr>();
19567 });
19568 if (!HasExcludeFromExplicitInstantiation)
19569 DefineVTable = false;
19570 }
19571 }
19572
19573 // The exception specifications for all virtual members may be needed even
19574 // if we are not providing an authoritative form of the vtable in this TU.
19575 // We may choose to emit it available_externally anyway.
19576 if (!DefineVTable) {
19577 MarkVirtualMemberExceptionSpecsNeeded(Loc, RD: Class);
19578 continue;
19579 }
19580
19581 // Mark all of the virtual members of this class as referenced, so
19582 // that we can build a vtable. Then, tell the AST consumer that a
19583 // vtable for this class is required.
19584 DefinedAnything = true;
19585 MarkVirtualMembersReferenced(Loc, RD: Class);
19586 CXXRecordDecl *Canonical = Class->getCanonicalDecl();
19587 // The vtable is assumed to be emitted in an external source only for
19588 // classes attached to a named module, which is guaranteed to have an object
19589 // file. This isn't true for -fmodules-debuginfo, which still has
19590 // shouldEmitInExternalSource as true so that debug info gets supressed.
19591 if (VTablesUsed[Canonical] &&
19592 !(Class->isInNamedModule() && Class->shouldEmitInExternalSource()))
19593 Consumer.HandleVTable(RD: Class);
19594
19595 // Warn if we're emitting a weak vtable. The vtable will be weak if there is
19596 // no key function or the key function is inlined. Don't warn in C++ ABIs
19597 // that lack key functions, since the user won't be able to make one.
19598 if (Context.getTargetInfo().getCXXABI().hasKeyFunctions() &&
19599 Class->isExternallyVisible() &&
19600 !(Class->getOwningModule() &&
19601 Class->getOwningModule()->isInterfaceOrPartition()) &&
19602 ClassTSK != TSK_ImplicitInstantiation &&
19603 ClassTSK != TSK_ExplicitInstantiationDeclaration &&
19604 ClassTSK != TSK_ExplicitInstantiationDefinition) {
19605 const FunctionDecl *KeyFunctionDef = nullptr;
19606 if (!KeyFunction || (KeyFunction->hasBody(Definition&: KeyFunctionDef) &&
19607 KeyFunctionDef->isInlined()))
19608 Diag(Loc: Class->getLocation(), DiagID: diag::warn_weak_vtable) << Class;
19609 }
19610 }
19611 VTableUses.clear();
19612
19613 return DefinedAnything;
19614}
19615
19616void Sema::MarkVirtualMemberExceptionSpecsNeeded(SourceLocation Loc,
19617 const CXXRecordDecl *RD) {
19618 for (const auto *I : RD->methods())
19619 if (I->isVirtual() && !I->isPureVirtual())
19620 ResolveExceptionSpec(Loc, FPT: I->getType()->castAs<FunctionProtoType>());
19621}
19622
19623void Sema::MarkVirtualMembersReferenced(SourceLocation Loc,
19624 const CXXRecordDecl *RD,
19625 bool ConstexprOnly) {
19626 // Mark all functions which will appear in RD's vtable as used.
19627 CXXFinalOverriderMap FinalOverriders;
19628 RD->getFinalOverriders(FinaOverriders&: FinalOverriders);
19629 for (const auto &FinalOverrider : FinalOverriders) {
19630 for (const auto &OverridingMethod : FinalOverrider.second) {
19631 assert(OverridingMethod.second.size() > 0 && "no final overrider");
19632 CXXMethodDecl *Overrider = OverridingMethod.second.front().Method;
19633
19634 // C++ [basic.def.odr]p2:
19635 // [...] A virtual member function is used if it is not pure. [...]
19636 if (!Overrider->isPureVirtual() &&
19637 (!ConstexprOnly || Overrider->isConstexpr()))
19638 MarkFunctionReferenced(Loc, Func: Overrider);
19639 }
19640 }
19641
19642 // Only classes that have virtual bases need a VTT.
19643 if (RD->getNumVBases() == 0)
19644 return;
19645
19646 for (const auto &I : RD->bases()) {
19647 const auto *Base = I.getType()->castAsCXXRecordDecl();
19648 if (Base->getNumVBases() == 0)
19649 continue;
19650 MarkVirtualMembersReferenced(Loc, RD: Base);
19651 }
19652}
19653
19654static
19655void DelegatingCycleHelper(CXXConstructorDecl* Ctor,
19656 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Valid,
19657 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Invalid,
19658 llvm::SmallPtrSet<CXXConstructorDecl*, 4> &Current,
19659 Sema &S) {
19660 if (Ctor->isInvalidDecl())
19661 return;
19662
19663 CXXConstructorDecl *Target = Ctor->getTargetConstructor();
19664
19665 // Target may not be determinable yet, for instance if this is a dependent
19666 // call in an uninstantiated template.
19667 if (Target) {
19668 const FunctionDecl *FNTarget = nullptr;
19669 (void)Target->hasBody(Definition&: FNTarget);
19670 Target = const_cast<CXXConstructorDecl*>(
19671 cast_or_null<CXXConstructorDecl>(Val: FNTarget));
19672 }
19673
19674 CXXConstructorDecl *Canonical = Ctor->getCanonicalDecl(),
19675 // Avoid dereferencing a null pointer here.
19676 *TCanonical = Target? Target->getCanonicalDecl() : nullptr;
19677
19678 if (!Current.insert(Ptr: Canonical).second)
19679 return;
19680
19681 // We know that beyond here, we aren't chaining into a cycle.
19682 if (!Target || !Target->isDelegatingConstructor() ||
19683 Target->isInvalidDecl() || Valid.count(Ptr: TCanonical)) {
19684 Valid.insert_range(R&: Current);
19685 Current.clear();
19686 // We've hit a cycle.
19687 } else if (TCanonical == Canonical || Invalid.count(Ptr: TCanonical) ||
19688 Current.count(Ptr: TCanonical)) {
19689 // If we haven't diagnosed this cycle yet, do so now.
19690 if (!Invalid.count(Ptr: TCanonical)) {
19691 S.Diag(Loc: (*Ctor->init_begin())->getSourceLocation(),
19692 DiagID: diag::warn_delegating_ctor_cycle)
19693 << Ctor;
19694
19695 // Don't add a note for a function delegating directly to itself.
19696 if (TCanonical != Canonical)
19697 S.Diag(Loc: Target->getLocation(), DiagID: diag::note_it_delegates_to);
19698
19699 CXXConstructorDecl *C = Target;
19700 while (C->getCanonicalDecl() != Canonical) {
19701 const FunctionDecl *FNTarget = nullptr;
19702 (void)C->getTargetConstructor()->hasBody(Definition&: FNTarget);
19703 assert(FNTarget && "Ctor cycle through bodiless function");
19704
19705 C = const_cast<CXXConstructorDecl*>(
19706 cast<CXXConstructorDecl>(Val: FNTarget));
19707 S.Diag(Loc: C->getLocation(), DiagID: diag::note_which_delegates_to);
19708 }
19709 }
19710
19711 Invalid.insert_range(R&: Current);
19712 Current.clear();
19713 } else {
19714 DelegatingCycleHelper(Ctor: Target, Valid, Invalid, Current, S);
19715 }
19716}
19717
19718
19719void Sema::CheckDelegatingCtorCycles() {
19720 llvm::SmallPtrSet<CXXConstructorDecl*, 4> Valid, Invalid, Current;
19721
19722 for (DelegatingCtorDeclsType::iterator
19723 I = DelegatingCtorDecls.begin(source: ExternalSource.get()),
19724 E = DelegatingCtorDecls.end();
19725 I != E; ++I)
19726 DelegatingCycleHelper(Ctor: *I, Valid, Invalid, Current, S&: *this);
19727
19728 for (CXXConstructorDecl *CI : Invalid)
19729 CI->setInvalidDecl();
19730}
19731
19732namespace {
19733 /// AST visitor that finds references to the 'this' expression.
19734class FindCXXThisExpr : public DynamicRecursiveASTVisitor {
19735 Sema &S;
19736
19737public:
19738 explicit FindCXXThisExpr(Sema &S) : S(S) {}
19739
19740 bool VisitCXXThisExpr(CXXThisExpr *E) override {
19741 S.Diag(Loc: E->getLocation(), DiagID: diag::err_this_static_member_func)
19742 << E->isImplicit();
19743 return false;
19744 }
19745};
19746}
19747
19748bool Sema::checkThisInStaticMemberFunctionType(CXXMethodDecl *Method) {
19749 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19750 if (!TSInfo)
19751 return false;
19752
19753 TypeLoc TL = TSInfo->getTypeLoc();
19754 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19755 if (!ProtoTL)
19756 return false;
19757
19758 // C++11 [expr.prim.general]p3:
19759 // [The expression this] shall not appear before the optional
19760 // cv-qualifier-seq and it shall not appear within the declaration of a
19761 // static member function (although its type and value category are defined
19762 // within a static member function as they are within a non-static member
19763 // function). [ Note: this is because declaration matching does not occur
19764 // until the complete declarator is known. - end note ]
19765 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19766 FindCXXThisExpr Finder(*this);
19767
19768 // If the return type came after the cv-qualifier-seq, check it now.
19769 if (Proto->hasTrailingReturn() &&
19770 !Finder.TraverseTypeLoc(TL: ProtoTL.getReturnLoc()))
19771 return true;
19772
19773 // Check the exception specification.
19774 if (checkThisInStaticMemberFunctionExceptionSpec(Method))
19775 return true;
19776
19777 // Check the trailing requires clause
19778 if (const AssociatedConstraint &TRC = Method->getTrailingRequiresClause())
19779 if (!Finder.TraverseStmt(S: const_cast<Expr *>(TRC.ConstraintExpr)))
19780 return true;
19781
19782 return checkThisInStaticMemberFunctionAttributes(Method);
19783}
19784
19785bool Sema::checkThisInStaticMemberFunctionExceptionSpec(CXXMethodDecl *Method) {
19786 TypeSourceInfo *TSInfo = Method->getTypeSourceInfo();
19787 if (!TSInfo)
19788 return false;
19789
19790 TypeLoc TL = TSInfo->getTypeLoc();
19791 FunctionProtoTypeLoc ProtoTL = TL.getAs<FunctionProtoTypeLoc>();
19792 if (!ProtoTL)
19793 return false;
19794
19795 const FunctionProtoType *Proto = ProtoTL.getTypePtr();
19796 FindCXXThisExpr Finder(*this);
19797
19798 switch (Proto->getExceptionSpecType()) {
19799 case EST_Unparsed:
19800 case EST_Uninstantiated:
19801 case EST_Unevaluated:
19802 case EST_BasicNoexcept:
19803 case EST_NoThrow:
19804 case EST_DynamicNone:
19805 case EST_MSAny:
19806 case EST_None:
19807 break;
19808
19809 case EST_DependentNoexcept:
19810 case EST_NoexceptFalse:
19811 case EST_NoexceptTrue:
19812 if (!Finder.TraverseStmt(S: Proto->getNoexceptExpr()))
19813 return true;
19814 [[fallthrough]];
19815
19816 case EST_Dynamic:
19817 for (const auto &E : Proto->exceptions()) {
19818 if (!Finder.TraverseType(T: E))
19819 return true;
19820 }
19821 break;
19822 }
19823
19824 return false;
19825}
19826
19827bool Sema::checkThisInStaticMemberFunctionAttributes(CXXMethodDecl *Method) {
19828 FindCXXThisExpr Finder(*this);
19829
19830 // Check attributes.
19831 for (const auto *A : Method->attrs()) {
19832 // FIXME: This should be emitted by tblgen.
19833 Expr *Arg = nullptr;
19834 ArrayRef<Expr *> Args;
19835 if (const auto *G = dyn_cast<GuardedByAttr>(Val: A))
19836 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19837 else if (const auto *G = dyn_cast<PtGuardedByAttr>(Val: A))
19838 Args = llvm::ArrayRef(G->args_begin(), G->args_size());
19839 else if (const auto *AA = dyn_cast<AcquiredAfterAttr>(Val: A))
19840 Args = llvm::ArrayRef(AA->args_begin(), AA->args_size());
19841 else if (const auto *AB = dyn_cast<AcquiredBeforeAttr>(Val: A))
19842 Args = llvm::ArrayRef(AB->args_begin(), AB->args_size());
19843 else if (const auto *LR = dyn_cast<LockReturnedAttr>(Val: A))
19844 Arg = LR->getArg();
19845 else if (const auto *LE = dyn_cast<LocksExcludedAttr>(Val: A))
19846 Args = llvm::ArrayRef(LE->args_begin(), LE->args_size());
19847 else if (const auto *RC = dyn_cast<RequiresCapabilityAttr>(Val: A))
19848 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19849 else if (const auto *AC = dyn_cast<AcquireCapabilityAttr>(Val: A))
19850 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19851 else if (const auto *AC = dyn_cast<TryAcquireCapabilityAttr>(Val: A)) {
19852 Arg = AC->getSuccessValue();
19853 Args = llvm::ArrayRef(AC->args_begin(), AC->args_size());
19854 } else if (const auto *RC = dyn_cast<ReleaseCapabilityAttr>(Val: A))
19855 Args = llvm::ArrayRef(RC->args_begin(), RC->args_size());
19856
19857 if (Arg && !Finder.TraverseStmt(S: Arg))
19858 return true;
19859
19860 for (Expr *A : Args) {
19861 if (!Finder.TraverseStmt(S: A))
19862 return true;
19863 }
19864 }
19865
19866 return false;
19867}
19868
19869void Sema::checkExceptionSpecification(
19870 bool IsTopLevel, ExceptionSpecificationType EST,
19871 ArrayRef<ParsedType> DynamicExceptions,
19872 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr,
19873 SmallVectorImpl<QualType> &Exceptions,
19874 FunctionProtoType::ExceptionSpecInfo &ESI) {
19875 Exceptions.clear();
19876 ESI.Type = EST;
19877 if (EST == EST_Dynamic) {
19878 Exceptions.reserve(N: DynamicExceptions.size());
19879 for (unsigned ei = 0, ee = DynamicExceptions.size(); ei != ee; ++ei) {
19880 // FIXME: Preserve type source info.
19881 QualType ET = GetTypeFromParser(Ty: DynamicExceptions[ei]);
19882
19883 if (IsTopLevel) {
19884 SmallVector<UnexpandedParameterPack, 2> Unexpanded;
19885 collectUnexpandedParameterPacks(T: ET, Unexpanded);
19886 if (!Unexpanded.empty()) {
19887 DiagnoseUnexpandedParameterPacks(
19888 Loc: DynamicExceptionRanges[ei].getBegin(), UPPC: UPPC_ExceptionType,
19889 Unexpanded);
19890 continue;
19891 }
19892 }
19893
19894 // Check that the type is valid for an exception spec, and
19895 // drop it if not.
19896 if (!CheckSpecifiedExceptionType(T&: ET, Range: DynamicExceptionRanges[ei]))
19897 Exceptions.push_back(Elt: ET);
19898 }
19899 ESI.Exceptions = Exceptions;
19900 return;
19901 }
19902
19903 if (isComputedNoexcept(ESpecType: EST)) {
19904 assert((NoexceptExpr->isTypeDependent() ||
19905 NoexceptExpr->getType()->getCanonicalTypeUnqualified() ==
19906 Context.BoolTy) &&
19907 "Parser should have made sure that the expression is boolean");
19908 if (IsTopLevel && DiagnoseUnexpandedParameterPack(E: NoexceptExpr)) {
19909 ESI.Type = EST_BasicNoexcept;
19910 return;
19911 }
19912
19913 ESI.NoexceptExpr = NoexceptExpr;
19914 return;
19915 }
19916}
19917
19918void Sema::actOnDelayedExceptionSpecification(
19919 Decl *D, ExceptionSpecificationType EST, SourceRange SpecificationRange,
19920 ArrayRef<ParsedType> DynamicExceptions,
19921 ArrayRef<SourceRange> DynamicExceptionRanges, Expr *NoexceptExpr) {
19922 if (!D)
19923 return;
19924
19925 // Dig out the function we're referring to.
19926 if (FunctionTemplateDecl *FTD = dyn_cast<FunctionTemplateDecl>(Val: D))
19927 D = FTD->getTemplatedDecl();
19928
19929 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: D);
19930 if (!FD)
19931 return;
19932
19933 // Check the exception specification.
19934 llvm::SmallVector<QualType, 4> Exceptions;
19935 FunctionProtoType::ExceptionSpecInfo ESI;
19936 checkExceptionSpecification(/*IsTopLevel=*/true, EST, DynamicExceptions,
19937 DynamicExceptionRanges, NoexceptExpr, Exceptions,
19938 ESI);
19939
19940 // Update the exception specification on the function type.
19941 Context.adjustExceptionSpec(FD, ESI, /*AsWritten=*/true);
19942
19943 if (CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(Val: D)) {
19944 if (MD->isStatic())
19945 checkThisInStaticMemberFunctionExceptionSpec(Method: MD);
19946
19947 if (MD->isVirtual()) {
19948 // Check overrides, which we previously had to delay.
19949 for (const CXXMethodDecl *O : MD->overridden_methods())
19950 CheckOverridingFunctionExceptionSpec(New: MD, Old: O);
19951 }
19952 }
19953}
19954
19955/// HandleMSProperty - Analyze a __delcspec(property) field of a C++ class.
19956///
19957MSPropertyDecl *Sema::HandleMSProperty(Scope *S, RecordDecl *Record,
19958 SourceLocation DeclStart, Declarator &D,
19959 Expr *BitWidth,
19960 InClassInitStyle InitStyle,
19961 AccessSpecifier AS,
19962 const ParsedAttr &MSPropertyAttr) {
19963 const IdentifierInfo *II = D.getIdentifier();
19964 if (!II) {
19965 Diag(Loc: DeclStart, DiagID: diag::err_anonymous_property);
19966 return nullptr;
19967 }
19968 SourceLocation Loc = D.getIdentifierLoc();
19969
19970 TypeSourceInfo *TInfo = GetTypeForDeclarator(D);
19971 QualType T = TInfo->getType();
19972 if (getLangOpts().CPlusPlus) {
19973 CheckExtraCXXDefaultArguments(D);
19974
19975 if (DiagnoseUnexpandedParameterPack(Loc: D.getIdentifierLoc(), T: TInfo,
19976 UPPC: UPPC_DataMemberType)) {
19977 D.setInvalidType();
19978 T = Context.IntTy;
19979 TInfo = Context.getTrivialTypeSourceInfo(T, Loc);
19980 }
19981 }
19982
19983 DiagnoseFunctionSpecifiers(DS: D.getDeclSpec());
19984
19985 if (D.getDeclSpec().isInlineSpecified())
19986 Diag(Loc: D.getDeclSpec().getInlineSpecLoc(), DiagID: diag::err_inline_non_function)
19987 << getLangOpts().CPlusPlus17;
19988 if (DeclSpec::TSCS TSCS = D.getDeclSpec().getThreadStorageClassSpec())
19989 Diag(Loc: D.getDeclSpec().getThreadStorageClassSpecLoc(),
19990 DiagID: diag::err_invalid_thread)
19991 << DeclSpec::getSpecifierName(S: TSCS);
19992
19993 // Check to see if this name was declared as a member previously
19994 NamedDecl *PrevDecl = nullptr;
19995 LookupResult Previous(*this, II, Loc, LookupMemberName,
19996 RedeclarationKind::ForVisibleRedeclaration);
19997 LookupName(R&: Previous, S);
19998 switch (Previous.getResultKind()) {
19999 case LookupResultKind::Found:
20000 case LookupResultKind::FoundUnresolvedValue:
20001 PrevDecl = Previous.getAsSingle<NamedDecl>();
20002 break;
20003
20004 case LookupResultKind::FoundOverloaded:
20005 PrevDecl = Previous.getRepresentativeDecl();
20006 break;
20007
20008 case LookupResultKind::NotFound:
20009 case LookupResultKind::NotFoundInCurrentInstantiation:
20010 case LookupResultKind::Ambiguous:
20011 break;
20012 }
20013
20014 if (PrevDecl && PrevDecl->isTemplateParameter()) {
20015 // Maybe we will complain about the shadowed template parameter.
20016 DiagnoseTemplateParameterShadow(Loc: D.getIdentifierLoc(), PrevDecl);
20017 // Just pretend that we didn't see the previous declaration.
20018 PrevDecl = nullptr;
20019 }
20020
20021 if (PrevDecl && !isDeclInScope(D: PrevDecl, Ctx: Record, S))
20022 PrevDecl = nullptr;
20023
20024 SourceLocation TSSL = D.getBeginLoc();
20025 MSPropertyDecl *NewPD =
20026 MSPropertyDecl::Create(C&: Context, DC: Record, L: Loc, N: II, T, TInfo, StartL: TSSL,
20027 Getter: MSPropertyAttr.getPropertyDataGetter(),
20028 Setter: MSPropertyAttr.getPropertyDataSetter());
20029 ProcessDeclAttributes(S: TUScope, D: NewPD, PD: D);
20030 NewPD->setAccess(AS);
20031
20032 if (NewPD->isInvalidDecl())
20033 Record->setInvalidDecl();
20034
20035 if (D.getDeclSpec().isModulePrivateSpecified())
20036 NewPD->setModulePrivate();
20037
20038 if (NewPD->isInvalidDecl() && PrevDecl) {
20039 // Don't introduce NewFD into scope; there's already something
20040 // with the same name in the same scope.
20041 } else if (II) {
20042 PushOnScopeChains(D: NewPD, S);
20043 } else
20044 Record->addDecl(D: NewPD);
20045
20046 return NewPD;
20047}
20048
20049void Sema::ActOnStartFunctionDeclarationDeclarator(
20050 Declarator &Declarator, unsigned TemplateParameterDepth) {
20051 auto &Info = InventedParameterInfos.emplace_back();
20052 TemplateParameterList *ExplicitParams = nullptr;
20053 ArrayRef<TemplateParameterList *> ExplicitLists =
20054 Declarator.getTemplateParameterLists();
20055 if (!ExplicitLists.empty()) {
20056 bool IsMemberSpecialization, IsInvalid;
20057 ExplicitParams = MatchTemplateParametersToScopeSpecifier(
20058 DeclStartLoc: Declarator.getBeginLoc(), DeclLoc: Declarator.getIdentifierLoc(),
20059 SS: Declarator.getCXXScopeSpec(), /*TemplateId=*/nullptr,
20060 ParamLists: ExplicitLists, /*IsFriend=*/false, IsMemberSpecialization, Invalid&: IsInvalid,
20061 /*SuppressDiagnostic=*/true);
20062 }
20063 // C++23 [dcl.fct]p23:
20064 // An abbreviated function template can have a template-head. The invented
20065 // template-parameters are appended to the template-parameter-list after
20066 // the explicitly declared template-parameters.
20067 //
20068 // A template-head must have one or more template-parameters (read:
20069 // 'template<>' is *not* a template-head). Only append the invented
20070 // template parameters if we matched the nested-name-specifier to a non-empty
20071 // TemplateParameterList.
20072 if (ExplicitParams && !ExplicitParams->empty()) {
20073 Info.AutoTemplateParameterDepth = ExplicitParams->getDepth();
20074 llvm::append_range(C&: Info.TemplateParams, R&: *ExplicitParams);
20075 Info.NumExplicitTemplateParams = ExplicitParams->size();
20076 } else {
20077 Info.AutoTemplateParameterDepth = TemplateParameterDepth;
20078 Info.NumExplicitTemplateParams = 0;
20079 }
20080}
20081
20082void Sema::ActOnFinishFunctionDeclarationDeclarator(Declarator &Declarator) {
20083 auto &FSI = InventedParameterInfos.back();
20084 if (FSI.TemplateParams.size() > FSI.NumExplicitTemplateParams) {
20085 if (FSI.NumExplicitTemplateParams != 0) {
20086 TemplateParameterList *ExplicitParams =
20087 Declarator.getTemplateParameterLists().back();
20088 Declarator.setInventedTemplateParameterList(
20089 TemplateParameterList::Create(
20090 C: Context, TemplateLoc: ExplicitParams->getTemplateLoc(),
20091 LAngleLoc: ExplicitParams->getLAngleLoc(), Params: FSI.TemplateParams,
20092 RAngleLoc: ExplicitParams->getRAngleLoc(),
20093 RequiresClause: ExplicitParams->getRequiresClause()));
20094 } else {
20095 Declarator.setInventedTemplateParameterList(TemplateParameterList::Create(
20096 C: Context, TemplateLoc: Declarator.getBeginLoc(), LAngleLoc: SourceLocation(),
20097 Params: FSI.TemplateParams, RAngleLoc: Declarator.getEndLoc(),
20098 /*RequiresClause=*/nullptr));
20099 }
20100 }
20101 InventedParameterInfos.pop_back();
20102}
20103
20104bool Sema::BuildCtorClosureDefaultArgs(SourceLocation Loc,
20105 CXXConstructorDecl *Ctor, bool IsCopy) {
20106 assert(Context.getTargetInfo().getCXXABI().isMicrosoft());
20107
20108 if (!Ctor->getCtorClosureDefaultArgs().empty()) {
20109 // If we build args for default constructor closures, those will have
20110 // been generated *before* building args for any copy constructor closures.
20111 assert(IsCopy || Ctor->getCtorClosureDefaultArgs()[0] != nullptr);
20112 return false;
20113 }
20114
20115 unsigned NumParams = Ctor->getNumParams();
20116 if (NumParams == 0)
20117 return false;
20118
20119 CXXDefaultArgExpr **Args =
20120 new (getASTContext()) CXXDefaultArgExpr *[NumParams];
20121
20122 if (IsCopy)
20123 Args[0] = nullptr; // Copy ctor closure will provide the first argument.
20124
20125 for (unsigned I = IsCopy ? 1 : 0; I != NumParams; ++I) {
20126 ExprResult R = BuildCXXDefaultArgExpr(CallLoc: Loc, FD: Ctor, Param: Ctor->getParamDecl(i: I));
20127 CleanupVarDeclMarking();
20128 if (R.isInvalid())
20129 return true;
20130 Args[I] = cast<CXXDefaultArgExpr>(Val: R.get());
20131 }
20132
20133 Ctor->setCtorClosureDefaultArgs(ArrayRef(Args, NumParams));
20134 return false;
20135}
20136